<?php

namespace App\Http\Controllers;

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

class ExpenseController extends Controller
{
    public function index()
    {
        $expenses = Expense::latest()->paginate(15);

        return view('expenses.index', compact('expenses'));
    }

    public function create()
    {
        $expenseCategories = ExpenseCategory::active()->orderBy('name')->get();
        $nextExpenseNo = 'EX-' . str_pad((Expense::max('id') ?? 0) + 1, 5, '0', STR_PAD_LEFT);

        return view('expenses.create', compact('expenseCategories', 'nextExpenseNo'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'expense_category_id' => ['nullable', 'exists:expense_categories,id'],
            'expense_no'          => ['nullable', 'string', 'max:50'],
            'expense_date'        => ['required', 'date'],
            'frequency'           => ['required', 'in:one_time,monthly,weekly,yearly'],
            'amount'              => ['required', 'numeric', 'min:0'],
            'reference'           => ['nullable', 'string', 'max:255'],
            'notes'               => ['nullable', 'string'],
        ]);

        if (empty($data['expense_no'])) {
            $data['expense_no'] = 'EX-' . str_pad((Expense::max('id') ?? 0) + 1, 5, '0', STR_PAD_LEFT);
        }

        Expense::create($data);

        return redirect()->route('expenses.index')->with('success', __('Expense added successfully.'));
    }

    public function destroy(Expense $expense)
    {
        $expense->delete();

        return redirect()->route('expenses.index')->with('success', __('Expense removed successfully.'));
    }
}
