<?php
declare(strict_types=1);

$legacyPageFile = (string) theme_data('legacy_page_file', '');

if ($legacyPageFile !== '' && is_file($legacyPageFile) && basename($legacyPageFile) !== 'home.php') {
    load_template($legacyPageFile, theme_context());
    return;
}

$dbPage = theme_data('db_page');
$pageTitle = is_array($dbPage) ? (string) ($dbPage['title'] ?? theme_data('title', 'Page')) : (string) theme_data('title', 'Page');
$content = is_array($dbPage) ? (string) ($dbPage['content'] ?? '') : (string) theme_data('content', '');
$headerContent = is_array($dbPage) ? (string) ($dbPage['header_content'] ?? theme_data('header_content', '')) : (string) theme_data('header_content', '');
$footerContent = is_array($dbPage) ? (string) ($dbPage['footer_content'] ?? theme_data('footer_content', '')) : (string) theme_data('footer_content', '');
$hiddenBlocksJson = is_array($dbPage) ? (string) ($dbPage['hidden_blocks_json'] ?? theme_data('hidden_blocks_json', '')) : (string) theme_data('hidden_blocks_json', '');
$homepageBlocks = is_array(theme_data('homepage_blocks')) ? theme_data('homepage_blocks') : [];
$hiddenBlocks = json_decode($hiddenBlocksJson, true);
if (!is_array($hiddenBlocks)) {
    $hiddenBlocks = [];
}
$hiddenBlocks = array_values(array_unique(array_filter(array_map(static function ($block): string {
    return strtolower(trim((string) $block));
}, $hiddenBlocks))));
$pluginRegistry = is_array($GLOBALS['plugins_registry'] ?? null) ? $GLOBALS['plugins_registry'] : [];
$blockPluginMap = [];
foreach ($pluginRegistry as $pluginSlug => $pluginMeta) {
    $pluginBlocks = is_array($pluginMeta['blocks'] ?? null) ? $pluginMeta['blocks'] : [];
    foreach ($pluginBlocks as $pluginBlock) {
        $blockPluginMap[strtolower((string) $pluginBlock)] = strtolower((string) $pluginSlug);
    }
}
$subpageBlocks = array_values(array_filter($homepageBlocks, static function (string $block) use ($hiddenBlocks, $blockPluginMap): bool {
    $pluginSlug = $blockPluginMap[strtolower($block)] ?? '';
    if ($pluginSlug !== '' && in_array($pluginSlug, $hiddenBlocks, true)) {
        return false;
    }

    if (in_array($block, $hiddenBlocks, true)) {
        return false;
    }

    return true;
}));
?>
<?php if ($headerContent !== ''): ?>
<section class="contener box cms-page-shell">
    <div><?php echo $headerContent; ?></div>
</section>
<?php endif; ?>
<?php if (function_exists('render_blocks') && $subpageBlocks !== []): ?>
<?php render_blocks($subpageBlocks); ?>
<?php endif; ?>
<section class="contener box cms-page-shell">
    <div><?php echo $content; ?></div>
</section>
<?php if ($footerContent !== ''): ?>
<section class="contener box cms-page-shell">
    <div><?php echo $footerContent; ?></div>
</section>
<?php endif; ?>
