<?php
/**
 * File di elaborazione dei dati del form
 * Genera un'immagine PNG dal template SVG con i dati inseriti
 */

require_once 'lib.php';

// Verifica che sia una richiesta POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

// Recupera il template
$template = isset($_POST['template']) ? $_POST['template'] : '';

if (!validateTemplate($template)) {
    die('Template non valido');
}

// Recupera tutti i dati del form (escluso il template)
$formData = $_POST;
unset($formData['template']);

// Assicura che la cartella temp esista
ensureTempDir();

// Pulisce i file temporanei vecchi
cleanOldTempFiles();

// Sostituisce i valori nel template SVG
$modifiedSvg = replaceSvgValues($template, $formData);

if ($modifiedSvg === false) {
    die('Errore durante la modifica del template SVG');
}

// Genera nomi file temporanei univoci
$uniqueId = uniqid('svg_', true);
$tempSvgPath = TEMP_DIR . $uniqueId . '.svg';
$tempPngPath = TEMP_DIR . $uniqueId . '.png';

// Salva il file SVG modificato
if (file_put_contents($tempSvgPath, $modifiedSvg) === false) {
    die('Errore durante il salvataggio del file SVG temporaneo');
}

// Converte SVG in PNG usando Inkscape
$conversionSuccess = convertSvgToPng($tempSvgPath, $tempPngPath, 1920);

if (!$conversionSuccess) {
    // Rimuove il file SVG temporaneo
    @unlink($tempSvgPath);

    // Mostra errore
    ?>
    <!DOCTYPE html>
    <html lang="it">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Errore</title>
        <link href="assets/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body {
                padding: 20px;
                background-color: #f8f9fa;
            }
            .container {
                max-width: 800px;
                background-color: white;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1 class="mb-4">Errore</h1>

            <div class="alert alert-danger" role="alert">
                <h4 class="alert-heading">Errore durante la conversione</h4>
                <p>Non è stato possibile convertire il file SVG in PNG.</p>
                <hr>
                <p class="mb-0">Assicurati che Inkscape sia installato sul sistema:</p>
                <pre class="mt-2">sudo apt-get install inkscape</pre>
            </div>

            <div class="mt-4">
                <a href="index.php?template=<?php echo urlencode($template); ?>" class="btn btn-primary">Torna al form</a>
                <a href="index.php" class="btn btn-secondary">Seleziona altro template</a>
            </div>
        </div>

        <script src="assets/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    <?php
    exit;
}

// Rimuove il file SVG temporaneo (non più necessario)
@unlink($tempSvgPath);

// Prepara il nome del file per il download
$downloadFilename = pathinfo($template, PATHINFO_FILENAME) . '_' . date('Y-m-d_H-i-s') . '.png';

// Invia il file PNG come download
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="' . $downloadFilename . '"');
header('Content-Length: ' . filesize($tempPngPath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

// Invia il file
readfile($tempPngPath);

// Rimuove il file PNG temporaneo
@unlink($tempPngPath);

exit;

