<?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::all();
        return view('modules.edit.account-types', compact('account_types'));
    }

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

        AccountType::create([
            'name' => $request->name,
            'description' => $request->description,
        ]);

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

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

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

        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');
    }
}
