<?php
/**
 * Фронт-контроллер сайта Metrostroi.
 * Все запросы вида /news/view/1 попадают сюда.
 */

require __DIR__ . '/bootstrap.php';

/* -------------------------------------------------------------------------
 * Разбор маршрута
 * ---------------------------------------------------------------------- */
$pageParam = $_GET['page'] ?? null;

if (is_string($pageParam) && $pageParam !== '') {
    $path = $pageParam;
} else {
    $uri = (string) (parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
    $scriptName = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? '/index.php'));
    $baseDir = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
    if ($baseDir !== '' && $baseDir !== '/' && str_starts_with($uri, $baseDir)) {
        $uri = substr($uri, strlen($baseDir));
    }
    $path = $uri;
}

$path = rawurldecode($path);
$path = trim($path, '/');

$lnk = ($path === '') ? ['home'] : explode('/', $path);

$mode = (string) ($lnk[0] ?? 'home');
if ($mode === 'index.php' || $mode === '') {
    $mode = 'home';
    $lnk = ['home'];
}

/* Разрешаем только безопасные имена страниц */
if (!preg_match('/^[a-zA-Z0-9_]+$/', $mode)) {
    $mode = '404';
}

$pageFile = ROOT . 'pages/' . $mode . '.php';
if (!is_file($pageFile)) {
    $pageFile = ROOT . 'pages/404.php';
    http_response_code(404);
}

/* -------------------------------------------------------------------------
 * Вывод
 * ---------------------------------------------------------------------- */
if (!headers_sent()) {
    header('Content-Type: text/html; charset=utf-8');
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: SAMEORIGIN');
    header('Referrer-Policy: strict-origin-when-cross-origin');
}

if (!function_exists('inject_csrf_fields')) {
    /**
     * Автоматически добавляет CSRF-токен во все POST-формы,
     * чтобы не править каждый шаблон вручную.
     */
    function inject_csrf_fields(string $html): string
    {
        $token = csrf_token();
        if ($token === '') {
            return $html;
        }
        $field = csrf_field();

        return (string) preg_replace_callback('/<form\b[^>]*>/i', static function (array $m) use ($field): string {
            $tag = $m[0];
            if (!preg_match('/\bmethod\s*=\s*["\']?post["\']?/i', $tag)) {
                return $tag;
            }
            return $tag . $field;
        }, $html);
    }
}

ob_start();

try {
    include $pageFile;
} catch (Throwable $e) {
    /* Не показываем стектрейс посетителям */
    if (!empty($config['debug'])) {
        $buffer = ob_get_clean();
        echo $buffer;
        echo '<pre style="background:#fff;color:#900;padding:1em;white-space:pre-wrap;">'
            . e($e->getMessage()) . "\n\n" . e($e->getFile() . ':' . $e->getLine())
            . "\n\n" . e($e->getTraceAsString()) . '</pre>';
        exit;
    }

    ob_clean();
    error_log('Metrostroi fatal: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    include ROOT . 'tpl/500.html';
    exit;
}

$html = ob_get_clean();

echo inject_csrf_fields($html);
