<?php

namespace App\Http\Controllers\Accounting;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\Accounting\FeeType;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Accounting\FeeCycleType;

class FeeTypeController extends Controller
{
    public function index()
    {
        // DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        // DB::statement('TRUNCATE TABLE fee_types;');
        // DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $this->authorize('accounting.fees-type.view');
        $feeTypes = FeeType::where('status', 1)->get();
        // dd($feeTypes);
        // $feeCycleTypes = FeeCycleType::pluck('name', 'id');
        return view('pages.accounting.fee_types.index', compact('feeTypes'));
    }

    public function store(Request $request)
    {
        $this->authorize('accounting.fees-type.create');
        $request->validate([
            'title' => 'required|unique:fee_types,title',
        ]);

        // $checkExist = FeeType::where('title', $request->title)->where('code', $request->code)->where('month', $request->month)->first();
        // if($checkExist){
        //     return redirect()->route('fee_types.index')->with('warning', 'Fee category already exist for this month.');
        // }

        FeeType::create([
            'title' => $request->title,
            'code' => Str::slug($request->title),
        ]);
        return redirect()->route('fee_types.index')->with('success', 'Fee Category created successfully.');
    }

    public function update(Request $request, FeeType $feeType)
    {
        $this->authorize('accounting.fees-type.edit');
        $request->validate([
            'title' => 'required|unique:fee_types,title,' . $feeType->id,
        ]);

        // $checkExist = FeeType::where('title', $request->title)->where('code', $request->code)->where('month', $request->month)->where('id', '!=', $feeType->id)->first();
        // if($checkExist){
        //     return redirect()->route('fee_types.index')->with('warning', 'Fee category already exist for this month.');
        // }

        $feeType->update([
            'title' => $request->title,
            'code' => Str::slug($request->title),
        ]);

        return redirect()->route('fee_types.index')->with('success', 'Fee Category updated successfully.');
    }

    public function destroy(FeeType $feeType)
    {
        $this->authorize('accounting.fees-type.delete');

        $classFeeCount = $feeType->classFee()->count();
        $invoiceItemCount = $feeType->invoiceItem()->count();
        if ($classFeeCount === 0 && $invoiceItemCount === 0) {
            $feeType->delete();
            return redirect()->route('fee_types.index')->with('success', 'Fee Category deleted successfully.');
        }
        return redirect()->route('fee_types.index')->with('danger', 'Cannot delete. Fee Category is already in use.');
    }

}
