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

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

function generateTicketJasper(int $venteId, PDO $conn): string
{
    global $host, $dbname, $user, $pass;

    // 1. Vérifier que la vente existe
    $stmt = $conn->prepare("SELECT id FROM ventes WHERE id = ?");
    $stmt->execute([$venteId]);
    if (!$stmt->fetch()) {
        throw new Exception("Vente #$venteId introuvable");
    }

    // 2. Vérifier qu'il y a des lignes
    $stmt = $conn->prepare("SELECT COUNT(*) FROM ventes_details WHERE vente_id = ?");
    $stmt->execute([$venteId]);
    if ($stmt->fetchColumn() == 0) {
        throw new Exception("Le ticket #$venteId ne contient aucune ligne");
    }

    // 3. Chemins
    $jasperstarter = __DIR__ . '/jasperstarter8.bat';
    if (!file_exists($jasperstarter)) {
        throw new Exception("JasperStarter introuvable");
    }

    $reportFile = __DIR__ . '/../pos/ticket_client.jasper';
    if (!file_exists($reportFile)) {
        throw new Exception("Fichier Jasper manquant");
    }

    $outputBaseDir = __DIR__ . '/../pos/output';
    if (!is_dir($outputBaseDir)) {
        mkdir($outputBaseDir, 0777, true);
    }

    $outputFile = $outputBaseDir . "/ticket_$venteId";

    // 4. Commande Jasper
    $cmd = "\"$jasperstarter\" process \"$reportFile\""
         . " -o \"$outputFile\" -f pdf"
         . " -t mysql"
         . " -H $host -n $dbname -u $user -p $pass"
         . " -P idVente=\"$venteId\"";

    exec($cmd . " 2>&1", $output, $code);

    // Log
    file_put_contents(
        __DIR__ . "/jasper_debug.log",
        "[".date('Y-m-d H:i:s')."]\n$cmd\n".implode("\n",$output)."\n\n",
        FILE_APPEND
    );

    if ($code !== 0 || !file_exists($outputFile.'.pdf')) {
        throw new Exception("Échec JasperStarter");
    }

    return $outputFile.'.pdf';
}
