<?php

namespace App\Http\Controllers;

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

class DepenseController extends Controller
{
    /**
     * Liste des dépenses
     */
    public function index()
    {
        $depenses = Depense::latest()->paginate(10);
        return view('depenses.index', compact('depenses'));
    }



    /**
     * Ajout d'une dépense
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'libelle' => 'required|string|max:255',
            'categorie' => 'required|string|max:255',
            'montant' => 'required|numeric|min:0',
            'date_depense' => 'required|date',
        ]);
        Depense::create($validated);
        return redirect()->route('depenses.index')->with('success', 'Dépense créée avec succès');
    }

    /**
     * Mise à jour d'une dépense.
     */
    public function update(Request $request, string $id)
    {
        $validated = $request->validate([
            'libelle' => 'required|string|max:255',
            'categorie' => 'required|string|max:255',
            'montant' => 'required|numeric|min:0',
            'date_depense' => 'required|date',
        ]);

        $depense = Depense::findOrFail(Depense::keyFromHashId($id));
        $depense->update($validated);

        return redirect()->route('depenses.index')->with('success', 'Dépense mise à jour avec succès');
    }

    /**
     * Suppression d'une dépense.
     */
    public function destroy(string $id)
    {
        $depense = Depense::findOrFail(Depense::keyFromHashId($id));

        $depense->update([
            'deleted_at' => now()
        ]);
        return redirect()->route('depenses.index')->with('success', 'Dépense supprimée avec succès');
    }
}