<?php
/**
 * Shared bootstrap for CMS-backed public pages.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/SiteContent.php';

if (!isset($siteContent) || !($siteContent instanceof SiteContent)) {
    $siteContent = new SiteContent();
}

if (!isset($region)) {
    $allowedRegions = array_merge(['global'], is_string(SUPPORTED_REGIONS) ? unserialize(SUPPORTED_REGIONS) : ['usa','europe','africa']);

    // Priority: ?region=GET (and persist to session) -> session region -> default
    if (isset($_GET['region'])) {
        $r = strtolower((string) $_GET['region']);
        if (in_array($r, $allowedRegions, true)) {
            $_SESSION['region'] = $r;
            $region = $r;
        } else {
            $region = 'global';
        }
    } elseif (!empty($_SESSION['region']) && in_array($_SESSION['region'], $allowedRegions, true)) {
        $region = $_SESSION['region'];
    } else {
        $region = defined('DEFAULT_REGION') ? DEFAULT_REGION : 'global';
        if (!in_array($region, $allowedRegions, true)) {
            $region = 'global';
        }
    }
}

if (!function_exists('sc_text')) {
    function sc_text(string $page, string $key, string $default = '', string $region = 'global'): void {
        global $siteContent;
        echo htmlspecialchars($siteContent->getBlockValue($page, $key, $region, $default));
    }
}

if (!function_exists('sc_html')) {
    function sc_html(string $page, string $key, string $default = '', string $region = 'global'): void {
        global $siteContent;
        echo $siteContent->getBlockValue($page, $key, $region, $default);
    }
}
