<?php

namespace App\Http\Controllers;

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

class ExpenseController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Expense::class);
        $query = Expense::query()->with('user');

        // Optional simple filtering
        if ($request->filled('date')) {
            $query->whereDate('expense_date', $request->date);
        }

        $expenses = $query->orderBy('expense_date', 'desc')
                          ->orderBy('created_at', 'desc')
                          ->paginate(15);
                          
        $totalDaily = Expense::whereDate('expense_date', today())->sum('amount');

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $this->authorize('create', Expense::class);
        return view('expenses.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $this->authorize('create', Expense::class);
        $validated = $request->validate([
            'description' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0.01',
            'category' => 'required|string|in:supplier_payment,internal_credit,services,other',
            'expense_date' => 'required|date',
            'reference' => 'nullable|string|max:255',
        ]);

        $validated['user_id'] = auth()->id();

        Expense::create($validated);

        return redirect()->route('expenses.index')->with('success', 'Gasto registrado correctamente.');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        // Not implemented for now, list is enough
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        // Expenses are usually immutable, but could be added later
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Expense $expense)
    {
        $this->authorize('delete', $expense);
        $expense->delete();
        return redirect()->route('expenses.index')->with('success', 'Gasto eliminado del registro.');
    }
}
