<?php

namespace App\Http\Controllers;

use App\Models\Expense_categorie;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ExpenseCatgController extends Controller
{
    public function show()
    {
        $categories = Expense_categorie::paginate(10);
        return view('expense.expCatg', compact('categories'));
    }

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

        DB::beginTransaction();

        try {
            $max_id    = Expense_categorie::max('id');
            $head_code = 30200 + ($max_id == null ? 1 : $max_id + 1);
            Expense_categorie::create([
                'head_code'    => $head_code,
                'name'         => $request->category_name,
                'account_type' => $request->category_type,
                'description'  => $request->description,
            ]);
            DB::commit();

            return redirect()->back()->with('success', 'Expense category created successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Failed to create expense category: ' . $e->getMessage());
        }
    }

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

        DB::beginTransaction();
        try {
            Expense_categorie::where('id', $id)->update([
                'name'         => $request->category_name,
                'account_type' => $request->category_type,
                'description'  => $request->description,
            ]);

            DB::commit();

            return redirect()->back()->with('success', 'Expense category updated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Failed to update expense category: ' . $e->getMessage());
        }
    }


    public function delete($id)
    {

        DB::beginTransaction();
        try {
            Expense_categorie::where('id', $id)->delete();

            DB::commit();

            return redirect()->back()->with('success', 'Expense category deleted successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Failed to delete expense category: ' . $e->getMessage());
        }
    }
}
