<?php

declare(strict_types=1);

namespace App\EventListener;

use Contao\CoreBundle\DependencyInjection\Attribute\AsHook;
use Contao\FilesModel;
use Contao\Validator;

#[AsHook("replaceInsertTags")]
class ReplaceInsertTagListener
{
    public function __invoke(string $insertTag, bool $useCache, string $cachedValue, array $flags, array $tags, array $cache, int $_rit, int $_cnt)
    {
        $elements = explode('::', $insertTag,2);
        $insertTag = array_shift($elements);

        if (strtolower($insertTag) === 'svg_inline') {
            if (isset($elements[0]) && $elements[0])
            {
                $fragments = explode(':', $elements[0]);
                $strFile = $fragments[0];
                $strId = null;
                $strClass = null;
                if (isset($fragments[1]))
                {
                    $strClass = $fragments[1];
                }
                if (isset($fragments[2]))
                {
                    $strId = $fragments[2];
                }

                if (Validator::isUuid($strFile))
                {
                    // Handle UUIDs
                    $objFile = FilesModel::findByUuid($strFile);

                    if ($objFile === null)
                    {
                        return '';
                    }

                    $strFile = $objFile->path;
                }
                elseif (is_numeric($strFile))
                {
                    // Handle numeric IDs (see #4805)
                    $objFile = FilesModel::findByPk($strFile);

                    if ($objFile === null)
                    {
                        return '';
                    }

                    $strFile = $objFile->path;
                }
                elseif (Validator::isInsecurePath($strFile))
                {
                    throw new \RuntimeException('Invalid path ' . $strFile);
                }
                elseif (($objFile = FilesModel::findByPath($strFile)) !== null)
                {
                    $strFile = $objFile->path;
                } else {
                    return '';
                }

                return $this->print_svg($strFile,$strClass,$strId);
            }
        }
    }

    protected function print_svg($svgPath, ?string $strClass=null, ?string$strId=null){
        $iconfile = new \DOMDocument();
        $iconfile->load($svgPath);
        if (($svg = $iconfile->getElementsByTagName('svg')->item(0)))
        {
            if ($strClass) {
                if (($embClass = $svg->getAttribute('class')))
                {
                    $strClass = $embClass. ' ' . $strClass;
                }
                $svg->setAttribute('class', $strClass);
            }
            if ($strId){
                $svg->setAttribute('id', $strId);
            }
            return $iconfile->saveHTML($svg);
        }
    }
}
