<?php
declare(strict_types=1);

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

if (!function_exists('register_block')) {
    function register_block(string $name, callable $callback): void
    {
        $name = strtolower(trim($name));
        if ($name === '') {
            return;
        }

        $GLOBALS['cms_blocks'][$name] = $callback;
    }
}

if (!function_exists('get_registered_blocks')) {
    function get_registered_blocks(): array
    {
        return is_array($GLOBALS['cms_blocks'] ?? null) ? $GLOBALS['cms_blocks'] : [];
    }
}

if (!function_exists('render_blocks')) {
    function render_blocks(array $blocks): void
    {
        $registeredBlocks = get_registered_blocks();

        foreach ($blocks as $blockName) {
            $blockName = strtolower(trim((string) $blockName));
            if ($blockName === '' || !isset($registeredBlocks[$blockName]) || !is_callable($registeredBlocks[$blockName])) {
                continue;
            }

            try {
                call_user_func($registeredBlocks[$blockName]);
            } catch (Throwable $exception) {
                error_log('[CMS Block] ' . $blockName . ' failed: ' . $exception->getMessage());
            }
        }
    }
}
