<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/generateTicketJasper.php';

try {
    if (!isset($_GET['ref']) || !ctype_digit($_GET['ref'])) {
        throw new Exception("Référence invalide");
    }

    $venteId = (int) $_GET['ref'];

    $pdfPath = generateTicketJasper($venteId, $conn);

    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="ticket_'.$venteId.'.pdf"');
    header('Content-Length: ' . filesize($pdfPath));
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Pragma: no-cache');

    readfile($pdfPath);
    exit;

} catch (Exception $e) {
    http_response_code(500);
    echo "<h3 style='color:red;text-align:center'>❌ ".$e->getMessage()."</h3>";
}
