<?php
/**
 * Libreria di funzioni per la gestione dei template SVG
 */

// Configurazione
define('TEMPLATES_DIR', __DIR__ . '/templates/');
define('TEMP_DIR', __DIR__ . '/temp/');

/**
 * Ottiene la lista dei file SVG nella cartella templates
 * 
 * @return array Lista dei nomi file SVG
 */
function getTemplateFiles() {
    $files = [];
    if (is_dir(TEMPLATES_DIR)) {
        $items = scandir(TEMPLATES_DIR);
        foreach ($items as $item) {
            if ($item !== '.' && $item !== '..' && pathinfo($item, PATHINFO_EXTENSION) === 'svg') {
                $files[] = $item;
            }
        }
    }
    return $files;
}

/**
 * Ottiene il label del template dal file SVG
 * 
 * @param string $filename Nome del file SVG
 * @return string Label del template o nome file se non trovato
 */
function getTemplateLabel($filename) {
    $filepath = TEMPLATES_DIR . $filename;
    if (!file_exists($filepath)) {
        return $filename;
    }
    
    $content = file_get_contents($filepath);
    if ($content === false) {
        return $filename;
    }
    
    // Cerca l'attributo data-template-label nel tag <svg>
    if (preg_match('/data-template-label="([^"]+)"/', $content, $matches)) {
        return $matches[1];
    }
    
    return $filename;
}

/**
 * Valida che il template esista e sia nella cartella corretta
 * 
 * @param string $filename Nome del file da validare
 * @return bool True se valido, false altrimenti
 */
function validateTemplate($filename) {
    if (empty($filename)) {
        return false;
    }
    
    // Previene path traversal
    $basename = basename($filename);
    if ($basename !== $filename) {
        return false;
    }
    
    // Verifica estensione
    if (pathinfo($filename, PATHINFO_EXTENSION) !== 'svg') {
        return false;
    }
    
    // Verifica esistenza
    $filepath = TEMPLATES_DIR . $filename;
    if (!file_exists($filepath) || !is_file($filepath)) {
        return false;
    }
    
    return true;
}

/**
 * Estrae i campi personalizzati dal template SVG
 * 
 * @param string $filename Nome del file SVG
 * @return array Array di campi personalizzati
 */
function getCustomFields($filename) {
    $filepath = TEMPLATES_DIR . $filename;
    $content = file_get_contents($filepath);
    if ($content === false) {
        return [];
    }
    
    $fields = [];
    
    // Carica il contenuto come XML
    $dom = new DOMDocument();
    @$dom->loadXML($content);
    
    // Usa XPath per trovare tutti gli elementi con attributi data-custom-*
    $xpath = new DOMXPath($dom);
    $elements = $xpath->query('//*[@*[starts-with(name(), "data-custom")]]');
    
    foreach ($elements as $element) {
        $fieldData = [
            'id' => $element->getAttribute('id'),
            'type' => 'text', // default
            'label' => '',
            'attributes' => []
        ];
        
        // Estrae tutti gli attributi data-custom-*
        foreach ($element->attributes as $attr) {
            if (strpos($attr->name, 'data-custom-') === 0) {
                $customKey = substr($attr->name, 12); // rimuove 'data-custom-'
                
                if ($customKey === 'type') {
                    $fieldData['type'] = $attr->value;
                } elseif ($customKey === 'label') {
                    $fieldData['label'] = $attr->value;
                } else {
                    $fieldData['attributes'][$customKey] = $attr->value;
                }
            }
        }
        
        // Se non c'è label, usa l'id
        if (empty($fieldData['label']) && !empty($fieldData['id'])) {
            $fieldData['label'] = $fieldData['id'];
        }
        
        // Genera un ID univoco se mancante
        if (empty($fieldData['id'])) {
            $fieldData['id'] = 'field_' . count($fields);
        }
        
        $fields[] = $fieldData;
    }
    
    return $fields;
}

/**
 * Renderizza un campo HTML in base al tipo
 * 
 * @param array $field Dati del campo
 * @return string HTML del campo
 */
function renderField($field) {
    $id = htmlspecialchars($field['id']);
    $label = htmlspecialchars($field['label']);
    $type = $field['type'];
    
    $html = '<div class="mb-3">';
    $html .= '<label for="' . $id . '" class="form-label">' . $label . '</label>';
    
    switch ($type) {
        case 'integer':
        case 'number':
            $html .= '<input type="number" class="form-control" id="' . $id . '" name="' . $id . '"';
            if ($type === 'integer') {
                $html .= ' step="1"';
            }
            $html .= '>';
            break;
            
        case 'email':
            $html .= '<input type="email" class="form-control" id="' . $id . '" name="' . $id . '">';
            break;
            
        case 'url':
            $html .= '<input type="url" class="form-control" id="' . $id . '" name="' . $id . '">';
            break;
            
        case 'date':
            $html .= '<input type="date" class="form-control" id="' . $id . '" name="' . $id . '">';
            break;
            
        case 'time':
            $html .= '<input type="time" class="form-control" id="' . $id . '" name="' . $id . '">';
            break;
            
        case 'color':
            $html .= '<input type="color" class="form-control form-control-color" id="' . $id . '" name="' . $id . '">';
            break;
            
        case 'textarea':
            $html .= '<textarea class="form-control" id="' . $id . '" name="' . $id . '" rows="3"></textarea>';
            break;
            
        case 'text':
        default:
            $html .= '<input type="text" class="form-control" id="' . $id . '" name="' . $id . '">';
            break;
    }
    
    $html .= '</div>';
    
    return $html;
}

/**
 * Sostituisce i valori nel template SVG
 *
 * @param string $filename Nome del file template
 * @param array $data Dati da sostituire (chiave => valore)
 * @return string|false Contenuto SVG modificato o false in caso di errore
 */
function replaceSvgValues($filename, $data) {
    $filepath = TEMPLATES_DIR . $filename;
    $content = file_get_contents($filepath);
    if ($content === false) {
        return false;
    }

    // Carica il contenuto come XML
    $dom = new DOMDocument();
    @$dom->loadXML($content);

    // Crea XPath per cercare elementi
    $xpath = new DOMXPath($dom);

    // Sostituisce i valori per ogni campo
    foreach ($data as $fieldId => $value) {
        // Cerca l'elemento con l'id specificato usando XPath
        $elements = $xpath->query("//*[@id='" . $fieldId . "']");

        if ($elements->length > 0) {
            $element = $elements->item(0);

            // Sostituisce il contenuto testuale dell'elemento
            // Rimuove tutti i nodi figli esistenti
            while ($element->firstChild) {
                $element->removeChild($element->firstChild);
            }

            // Aggiunge il nuovo testo
            $textNode = $dom->createTextNode($value);
            $element->appendChild($textNode);
        }
    }

    return $dom->saveXML();
}

/**
 * Genera un file PNG da un SVG usando Inkscape
 * 
 * @param string $svgPath Percorso del file SVG
 * @param string $pngPath Percorso del file PNG di output
 * @param int $width Larghezza in pixel (opzionale)
 * @return bool True se successo, false altrimenti
 */
function convertSvgToPng($svgPath, $pngPath, $width = null) {
    // Prova diversi percorsi di Inkscape
    $possiblePaths = [
        '/usr/bin/inkscape',       // Installazione sistema
        '/usr/local/bin/inkscape', // Installazione locale
        'inkscape'                 // PATH
    ];

    $inkscapePath = null;
    foreach ($possiblePaths as $path) {
        // Testa se il comando funziona
        // Ripulisce le variabili d'ambiente snap che causano conflitti
        $testCmd = $path . ' --version 2>&1';
        $testOutput = [];
        $testReturn = 0;
        @exec($testCmd, $testOutput, $testReturn);

        if ($testReturn === 0) {
            $inkscapePath = $path;
            break;
        }
    }

    if ($inkscapePath === null) {
        error_log('Inkscape non trovato o non funzionante nel sistema');
        return false;
    }
    
    // Costruisce il comando
    // Ripulisce le variabili d'ambiente snap per evitare conflitti con le librerie
    $cmd = 'unset LD_LIBRARY_PATH; unset GTK_PATH; ';
    $cmd .= escapeshellcmd($inkscapePath) . ' ';
    $cmd .= escapeshellarg($svgPath) . ' ';
    $cmd .= '--export-filename=' . escapeshellarg($pngPath) . ' ';

    if ($width !== null) {
        $cmd .= '--export-width=' . intval($width) . ' ';
    }

    $cmd .= '2>&1';

    // Esegue il comando
    $output = [];
    $returnVar = 0;
    exec($cmd, $output, $returnVar);
    
    if ($returnVar !== 0) {
        error_log('Errore durante la conversione SVG->PNG: ' . implode("\n", $output));
        return false;
    }
    
    return file_exists($pngPath);
}

/**
 * Crea la cartella temp se non esiste
 */
function ensureTempDir() {
    if (!is_dir(TEMP_DIR)) {
        mkdir(TEMP_DIR, 0755, true);
    }
}

/**
 * Pulisce i file temporanei più vecchi di un'ora
 */
function cleanOldTempFiles() {
    if (!is_dir(TEMP_DIR)) {
        return;
    }
    
    $files = glob(TEMP_DIR . '*');
    $now = time();
    
    foreach ($files as $file) {
        if (is_file($file)) {
            if ($now - filemtime($file) >= 3600) { // 1 ora
                unlink($file);
            }
        }
    }
}

