<?php
require_once 'config.php';
require_once 'functions.php';

$host = $_SERVER['HTTP_HOST'] ?? '';
$host = preg_replace('/^www\./i', '', $host);
$host = explode(':', $host)[0];

$main_domains = [];
foreach (get_site_domains() as $url) {
    $main_domains[] = parse_url($url, PHP_URL_HOST);
}

$is_main = in_array($host, $main_domains);
$subdomain = '';
$base_domain = '';

if (!$is_main) {
    foreach ($main_domains as $domain) {
        if (substr($host, -strlen($domain) - 1) === '.' . $domain) {
            $subdomain = substr($host, 0, strlen($host) - strlen($domain) - 1);
            $base_domain = $domain;
            break;
        }
    }
}

if (!$is_main && empty($subdomain)) {
    http_response_code(404);
    exit('404 Not Found');
}

$file = null;
$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$request_uri = '/' . ltrim($request_uri, '/');

if ($is_main && ($request_uri === '/' || $request_uri === '/index.html')) {
    // 主域名首页
    $file = __DIR__ . '/domains/' . $host . '/index.html';
} elseif ($is_main) {
    // 主域名内页：second_level/09sq.com/__main__/kjmj/9222.html
    $slug = trim($request_uri, '/');
    if (preg_match('/\.html$/i', $slug)) {
        $slug = substr($slug, 0, -5);
    }
    $slug = preg_replace('/[^a-zA-Z0-9\-_\/]/', '', $slug);
    $slug = substr($slug, 0, 100);
    if (!empty($slug)) {
        $file = SECOND_LEVEL_DIR . $host . '/' . MAIN_INNER_PREFIX . '/' . $slug . '.html';
    }
} elseif (!empty($subdomain) && !empty($base_domain)) {
    // 二级域名（如 amlgwr.09sq.com）
    $base_dir = SECOND_LEVEL_DIR . $base_domain . '/' . $subdomain;
    if ($request_uri === '/' || $request_uri === '/index.html') {
        // 二级域名首页：second_level/09sq.com/amlgwr/index.html
        $file = $base_dir . '/index.html';
    } else {
        // 二级域名内页：second_level/09sq.com/amlgwr/kjmj/9222.html
        $slug = trim($request_uri, '/');
        if (preg_match('/\.html$/i', $slug)) {
            $slug = substr($slug, 0, -5);
        }
        $slug = preg_replace('/[^a-zA-Z0-9\-_\/]/', '', $slug);
        $slug = substr($slug, 0, 100);
        if (!empty($slug)) {
            $file = $base_dir . '/' . $slug . '.html';
        }
    }
}

// 文件存在 → 直接输出
if ($file && file_exists($file)) {
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: public, max-age=3600');
    readfile($file);
    exit;
}

// 文件不存在 → 记录缺失
$missing_uri = $host . $request_uri;
$ignore_patterns = [
    '/\.(json|php|asp|aspx|jsp|do|action)$/i',
    '/\.(jpg|jpeg|png|gif|webp|ico|bmp|svg)$/i',
    '/\.(css|js|map)$/i',
    '/\.(xml|txt|gz|tar|zip|rar|sql|bak|log)$/i',
    '/\.(yml|yaml|toml|cfg|conf|config|key|pem|crt|csr)$/i',
    '/\.(git|env|env\.example|htaccess|passwd|shadow|netrc|npmrc)$/i',
    '/\/robots\.txt$/i',
    '/\/favicon\.ico$/i',
];

$should_record = true;
foreach ($ignore_patterns as $pattern) {
    if (preg_match($pattern, $request_uri)) {
        $should_record = false;
        break;
    }
}

if ($should_record) {
    record_missing($missing_uri);
}

// 输出 404
http_response_code(404);
$error_page = __DIR__ . '/404.html';
if (file_exists($error_page)) {
    header('Content-Type: text/html; charset=utf-8');
    readfile($error_page);
} else {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>404 Not Found</title></head><body><h1>404 - 页面未找到</h1></body></html>';
}
exit;