<?php
// Plugin: fetch_svg
// Version: 1.0 - 2025-10-05
// Author: Optimized version
// Description: Fetch and optimize SVG files with ID prefixing and caching

function smarty_function_fetch_svg($params, &$smarty) {
    // Validation des paramètres
    if (empty($params['file'])) {
        trigger_error('fetch_svg: paramètre "file" requis', E_USER_WARNING);
        return '';
    }
    
    $gCms = CmsApp::get_instance();
    $config = $gCms->GetConfig();
    $filePath = cms_join_path($config['root_path'], $params['file']);
    
    // Vérifications de sécurité et d'existence
    if (!file_exists($filePath)) {
        trigger_error("fetch_svg: fichier introuvable - {$params['file']}", E_USER_WARNING);
        return '';
    }
    
    if (!is_readable($filePath)) {
        trigger_error("fetch_svg: fichier non lisible - {$params['file']}", E_USER_WARNING);
        return '';
    }
    
    // Mise en cache optionnelle
    $cacheKey = 'svg_' . md5($filePath . filemtime($filePath));
    $useCache = !empty($params['cache']);
    
    if ($useCache && isset($smarty->_cache[$cacheKey])) {
        $content = $smarty->_cache[$cacheKey];
    } else {
        $content = file_get_contents($filePath);
        
        if ($content === false) {
            trigger_error("fetch_svg: erreur de lecture - {$params['file']}", E_USER_WARNING);
            return '';
        }
        
        // Compression optimisée avec une seule passe
        $patterns = [
            '/<\?.*\?>/',              // Instructions PHP
            '/<!--(.|\s)*?-->/',       // Commentaires
            '/<g>\s*<\/g>/',          // Groupes vides
            '/\s*\n\s*/',             // Sauts de ligne et espaces autour
            '/\t+/',                   // Tabulations
            '/\s{2,}/',               // Espaces multiples
            '/>\s+</',                 // Espaces entre tags
            '/;\s*"/',                 // Point-virgule avant guillemet
        ];
        
        $replacements = ['', '', '', ' ', ' ', ' ', '><', '"'];
        $content = preg_replace($patterns, $replacements, $content);
        
        // Stockage en cache
        if ($useCache) {
            $smarty->_cache[$cacheKey] = $content;
        }
    }
    
    // Génération du préfixe unique
    if (!empty($params['prefix'])) {
        $prefix = $params['prefix'];
    } else {
        // Utilisation d'un identifiant plus léger et unique
        static $counter = 0;
        $prefix = 'svg-' . (++$counter) . '-';
    }
    
    // Préfixage des IDs et références (optimisé)
    if ($prefix) {
        $content = preg_replace_callback(
            '/\b(id|href|xlink:href)=(["\'])([^"\']+)\2/',
            function($matches) use ($prefix) {
                $attr = $matches[1];
                $quote = $matches[2];
                $value = $matches[3];
                
                // Préfixer les IDs et les références internes
                if ($attr === 'id') {
                    return "{$attr}={$quote}{$prefix}{$value}{$quote}";
                } elseif (strpos($value, '#') === 0) {
                    return "{$attr}={$quote}#{$prefix}" . substr($value, 1) . "{$quote}";
                }
                return $matches[0];
            },
            $content
        );
        
        // url() dans les styles
        $content = preg_replace('/url\(#([^)]+)\)/', 'url(#' . $prefix . '$1)', $content);
    }
    
    // Classes CSS optionnelles
    if (!empty($params['class'])) {
        $content = preg_replace('/<svg/', '<svg class="' . htmlspecialchars($params['class']) . '"', $content, 1);
    }
    
    // Assignation ou affichage
    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $content);
    } else {
        return $content;
    }
}

function smarty_cms_about_function_fetch_svg() {
    ?>
    <p><strong>Author:</strong> Jocelyn LUSSEAU • <a href="https://www.koalink.fr" target="_blank">Koa'link</a></p>
    <p><strong>Version:</strong> 1.0</p>
    <p><strong>Last Update:</strong> October 2025</p>
    <p><strong>Purpose:</strong> Fetches SVG files, optimizes them by removing unnecessary whitespace and comments, and prefixes IDs to prevent conflicts when multiple SVGs are used on the same page.</p>
    <p><strong>Features:</strong></p>
    <ul>
        <li>Automatic SVG compression and optimization</li>
        <li>Unique ID prefixing to avoid conflicts</li>
        <li>Optional caching for improved performance</li>
        <li>CSS class injection support</li>
        <li>Security checks for file access</li>
    </ul>
    <p><strong>License:</strong> Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)</p>
    <?php
}

function smarty_cms_help_function_fetch_svg() {
    ?>
    <h3>What does this plugin do?</h3>
    <p>The <code>fetch_svg</code> plugin loads SVG files from your server, optimizes them, and outputs them inline in your HTML. It automatically prefixes all IDs within the SVG to prevent conflicts when using multiple SVG files on the same page.</p>
    
    <h3>How do I use it?</h3>
    <p>Use the plugin in your Smarty templates with the following syntax:</p>
    <pre>{fetch_svg file='path/to/your/file.svg'}</pre>
    
    <h3>Parameters</h3>
    <table class="pagetable">
        <thead>
            <tr>
                <th>Parameter</th>
                <th>Required</th>
                <th>Default</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><strong>file</strong></td>
                <td>Yes</td>
                <td>-</td>
                <td>Path to the SVG file relative to the CMS root directory.<br>
                Example: <code>images/icons/home.svg</code></td>
            </tr>
            <tr>
                <td><strong>prefix</strong></td>
                <td>No</td>
                <td>Auto-generated</td>
                <td>Custom prefix for IDs within the SVG. If not specified, a unique prefix is automatically generated.<br>
                Example: <code>prefix='icon-home-'</code></td>
            </tr>
            <tr>
                <td><strong>cache</strong></td>
                <td>No</td>
                <td>false</td>
                <td>Enable caching to improve performance. Set to <code>true</code> to cache the processed SVG.<br>
                Example: <code>cache=true</code></td>
            </tr>
            <tr>
                <td><strong>class</strong></td>
                <td>No</td>
                <td>-</td>
                <td>CSS class(es) to add to the SVG element.<br>
                Example: <code>class='icon icon-large'</code></td>
            </tr>
            <tr>
                <td><strong>assign</strong></td>
                <td>No</td>
                <td>-</td>
                <td>Assign the SVG content to a Smarty variable instead of outputting it directly.<br>
                Example: <code>assign='svg_content'</code></td>
            </tr>
        </tbody>
    </table>
    
    <h3>Examples</h3>
    
    <h4>Basic Usage</h4>
    <pre>{fetch_svg file='images/logo.svg'}</pre>
    <p>Loads and displays the SVG file with automatic ID prefixing.</p>
    
    <h4>With CSS Class</h4>
    <pre>{fetch_svg file='images/icons/home.svg' class='header-icon'}</pre>
    <p>Adds the class "header-icon" to the SVG element.</p>
    
    <h4>With Caching</h4>
    <pre>{fetch_svg file='images/logo.svg' cache=true}</pre>
    <p>Enables caching for better performance when the same SVG is used multiple times.</p>
    
    <h4>With Custom Prefix</h4>
    <pre>{fetch_svg file='images/icons/user.svg' prefix='user-icon-'}</pre>
    <p>Uses "user-icon-" as the prefix for all IDs in the SVG.</p>
    
    <h4>Assign to Variable</h4>
    <pre>{fetch_svg file='images/icon.svg' assign='my_svg'}
{$my_svg}</pre>
    <p>Stores the SVG content in the variable <code>$my_svg</code> for later use.</p>
    
    <h4>Combined Parameters</h4>
    <pre>{fetch_svg file='images/logo.svg' class='site-logo' cache=true prefix='logo-'}</pre>
    <p>Combines multiple parameters for maximum control.</p>
    
    <h3>What does the plugin optimize?</h3>
    <ul>
        <li>Removes XML/PHP processing instructions</li>
        <li>Strips HTML comments</li>
        <li>Removes empty groups</li>
        <li>Compresses whitespace and line breaks</li>
        <li>Removes unnecessary semicolons</li>
        <li>Prefixes all <code>id</code> attributes</li>
        <li>Updates all internal references (<code>href</code>, <code>xlink:href</code>, <code>url()</code>)</li>
    </ul>
    
    <h3>Why use ID prefixing?</h3>
    <p>SVG files often contain IDs for gradients, masks, filters, and other elements. When you use multiple SVGs on the same page, duplicate IDs can cause conflicts, resulting in incorrect rendering. This plugin automatically prefixes all IDs to make them unique.</p>
    
    <h3>Performance Tips</h3>
    <ul>
        <li>Use <code>cache=true</code> for SVGs that don't change frequently</li>
        <li>Keep SVG files optimized before uploading (use tools like SVGO)</li>
        <li>Use <code>assign</code> if you need to reuse the same SVG multiple times in a template</li>
    </ul>
    
    <h3>Troubleshooting</h3>
    <p><strong>SVG not displaying:</strong> Check that the file path is correct and relative to your CMS root directory.</p>
    <p><strong>File not found error:</strong> Verify the file exists and is readable by the web server.</p>
    <p><strong>IDs still conflicting:</strong> Make sure you're not manually setting the same prefix for different SVGs.</p>
    <?php
}
?>