<?php
// generer_pdf.php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Méthode non autorisée']);
    exit;
}

$commandes = $_POST['commandes'] ?? '';
if (empty($commandes)) {
    echo json_encode(['success' => false, 'error' => 'Aucune commande fournie']);
    exit;
}

$tmpDir = sys_get_temp_dir();
$macFile = tempnam($tmpDir, 'maxima_') . '.mac';
file_put_contents($macFile, $commandes);

// Récupérer les paramètres depuis le formulaire
$fontSize = $_POST['fontSize'] ?? '11pt';
$imgScale = $_POST['imgScale'] ?? '0.5';

$pythonScript = '/home/mgosse2/yamwifr/mac2pdf_cli.py';

if (!file_exists($pythonScript)) {
    echo json_encode([
        'success' => false, 
        'error' => 'Script Python introuvable: ' . $pythonScript
    ]);
    unlink($macFile);
    exit;
}

// Nom unique pour le PDF
$pdfName = 'yamwi_' . uniqid() . '.pdf';
$pdfFile = $tmpDir . '/' . $pdfName;

// Construction de la commande
$command = 'python3 ' . 
    escapeshellarg($pythonScript) . ' ' .
    escapeshellarg($macFile) . ' ' .
    escapeshellarg($pdfFile) . ' ' .
    escapeshellarg($fontSize) . ' ' .
    escapeshellarg($imgScale) . 
    ' 2>&1';

exec($command, $output, $returnCode);
unlink($macFile);

if ($returnCode === 0 && file_exists($pdfFile)) {
    echo json_encode([
        'success' => true,
        'pdf' => $pdfName,
        'download_url' => 'telecharger_pdf.php?file=' . urlencode($pdfName) . '&action=download',
        'view_url' => 'telecharger_pdf.php?file=' . urlencode($pdfName) . '&action=view'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'error' => 'Erreur lors de la génération du PDF (code: ' . $returnCode . ')',
        'details' => implode("\n", $output)
    ]);
}
?>
