<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\AccountType;

class AccountTypeController extends Controller
{
    public function index()
    {
        $account_types = AccountType::orderBy('name')->get();
        return view('accounts.account-types.create', compact('account_types'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:account_types,name',
        ]);

        $code = Str::slug($request->name);

        if ($request->filled('id')) {
            $type = AccountType::find($request->id);
            if ($type) {
                $request->validate([
                    'name' => 'required|string|max:255|unique:account_types,name,' . $type->id,
                ]);
                $type->update(['name' => $request->name, 'code' => $code]);
                return redirect()->back()->with('success', 'Account type updated successfully.');
            }
        }

        AccountType::create(['name' => $request->name, 'code' => $code]);
        return redirect()->back()->with('success', 'Account type created successfully.');
    }

    public function update(Request $request, AccountType $accountType)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:account_types,name,' . $accountType->id,
        ]);
        $code = Str::slug($request->name);
        $accountType->update(['name' => $request->name, 'code' => $code]);
        return redirect()->back()->with('success', 'Account type updated successfully.');
    }

    public function destroy($id)
    {
        $type = AccountType::findOrFail($id);
        $type->delete();
        return redirect()->back()->with('success', 'Account type deleted successfully.');
    }
}
