<?php

namespace App\Http\Controllers;

use App\Exports\CautionsExport;
use App\Models\Caution;
use App\Models\Client;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class CautionController extends Controller
{
    /**
     * Liste des cautions des clients.
     */
    public function index(Request $request)
    {
        $query = Caution::with('client');

        if ($request->filled('date_from')) {
            $query->whereDate('date_depot', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('date_depot', '<=', $request->date_to);
        }
        if ($request->filled('client_id')) {
            $query->where('client_id', $request->client_id);
        }
        if ($request->filled('statut')) {
            $query->where('statut', $request->statut);
        }

        $cautions = $query->latest('date_depot')->paginate(10)->withQueryString();

        $totalCautionsActives = (int) Caution::where('statut', Caution::STATUT_ACTIVE)->sum('montant');
        $clientsAvecCaution = (int) Caution::where('statut', Caution::STATUT_ACTIVE)
            ->selectRaw('count(distinct client_id) as cnt')->value('cnt');
        $restitueesCeMois = Caution::where('statut', Caution::STATUT_RESTITUEE)
            ->whereMonth('date_restitution', now()->month)
            ->whereYear('date_restitution', now()->year)->count();

        $clients = Client::orderBy('nom')->get(['id', 'nom']);

        return view('cautions.index', compact('cautions', 'totalCautionsActives', 'clientsAvecCaution', 'restitueesCeMois', 'clients'));
    }

    /**
     * Exporte les cautions en XLSX selon les filtres appliqués.
     */
    public function export(Request $request)
    {
        $query = Caution::with('client');

        if ($request->filled('date_from')) {

            $query->whereDate('date_depot', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('date_depot', '<=', $request->date_to);
        }
        if ($request->filled('client_id')) {
            $query->where('client_id', $request->client_id);
        }
        if ($request->filled('statut')) {
            $query->where('statut', $request->statut);
        }

        $cautions = $query->latest('date_depot')->get();

        $filename = 'cautions_' . now()->format('Y-m-d_H-i') . '.xlsx';

        return Excel::download(new CautionsExport($cautions), $filename);
    }
}
