<?php

namespace App\Http\Controllers;

use App\Models\ExpenseCategory;
use Illuminate\Http\Request;

class ExpenseCategoryController extends Controller
{
    public function index(Request $request)
    {
        $query = ExpenseCategory::withCount('expenses');

        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        if ($request->filled('status')) {
            $query->where('is_active', $request->status === 'active');
        }

        $categories = $query->latest()->paginate(15)->withQueryString();

        return view('pages.expense-categories.index', [
            'title' => 'Jenis Pengeluaran',
            'categories' => $categories,
        ]);
    }

    public function create()
    {
        return view('pages.expense-categories.form', [
            'title' => 'Tambah Jenis Pengeluaran',
            'category' => new ExpenseCategory(),
        ]);
    }

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

        $validated['is_active'] = $request->has('is_active');

        ExpenseCategory::create($validated);

        return redirect()->route('expense-categories.index')
            ->with('success', 'Jenis pengeluaran berhasil ditambahkan.');
    }

    public function edit(ExpenseCategory $expenseCategory)
    {
        return view('pages.expense-categories.form', [
            'title' => 'Edit Jenis Pengeluaran',
            'category' => $expenseCategory,
        ]);
    }

    public function update(Request $request, ExpenseCategory $expenseCategory)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:expense_categories,name,' . $expenseCategory->id,
            'description' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $expenseCategory->update($validated);

        return redirect()->route('expense-categories.index')
            ->with('success', 'Jenis pengeluaran berhasil diperbarui.');
    }

    public function destroy(ExpenseCategory $expenseCategory)
    {
        if ($expenseCategory->expenses()->exists()) {
            return redirect()->back()
                ->with('error', 'Jenis pengeluaran tidak dapat dihapus karena memiliki data pengeluaran.');
        }

        $expenseCategory->delete();

        return redirect()->route('expense-categories.index')
            ->with('success', 'Jenis pengeluaran berhasil dihapus.');
    }
}
