<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Expense;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ExpenseController extends Controller
{
    public function index()
    {
        $expenses = Expense::latest()->paginate(20);
        return view('admin.expenses.index', compact('expenses'));
    }

    public function create()
    {
        return view('admin.expenses.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'category'      => 'required|string|max:255',
            'amount'        => 'required|numeric|min:0',
            'expense_date'  => 'required|date',
            'description'   => 'nullable|string',
        ]);

        Expense::create([
            'category'      => $request->category,
            'description'   => $request->description,
            'amount'        => $request->amount,
            'expense_date'  => $request->expense_date,
            'recorded_by'   => Auth::id(),
        ]);

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

    public function edit(Expense $expense)
    {
        return view('admin.expenses.edit', compact('expense'));
    }

    public function update(Request $request, Expense $expense)
    {
        $request->validate([
            'category'      => 'required|string|max:255',
            'amount'        => 'required|numeric|min:0',
            'expense_date'  => 'required|date',
            'description'   => 'nullable|string',
        ]);

        $expense->update($request->all());

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