<?php
declare(strict_types=1);

define('CMS_ROOT', __DIR__);

require_once __DIR__ . '/core/config.php';
require_once __DIR__ . '/core/db.php';
require_once __DIR__ . '/core/platform.php';

$cmsConfig = cms_load_config(__DIR__);
cms_platform_boot($cmsConfig);
$cmsTheme = cms_active_theme($cmsConfig);
$cmsSiteTitle = cms_site_title_value($cmsConfig);
$cmsInfoChartBaseSlug = function_exists('cms_info_chart_base_slug') ? cms_info_chart_base_slug($cmsConfig) : 'info-chart';
$cmsActivePlugins = cms_get_active_plugins($cmsConfig);
$cmsHomepageBlocks = cms_get_homepage_blocks_wp($cmsConfig);

define('CMS_SITE_TITLE', $cmsSiteTitle);
define('CMS_THEME', $cmsTheme);
define('CMS_THEME_DIR', CMS_ROOT . '/content/themes/' . CMS_THEME);
define('CMS_THEME_MOD_DIR', CMS_THEME_DIR . '/mod');
define('CMS_THEME_PAGE_DIR', CMS_THEME_DIR . '/pages');
define('CMS_PLUGIN_DIR', CMS_ROOT . '/content/plugins');
define('CMS_THEME_FUNCTIONS_FILE', CMS_THEME_DIR . '/functions.php');
define('CMS_HOOKS_FILE', CMS_ROOT . '/core/hooks.php');
define('CMS_SHORTCODES_FILE', CMS_ROOT . '/core/shortcodes.php');
define('CMS_BLOCKS_FILE', CMS_ROOT . '/core/blocks.php');
define('CMS_PLUGIN_LOADER_FILE', CMS_ROOT . '/core/plugins.php');

if (!is_dir(CMS_ROOT . '/core/sessions')) {
    @mkdir(CMS_ROOT . '/core/sessions', 0775, true);
}

if (is_dir(CMS_ROOT . '/core/sessions') && is_writable(CMS_ROOT . '/core/sessions')) {
    ini_set('session.save_path', CMS_ROOT . '/core/sessions');
    session_save_path(CMS_ROOT . '/core/sessions');
}

if (session_status() !== PHP_SESSION_ACTIVE) {
    @session_start();
}

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');

if (!headers_sent()) {
    header("Content-Security-Policy: frame-ancestors 'self'; upgrade-insecure-requests", false);
}

if (is_file(CMS_HOOKS_FILE)) {
    require_once CMS_HOOKS_FILE;
}
if (is_file(CMS_SHORTCODES_FILE)) {
    require_once CMS_SHORTCODES_FILE;
}
if (is_file(CMS_BLOCKS_FILE)) {
    require_once CMS_BLOCKS_FILE;
}
if (is_file(CMS_PLUGIN_LOADER_FILE)) {
    require_once CMS_PLUGIN_LOADER_FILE;
}
if (is_file(CMS_THEME_FUNCTIONS_FILE)) {
    require_once CMS_THEME_FUNCTIONS_FILE;
}
if (function_exists('load_plugins')) {
    load_plugins(CMS_PLUGIN_DIR, $cmsActivePlugins);
}
if (function_exists('do_action')) {
    do_action('init');
}

$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($requestUri, PHP_URL_PATH) ?: '/';
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$basePath = str_replace('\\', '/', dirname($scriptName));

if ($basePath !== '/' && $basePath !== '.') {
    if (strpos($path, $basePath) === 0) {
        $path = substr($path, strlen($basePath));
    }
}

$path = '/' . ltrim($path, '/');

$hasFileExtension = (bool) preg_match('/\.[a-z0-9]+$/i', basename($path));
if (
    $_SERVER['REQUEST_METHOD'] === 'GET'
    && $path !== '/'
    && !str_ends_with($path, '/')
    && !$hasFileExtension
) {
    $queryString = (string) ($_SERVER['QUERY_STRING'] ?? '');
    $redirectPath = $path . '/';

    if ($basePath !== '/' && $basePath !== '.') {
        $redirectPath = rtrim($basePath, '/') . $redirectPath;
    }

    $redirectUrl = $redirectPath . ($queryString !== '' ? '?' . $queryString : '');
    header('Location: ' . $redirectUrl, true, 301);
    exit;
}

$trimmedPath = trim($path, '/');
$segments = $trimmedPath === '' ? [] : array_values(array_filter(explode('/', $trimmedPath), 'strlen'));

$pageSlug = 'home';

if (!empty($_GET['page']) && is_string($_GET['page'])) {
    $pageSlug = strtolower(trim((string) $_GET['page']));
}

if (!empty($segments)) {
    if ($segments[0] === 'passing-record') {
        require CMS_PLUGIN_DIR . '/free_matka_pass/passing_record.php';
        exit;
    }

    if (in_array($segments[0], [$cmsInfoChartBaseSlug, 'info-chart'], true) && isset($segments[1])) {
        $chartSlug = $segments[1];

        if (preg_match('/^([a-z0-9-]+)-jodi$/i', $chartSlug, $matches)) {
            $_GET['alias'] = $matches[1];
            require CMS_PLUGIN_DIR . '/info-chart/jodi_chart.php';
            exit;
        }

        if (preg_match('/^([a-z0-9-]+)-panel$/i', $chartSlug, $matches)) {
            $_GET['alias'] = $matches[1];
            require CMS_PLUGIN_DIR . '/info-chart/panel_chart.php';
            exit;
        }

        $allowedInfoScripts = ['data', 'jodi_chart', 'panel_chart'];
        $infoScript = strtolower(pathinfo($chartSlug, PATHINFO_FILENAME));
        if (in_array($infoScript, $allowedInfoScripts, true)) {
            require CMS_PLUGIN_DIR . '/info-chart/' . $infoScript . '.php';
            exit;
        }
    }

    $pluginFolders = ['free_matka_pass', 'weekly'];
    if (in_array($segments[0], $pluginFolders, true)) {
        $pluginName = $segments[0];
        $pluginFile = $segments[1] ?? 'index';

        if (preg_match('/^[a-z0-9._-]+$/i', $pluginFile)) {
            $pluginPath = CMS_PLUGIN_DIR . '/' . $pluginName . '/' . pathinfo($pluginFile, PATHINFO_FILENAME) . '.php';
            if (is_file($pluginPath)) {
                require $pluginPath;
                exit;
            }
        }
    }

    if ($segments[0] === 'pages' && isset($segments[1])) {
        $pageSlug = $segments[1];
    } else {
        $pageSlug = $segments[0];
    }
}

$pageSlug = strtolower(trim((string) $pageSlug));
$pageSlug = preg_replace('/[^a-z0-9\-]/', '', $pageSlug) ?: 'home';

if (function_exists('render')) {
    if ($pageSlug === '' || $pageSlug === '/') {
        $pageSlug = 'home';
    }

    $dbPageExists = function_exists('cms_get_page_by_slug') && is_array(cms_get_page_by_slug($pageSlug));

    if ($pageSlug !== 'home' && function_exists('theme_page_exists') && !theme_page_exists($pageSlug) && !$dbPageExists) {
        http_response_code(404);
        $pageSlug = '404';
    }

    render($pageSlug, [
        'page' => $pageSlug,
        'site_title' => CMS_SITE_TITLE,
        'active_theme' => CMS_THEME,
        'homepage_blocks' => $cmsHomepageBlocks,
        'request_uri' => $requestUri,
        'segments' => $segments,
    ]);
    exit;
}

$pageFile = CMS_THEME_PAGE_DIR . '/' . $pageSlug . '.php';

if (!is_file($pageFile)) {
    http_response_code(404);
    $pageSlug = '404';
}

if ($pageSlug === '404') {
    $pageFile = CMS_THEME_PAGE_DIR . '/404.php';
}

if (!is_file($pageFile)) {
    http_response_code(404);
    exit('404 Not Found');
}

require CMS_THEME_MOD_DIR . '/_header.php';
require $pageFile;
require CMS_THEME_MOD_DIR . '/_footer.php';
 
