<?php
namespace Zab\ZabSite\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class InlineSvgViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;
    
    public function initializeArguments(): void
    {
        $this->registerArgument('path', 'string', 'Path to SVG (suporta EXT:)', true);
        $this->registerArgument('class', 'string', 'Class to be added to <svg>', false);
        $this->registerArgument('ariaLabel', 'string', 'Aria-label to be added to <svg>', false);
    }


    public function render(): string
    {
        $path = $this->arguments['path'];
        if (empty($path)) return '';
        $absolutePath = '';

        if (str_starts_with($path, 'EXT:')) {
            $absolutePath = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($path);
        } else {
            // Para caminhos como /fileadmin/..., removemos a primeira barra e 
            // usamos o Environment do TYPO3 v13 para chegar ao disco
            $relativePath = ltrim($path, '/');
            $absolutePath = \TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/' . $relativePath;
        }

        if (!file_exists($absolutePath) || is_dir($absolutePath)) {
            return '';
        }

        $svg = file_get_contents($absolutePath);
        // Remove XML declaration 
        $svg = preg_replace('/<\?xml.*?\?>\s*/s', '', $svg);
        $class = !empty($this->arguments['class']) ? htmlspecialchars($this->arguments['class']) : '';
        $ariaLabel = !empty($this->arguments['ariaLabel']) ? ' aria-label="' . htmlspecialchars($this->arguments['ariaLabel']) . '"' : '';

        if (!empty($class) || !empty($ariaLabel)) {
            $svg = preg_replace(
                '/<svg\b([^>]*)>/',
                '<svg$1' . (!empty($class) ? ' class="' . $class . '"' : '') . $ariaLabel . '>',
                $svg,
                1
            );
        }

        return $svg;
    }
}