<?php

namespace App\Http\Controllers\Accounting;
 
use App\Constants\Accounting;
use App\Http\Controllers\Controller;
use App\Models\Accounting\AccountingHead;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AccountingHeadController extends Controller
{
    public function index()
    {
        $this->authorize('accounting.accounting-head.view');
        $accounting_heads = AccountingHead::get();
        $types = Accounting::AC_HEAD_TYPE;
        return view('pages.accounting.accounting_head.index', compact('accounting_heads', 'types'));
    }


    public function store(Request $request)
    {
        $this->authorize('accounting.accounting-head.create');
        $request->validate([
            'name' => 'required|string|max:255|unique:accounting_heads,name',
        ]);

        $head_name = $request->name;
        $head_type = $request->type;
        $head_slug = Str::slug($head_name);

        $head = new AccountingHead();
        $head->branch_id = auth()->user()->branch_id;
        $head->name = $head_name;
        $head->type = $head_type;
        $head->slug = $head_slug;
        $head->save();

        return redirect()->route('accounting_head.index')->with('success', 'Accounting Head created successfully.');
    }

    public function edit($id)
    {
        $this->authorize('accounting.accounting-head.edit');
        $head = AccountingHead::findOrFail($id);
        return view('pages.accounting.accounting_head.edit', compact('category'));
    }

    public function update(Request $request, $id)
    {
        $this->authorize('accounting.accounting-head.edit');
        $request->validate([
            'name' => 'required|string|max:255|unique:permission_categories,name,'.$id,
        ]);

        $head = AccountingHead::findOrFail($id);
        $head_name = $request->name;
        $head_type = $request->type;
        $head_slug = Str::slug($head_name);

        $head->name = $head_name;
        $head->type = $head_type;
        $head->slug = $head_slug;
        $head->save();

        return redirect()->route('accounting_head.index')->with('success', 'Accounting Head updated successfully.');
    }

    public function destroy($id)
    {
        $this->authorize('accounting.accounting-head.delete');
        $head = AccountingHead::findOrFail($id);
        $head->delete();

        return redirect()->route('accounting_head.index')->with('success', 'Accounting Head deleted successfully.');
    }
}
