<?php
/**
 * index.php —— 站点唯一入口
 *   /              → 按域名从 1.html~50.html 里挑一个模板
 *   /robots.txt    → 动态输出
 *   /sitemap.xml   → 动态输出本域名站点地图（/sitemap-2.xml … 自动拆分）
 *   /xxx           → pages/xxx.html
 *   其它           → 404
 */
declare(strict_types=1);

require_once __DIR__ . '/core.php';
core_init();

$host = req_host();
if ($host === '') {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo "400 Bad Host\n";
    exit;
}

// 该域名第一次被访问时自动登记进 domains.txt
register_domain($host);

$path = (string) (parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/');
$path = (string) preg_replace('~/{2,}~', '/', rawurldecode($path));
if ($path === '') {
    $path = '/';
}

/* 1) robots.txt */
if (preg_match('~^/robots\.txt$~i', $path)) {
    serve_robots($host);
    exit;
}

/* 2) sitemap.xml / sitemap-N.xml */
if (preg_match('~^/sitemap(?:-(\d+))?\.xml$~i', $path, $m)) {
    serve_sitemap($host, (isset($m[1]) && $m[1] !== '') ? (int) $m[1] : 0);
    exit;
}

/* 3) 首页 */
if (in_array($path, ['/', '/index.php', '/index.html', '/index.htm'], true)) {
    serve_home($host);
    exit;
}

/* 4) 内页：/about → pages/about.html */
$slug = (string) preg_replace('~\.html?$~i', '', trim($path, '/'));
if ($slug !== '' && preg_match('~^[A-Za-z0-9][A-Za-z0-9_\-/]{0,190}$~', $slug)) {
    $file = APP_ROOT . '/pages/' . $slug . '.html';
    if (is_file($file)) {
        serve_page($file, $host, $slug);
        exit;
    }
}

/* 5) 404 */
serve_404();