<?php

namespace App\Http\Controllers\Admin\Rental;

use App\Http\Controllers\Controller;
use App\Models\Rental\ExpenseCategory;
use Illuminate\Http\Request;

class ExpenseCategoryController extends Controller
{
    public function index()
    {
        $categories = ExpenseCategory::all();
        return view('admin.rentals.expenses.categories.index', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
            'type' => 'required|in:vehicle,contract,general',
            'is_active' => 'boolean'
        ]);

        ExpenseCategory::create($validated);

        return back()->with('success', 'Category created successfully.');
    }

    public function update(Request $request, ExpenseCategory $expense_category)
    {
        $validated = $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
            'type' => 'required|in:vehicle,contract,general',
            'is_active' => 'boolean'
        ]);

        $expense_category->update($validated);

        return back()->with('success', 'Category updated successfully.');
    }

    public function destroy(ExpenseCategory $expense_category)
    {
        if ($expense_category->expenses()->exists()) {
            return back()->with('error', 'Cannot delete category with associated expenses.');
        }

        $expense_category->delete();

        return back()->with('success', 'Category deleted successfully.');
    }
}
