<?php

namespace App\Http\Controllers;

use App\Exports\FacturesExport;
use App\Models\Creance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class InvoiceController extends Controller
{
    /**
     * Liste des factures impayées
     */
    public function index(Request $request)
    {
        $query = Creance::with(['vente.produit', 'vente.magasin', 'client'])
            ->where('statut', 'impaye')
            ->latest();

        if ($request->filled('client')) {
            $query->whereHas('client', function ($q) use ($request) {
                $q->where('nom', $request->client);
            });
        }

        if ($request->filled('date_from')) {
            $query->whereDate('date_creance', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('date_creance', '<=', $request->date_to);
        }

        $impayes = $query->paginate(10)->withQueryString();

        return view('factures.index', compact('impayes'));
    }

    /**
     * Export XLSX des factures impayées (en fonction des filtres).
     */
    public function export(Request $request)
    {
        $query = Creance::with(['vente.produit', 'vente.magasin', 'client'])
            ->where('statut', 'impaye')
            ->latest();

        if ($request->filled('client')) {
            $query->whereHas('client', function ($q) use ($request) {
                $q->where('nom', $request->client);
            });
        }

        if ($request->filled('date_from')) {
            $query->whereDate('date_creance', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('date_creance', '<=', $request->date_to);
        }

        $creances = $query->get();

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

        return Excel::download(new FacturesExport($creances), $filename);
    }
}
