<?php
declare(strict_types=1);

if (!isset($GLOBALS['cms_actions']) || !is_array($GLOBALS['cms_actions'])) {
    $GLOBALS['cms_actions'] = [];
}

if (!isset($GLOBALS['cms_filters']) || !is_array($GLOBALS['cms_filters'])) {
    $GLOBALS['cms_filters'] = [];
}

if (!function_exists('add_action')) {
    function add_action(string $hook, callable $callback, int $priority = 10): void
    {
        $GLOBALS['cms_actions'][$hook][$priority][] = $callback;
    }
}

if (!function_exists('do_action')) {
    function do_action(string $hook, ...$args): void
    {
        if (empty($GLOBALS['cms_actions'][$hook])) {
            return;
        }

        ksort($GLOBALS['cms_actions'][$hook]);

        foreach ($GLOBALS['cms_actions'][$hook] as $callbacks) {
            foreach ($callbacks as $callback) {
                call_user_func_array($callback, $args);
            }
        }
    }
}

if (!function_exists('add_filter')) {
    function add_filter(string $hook, callable $callback, int $priority = 10): void
    {
        $GLOBALS['cms_filters'][$hook][$priority][] = $callback;
    }
}

if (!function_exists('apply_filters')) {
    function apply_filters(string $hook, $value, ...$args)
    {
        if (empty($GLOBALS['cms_filters'][$hook])) {
            return $value;
        }

        ksort($GLOBALS['cms_filters'][$hook]);

        foreach ($GLOBALS['cms_filters'][$hook] as $callbacks) {
            foreach ($callbacks as $callback) {
                $value = call_user_func_array($callback, array_merge([$value], $args));
            }
        }

        return $value;
    }
}
