<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Receipt;
use Illuminate\Support\Str;
use ZipArchive;
use Barryvdh\DomPDF\Facade\Pdf;

class ReceiptExportController extends Controller
{
    public function exportZip(Request $request)
    {
        $q = Receipt::query()->with('member');

        if ($request->filled('filterStatus')) {
            $q->where('status', $request->input('filterStatus'));
        }
        if ($request->filled('filterFrom')) {
            $q->whereDate('date', '>=', $request->input('filterFrom'));
        }
        if ($request->filled('filterTo')) {
            $q->whereDate('date', '<=', $request->input('filterTo'));
        }
        if ($request->filled('filterMember')) {
            $q->where('member_id', $request->input('filterMember'));
        }

        // Eventuale ricerca globale
        if ($search = $request->input('search')) {
            $q->where(function ($sub) use ($search) {
                $sub->where('number', 'like', "%{$search}%")
                    ->orWhere('status', 'like', "%{$search}%")
                    ->orWhereHas('member', function ($mq) use ($search) {
                        $mq->where('first_name', 'like', "%{$search}%")
                            ->orWhere('last_name', 'like', "%{$search}%");
                    });
            });
        }

        $receipts = $q->get();

        if ($receipts->isEmpty()) {
            return abort(404, 'Nessuna ricevuta trovata.');
        }

        $zipFileName = now()->format('Ymd') . '_Ricevute.zip';
        $zipPath = storage_path('app/' . $zipFileName);

        $zip = new \ZipArchive();
        if ($zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
            return abort(500, 'Impossibile creare lo ZIP.');
        }

        foreach ($receipts as $receipt) {
            $lastName  = Str::slug($receipt->member->last_name ?? 'sconosciuto', '_');
            $firstName = Str::slug($receipt->member->first_name ?? 'sconosciuto', '_');
            $pdfName   = "Ricevuta_{$receipt->number}_{$lastName}_{$firstName}.pdf";

            $pdf = PDF::loadView('receipt', ['receipt' => $receipt]);
            $zip->addFromString($pdfName, $pdf->output());
        }

        $zip->close();

        return response()->download($zipPath)->deleteFileAfterSend(true);
    }
}
