<?php

namespace App\Http\Controllers;

use App\Models\AccountType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

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

    public function create()
    {
        return view('modules.edit.account-types-create');
    }

    public function show($id)
    {
        $accountType = AccountType::findOrFail($id);
        return view('modules.edit.account-types-show', compact('accountType'));
    }

    public function editForm($id)
    {
        $accountType = AccountType::findOrFail($id);
        return view('modules.edit.account-types-edit', compact('accountType'));
    }

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

        AccountType::create([
            'code' => $request->code,
            'name' => $request->name,
            'description' => $request->description,
            'created_by' => auth()->id(),
            'updated_by' => auth()->id(),
        ]);

        Session::flash('success', 'Account type created successfully.');
        return redirect()->route('account_types.index');
    }

    public function edit(Request $request)
    {
        $request->validate([
            'id' => 'required|integer',
            'code' => 'required|string|max:50|unique:account_types,code,' . $request->id . ',id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        $accountType = AccountType::findOrFail($request->id);
        $accountType->update([
            'code' => $request->code,
            'name' => $request->name,
            'description' => $request->description,
            'updated_by' => auth()->id(),
        ]);

        Session::flash('success', 'Account type updated successfully.');
        return redirect()->route('account_types.index');
    }

    public function destroy($id)
    {
        $accountType = AccountType::findOrFail($id);
        $accountType->delete();

        Session::flash('success', 'Account type deleted successfully.');
        return redirect()->route('account_types.index');
    }
}
