<?php
/**
 * Фронт-контроллер (точка входа).
 * Маршрутизация: index.php?page=<page>&...
 */
require_once __DIR__ . '/includes/functions.php';

// Проверка режима технического обслуживания (пропускаем login/logout, чтобы админ мог войти)
$publicPages = ['login', 'logout'];
if (get_setting('site_maintenance') === '1' && !is_admin() && !in_array($_GET['page'] ?? 'home', $publicPages, true)) {
    http_response_code(503);
    $pageTitle = 'Техническое обслуживание — ' . SITE_NAME;
    require __DIR__ . '/includes/header.php';
    echo '<div class="container py-5 text-center">
            <i class="fa-solid fa-wrench text-bronze" style="font-size:4rem;margin-bottom:1rem"></i>
            <h1 class="display-5 text-uppercase">Техническое обслуживание</h1>
            <p class="lead text-muted-2" style="max-width:600px;margin:0 auto">'
            . e(get_setting('site_maintenance_message'))
            . '</p>
            <div class="mt-4"><a href="' . url_with('login') . '" class="btn btn-outline-bronze"><i class="fa-solid fa-right-to-bracket me-1"></i>Вход для администратора</a></div>
          </div>';
    require __DIR__ . '/includes/footer.php';
    exit;
}

// Белый список публичных страниц
$routes = [
    'home'      => 'home.php',
    'blog'      => 'blog.php',
    'post'      => 'post.php',
    'shop'      => 'shop.php',
    'order'     => 'order.php',
    'about'     => 'about.php',
    'contacts'  => 'contacts.php',
    'login'     => 'login.php',
    'register'  => 'register.php',
    'forgot'    => 'forgot.php',
    'reset'     => 'reset.php',
    'verify_email' => 'verify_email.php',
    'profile'   => 'profile.php',
    'logout'    => 'logout.php',
    'sitemap'   => 'sitemap.php',
    'robots'    => 'robots.php',
    'search'    => 'search.php',
    'payment'   => 'payment.php',
    'webhook'   => 'webhook.php',
    'robokassa_result' => 'robokassa_result.php',
    'rss'       => 'rss.php',
    'download'  => 'download.php',
    'cart'      => 'cart.php',
    'product'   => 'product.php',
    'terms'     => 'terms.php',
    'privacy'   => 'privacy.php',
    'push_subscribe'   => 'push_subscribe.php',
    'push_unsubscribe' => 'push_unsubscribe.php',
    'push_latest'      => 'push_latest.php',
    'push_icon'        => 'push_icon.php',
    'notifications'    => 'notifications.php',
    'newsletter'       => 'newsletter.php',
    'newsletter_unsubscribe' => 'newsletter_unsubscribe.php',
];

$page = $_GET['page'] ?? 'home';
$file = $routes[$page] ?? null;

// География посетителей (для карты посещений в админке). Пишется до вывода.
record_visit();

// Каноникализация ЧПУ: если включены и запрос пришёл через ?page=... — редирект 301 на красивый адрес
if (pretty_urls_enabled() && $file && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    $canonParams = $_GET;
    $canonPath = clean_url_path($page, $canonParams);
    if ($canonPath !== null) {
        $uri = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?? '';
        // Уже ЧПУ-адрес (запрос через rewrite) — не редиректим
        if (str_ends_with($uri, '/index.php')) {
            unset($canonParams['page']);
            $query = http_build_query($canonParams);
            redirect(SITE_URL . '/' . $canonPath . ($query !== '' ? '?' . $query : ''), 301);
        }
    }
}

if (!$file || !file_exists(__DIR__ . '/pages/' . $file)) {
    // 404
    http_response_code(404);
    $pageTitle = 'Страница не найдена — ' . SITE_NAME;
    $activePage = '404';
    require __DIR__ . '/includes/header.php';
    echo '<div class="container py-5 text-center">
            <h1 class="display-3 text-bronze">404</h1>
            <p class="lead">К сожалению, такой страницы не существует.</p>
            <a href="' . url_with('home') . '" class="btn btn-bronze mt-3"><i class="fa-solid fa-house me-1"></i>На главную</a>
          </div>';
    require __DIR__ . '/includes/footer.php';
    exit;
}

require __DIR__ . '/pages/' . $file;
