<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Support;

use enshrined\svgSanitize\Sanitizer;

defined('ABSPATH') || exit;

/**
 * Marker URL handling.
 *
 * This deliberately contains no marker-editor shapes, glyphs, or catalogue, so
 * it works with nothing but the packaged SVG files. Where the marker-editor
 * package is present it layers editor composition data on top.
 */
final class MarkerRuntime
{
    private const MAX_DATA_URI_BYTES = 100 * 1024;

    public static function dir(): string
    {
        return CLIQ_SL_PATH . 'assets/markers/';
    }

    public static function url(string $file): string
    {
        return CLIQ_SL_URL . 'assets/markers/' . $file;
    }

    public static function rebaseUrl(string $url): string
    {
        if ($url !== '' && preg_match('~/assets/markers/([^/?#]+)$~', $url, $matches)) {
            return self::url($matches[1]);
        }

        return $url;
    }

    public static function frontendUrl(string $url): string
    {
        $url = trim(self::rebaseUrl($url));
        if ($url === '') {
            return '';
        }
        if (! str_starts_with(strtolower($url), 'data:')) {
            return esc_url_raw($url);
        }
        if (! preg_match('/^data:image\/svg\+xml,(.*)$/is', $url, $matches)) {
            return '';
        }

        $svg = rawurldecode($matches[1]);
        if ($svg === '' || strlen($svg) > self::MAX_DATA_URI_BYTES || stripos($svg, '<svg') === false) {
            return '';
        }

        $sanitizer = new Sanitizer();
        $sanitizer->removeRemoteReferences(true);
        $clean = $sanitizer->sanitize($svg);
        if (! is_string($clean) || $clean === '' || stripos($clean, '<svg') === false) {
            return '';
        }

        return 'data:image/svg+xml,' . rawurlencode($clean);
    }

    /**
     * Discover the SVG files physically packaged with this plugin.
     *
     * @return array<int, array{name:string,file:string,url:string}>
     */
    public static function presets(): array
    {
        $files = glob(self::dir() . '*.svg') ?: [];
        sort($files);

        $presets = [];
        foreach ($files as $path) {
            $file = basename($path);
            if (str_starts_with($file, '_')) {
                continue;
            }

            $presets[] = [
                'name' => ucwords(trim(str_replace(['-', '.svg'], [' ', ''], $file))),
                'file' => $file,
                'url' => self::url($file),
            ];
        }

        return $presets;
    }
}
