<?php

namespace Oksydan\Module\IsThemeCore\Core\Smarty;

use Oksydan\Module\IsThemeCore\Core\Webp\WebpPictureGenerator;
use Oksydan\Module\IsThemeCore\Form\Settings\WebpConfiguration;
use PrestaShop\PrestaShop\Core\Util\ColorBrightnessCalculator;

class SmartyHelperFunctions
{
    public static function generateImagesSources($params)
    {
        $image = $params['image'];
        $size = $params['size'];
        $lazyLoad = isset($params['lazyload']) ? $params['lazyload'] : true;
        $attributes = [];
        $highDpiImagesEnabled = (bool) \Configuration::get('PS_HIGHT_DPI');

        $srcAttributePrefix = $lazyLoad ? 'data-' : '';

        $img = $image['bySize'][$size]['url'];

        if ($highDpiImagesEnabled) {
            $size2x = $size . '2x';
            $img2x = str_replace($size, $size2x, $img);
            $attributeName = $srcAttributePrefix . 'srcset';
            $attributes[$attributeName] = "$img, $img2x 2x";
        } else {
            $attributeName = $srcAttributePrefix . 'src';
            $attributes[$attributeName] = $img;
        }

        if ($lazyLoad) {
            $width = $image['bySize'][$size]['width'];
            $height = $image['bySize'][$size]['height'];
            $placeholderSrc = self::generateImageSvgPlaceholder(['width' => $width, 'height' => $height]);

            $attributes['src'] = $placeholderSrc;
        }

        $attributesToPrint = [];

        foreach ($attributes as $attr => $value) {
            $attributesToPrint[] = $attr . '="' . $value . '"';
        }

        return implode(PHP_EOL, $attributesToPrint);
    }

    public static function generateImageSvgPlaceholder($params)
    {
        $width = $params['width'];
        $height = $params['height'];

        return "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='$width' height='$height' viewBox='0 0 1 1'%3E%3C/svg%3E";
    }

    public static function appendParamToUrl($params)
    {
        list(
            'url' => $url,
            'key' => $key,
            'value' => $value
        ) = $params;

        $replace = false;

        if (isset($params['replace'])) {
            $replace = $params['replace'];
        }

        if (!is_array($value)) {
            $value = [$value];
        } else {
            $replace = false;
        }

        foreach ($value as $qValue) {
            $query = parse_url($url, PHP_URL_QUERY);

            if ($query) {
                if ($replace) {
                    parse_str($query, $queryParams);
                    $queryParams[$key] = $qValue;
                    $url = str_replace("?$query", '?' . http_build_query($queryParams), $url);
                } else {
                    $queryParams = [];
                    $queryParams[$key] = $qValue;
                    $url .= '&' . http_build_query($queryParams);
                }
            } else {
                $url .= '?' . urlencode($key) . '=' . urlencode($qValue);
            }
        }

        return $url;
    }

    public static function imagesBlock($params, $content, $smarty)
    {
        $webpEnabled = isset($params['webpEnabled']) ? $params['webpEnabled'] : \Configuration::get(WebpConfiguration::THEMECORE_WEBP_ENABLED);

        if ($webpEnabled && !empty($content)) {
            $pictureGenerator = new WebpPictureGenerator($content);

            $pictureGenerator
                ->loadContent()
                ->generatePictureTags();

            return $pictureGenerator->getContent();
        }

        return $content;
    }

    public static function displayMobileBlock($params, $content, $smarty)
    {
        if (!empty($content) && \Context::getContext()->isMobile()) {
            return $content;
        }

        return '';
    }

    public static function displayDesktopBlock($params, $content, $smarty)
    {
        if (!empty($content) && !\Context::getContext()->isMobile()) {
            return $content;
        }

        return '';
    }

    public static function cmsImagesBlock($params, $content, $smarty)
    {
        $doc = new \DOMDocument();
        $doc->loadHTML('<meta http-equiv="Content-Type" content="charset=utf-8">' . $content);
        $context = \Context::getContext();

        $images = $doc->getElementsByTagName('img');

        $domains = \Tools::getDomains();
        $medias = [
            \Configuration::get('PS_MEDIA_SERVER_1'),
            \Configuration::get('PS_MEDIA_SERVER_2'),
            \Configuration::get('PS_MEDIA_SERVER_3'),
        ];

        $internalUrls = [];

        foreach ($domains as $domain => $options) {
            $internalUrls[] = $domain;
        }

        foreach ($medias as $media) {
            if ($media) {
                $internalUrls[] = $media;
            }
        }

        foreach ($images as $image) {
            $newImg = $doc->createElement('img');
            $src = urldecode($image->attributes->getNamedItem('src')->nodeValue);

            if (!preg_match('/' . implode('|', $internalUrls) . '/i', $src)) {
                $newImg->setAttribute('data-external-url', '');
            }

            foreach ($image->attributes as $attribute) {
                $newImg->setAttribute($attribute->nodeName, $attribute->nodeValue);
            }

            $image->parentNode->replaceChild($newImg, $image);
        }

        $content = $doc->saveHTML();
        $content = str_replace('<meta http-equiv="Content-Type" content="charset=utf-8">', '', $content);

        $webpEnabled = isset($params['webpEnabled']) ? $params['webpEnabled'] : \Configuration::get(WebpConfiguration::THEMECORE_WEBP_ENABLED);

        if ($webpEnabled && !empty($content)) {
            $pictureGenerator = new WebpPictureGenerator($content);

            $pictureGenerator
                ->loadContent()
                ->generatePictureTags();

            return $pictureGenerator->getContent();
        }

        return $content;
    }



/* CUSTOM ADDITIONS BELOW */


    public static function isBright($hexColor)
    {
        $calculator = new ColorBrightnessCalculator();
        return $calculator->isBright($hexColor);
    }

    public static function displaySvgIcon($params){
    /*  
        Helper to display SVG icons stored in themes/falcon/_dev/img/icons/
        registered under public_html/modules/is_themecore/src/Hook/Smarty.php

        Usage examples in a TPL file:

        {svg_icon file='person.svg' fill='red' width='24' height='24'}
        {svg_icon file='person.svg'}
    */

        // Grab svg under falcon/_dev/img and display an error if not found
        if (empty($params['file'])) {
            return '';
        }
        $icon_path = _PS_THEME_DIR_ . '/_dev/img/' . basename($params['file']);
        
        if (!is_file($icon_path)) {
            if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_) {
                return 'Invalid SVG path: ' . htmlspecialchars($icon_path);
            }
            return '';
        }

        $svg_content = file_get_contents($icon_path);

        /* Define an associative array of SVG properties
        If the property is a style, addd it in a style tag.
        If the property is an attribute, replace it in the svg code.

        This reduces the risk of interfering with other attributes. */ 
        $svg_props = array( 
            'width' => 'style',
            'height' => 'style',
            'opacity' => 'style',
            'fill' => 'attribute',
            'stroke' => 'attribute',
        );

        // Styles
        $styles = [];
        foreach ($svg_props as $prop => $type) {
            if ($type === 'style' && !empty($params[$prop])) {
                $value = $params[$prop];
                if (in_array($prop, ['width', 'height']) && is_numeric($value)) {
                    $value .= 'px';
                }
                $styles[] = $prop . ': ' . $value;
            }
        }
        if (!empty($styles)) {
            $style_attr = 'style="' . implode('; ', $styles) . '"';
            $svg_content = preg_replace('/(<svg[^>]*?)>/', '$1 ' . $style_attr . '>', $svg_content, 1);
        }

        // Attributes
        foreach ($svg_props as $prop => $type) {
            if ($type === 'attribute' && !empty($params[$prop])) {
                $value = $params[$prop];
                // Use word boundaries to avoid matching partial names like fill-opacity or stroke-width
                // Replace ALL occurrences of the attribute
                $svg_content = preg_replace(
                    '/\b' . preg_quote($prop) . '\b\s*=\s*"[^"]*"/',
                    $prop . '="' . $value . '"',
                    $svg_content
                );
            }
        }

        return $svg_content;
    }
    

    public static function displayPriceSplit($price, $show_currency = false) {
        /* Helper to split the price into euros and cents to make it more stylish
        registered under public_html/modules/is_themecore/src/Hook/Smarty.php

        Usage examples in a TPL file:
        {price_split price=$product.price}

        */
        //Convert to a string and only keep numbers, commas and dots
        $currency_name = \Context::getContext()->currency->name;
        $currency_symbol = \Context::getContext()->currency->symbol;
        $price_string = implode(',', $price);
        $price_string = preg_replace('/[^0-9,.]/', '', $price_string);
       
        // Split by comma and wrap each part in a span
        $price_parts = explode(',', $price_string);
        if (count($price_parts) >= 2) {
            echo '<span class="currency" aria-label="' . htmlspecialchars($currency_name) . '">' . ($show_currency ? $currency_symbol : '') .  $price_parts[0] . '</span>';
            echo '<sup class="cents" aria-label="cents">' . $price_parts[1] . '</sup>';
        } else {
            foreach ($price_parts as $part) {
            echo '<span>' . $part . '</span>';
            }
        }
    }
}