<?php
namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AccountType;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class SuperAdminAccountTypeController extends Controller
{
    public function index()
    {
        return view('superadmin.master.accounttype');
    }

    public function list()
    {
        $types = AccountType::select('id', 'accounttype')->get();
        return response()->json(['data' => $types]);
    }

    public function show(AccountType $accounttype)
    {
        // Return single account type for edit
        return response()->json($accounttype);
    }

    public function store_old(Request $request)
    {
        $request->validate(['account_type' => 'required']);
        AccountType::create(['accounttype' => $request->account_type]);
        return response()->json(['success' => true, 'message' => 'Account Type added']);
    }
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'account_type' => 'required|unique:account_types,accounttype',
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        AccountType::create(['accounttype' => $request->account_type]);
    
        return response()->json(['success' => true, 'message' => 'Account Type added']);
    }

    public function update_old(Request $request, AccountType $accounttype)
    {
        $request->validate(['account_type' => 'required']);
        $accounttype->update(['accounttype' => $request->account_type]);
        return response()->json(['success' => true, 'message' => 'Account Type updated']);
    }
    
    public function update(Request $request, AccountType $accounttype)
    {
        $validator = Validator::make($request->all(), [
            'account_type' => [
                'required',
                Rule::unique('account_types', 'accounttype')->ignore($accounttype->id),
            ],
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        $accounttype->update(['accounttype' => $request->account_type]);
    
        return response()->json(['success' => true, 'message' => 'Account Type updated']);
    }

    public function delete(AccountType $accounttype)
    {
        $accounttype->delete();
        return response()->json(['success' => true, 'message' => 'Account Type deleted']);
    }
}
