<?php

declare(strict_types=1);



class Shortcode
{
     
    private static ?array $widgets = null;

     
    private static function all(): array
    {
        if (self::$widgets !== null) {
            return self::$widgets;
        }
        $widgets = [];
        foreach (glob(APP_ROOT . '/src/Widgets/*Widget.php') ?: [] as $file) {
            require_once $file;
            $class = basename($file, '.php');
            if ($class === 'Widget' || !class_exists($class) || !is_subclass_of($class, 'Widget')) {
                continue;
            }
            $widget = new $class();
            $widgets[$widget->code()] = $widget;
        }
        return self::$widgets = $widgets;
    }

    

    public static function widgets(): array
    {
        $out = [];
        foreach (self::all() as $code => $w) {
            $out[$code] = ['name' => $w->name(), 'desc' => $w->description(), 'icon' => $w->icon()];
        }
        return $out;
    }

    

    public static function expand(string $html, array $ctx = []): string
    {
        if ($html === '' || strpos($html, '[') === false) {
            return $html;
        }
        foreach (self::all() as $code => $w) {
             
             
            $pattern = '~(?:<p>\s*)?\[' . preg_quote($code, '~') . '\](?:\s*</p>)?~i';
            if (preg_match($pattern, $html) !== 1) {
                continue;
            }
            $html = preg_replace_callback($pattern, static function () use ($w, $ctx): string {
                return $w->render($ctx);
            }, $html) ?? $html;
        }
        return $html;
    }

     
    public static function contains(string $content, ?string $code = null): bool
    {
        foreach (array_keys(self::all()) as $c) {
            if ($code !== null && $c !== $code) {
                continue;
            }
            if (stripos($content, '[' . $c . ']') !== false) {
                return true;
            }
        }
        return false;
    }
}
