<?php
/**
 * 主入口 v11 — 镜像站 + 影视站群 双模式
 * 根据当前域名自动判断：Mirror模式 or VOD影视模式
 */

// PHP 7.4 polyfill
if (!function_exists('str_ends_with')) {
    function str_ends_with(string $haystack, string $needle): bool {
        if ($needle === '') return true;
        return substr($haystack, -strlen($needle)) === $needle;
    }
}

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/data/logs/php_error.log');

define('BASE_DIR', __DIR__);
define('DATA_DIR', BASE_DIR . '/data');

// 自动加载（镜像站核心）
spl_autoload_register(function ($class) {
    // VOD 核心类优先
    $vodFile = BASE_DIR . '/vod/core/' . $class . '.php';
    if (file_exists($vodFile)) { require_once $vodFile; return; }
    // 镜像站核心
    $coreFile = BASE_DIR . '/core/' . $class . '.php';
    if (file_exists($coreFile)) require_once $coreFile;
});

header_remove('X-Powered-By');

$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$host       = strtolower(preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST'] ?? ''));

// ── 流量统计（v11.13）：只登记请求，响应发完才写日志；任何错误都不影响网站 ──
try { VodStats::begin(); } catch (Throwable $e) { }

// ── 路由1：镜像站后台 ──
if (strpos($requestUri, '/mirror-admin') === 0) {
    require BASE_DIR . '/admin/index.php'; exit;
}

// ── 路由2：影视站后台 ──
if (strpos($requestUri, '/vod-admin') === 0) {
    require BASE_DIR . '/vod/admin.php'; exit;
}

// ── 安全屏蔽 ──
foreach (['/core/', '/data/', '/admin/', '/vod/'] as $b) {
    if (strpos($requestUri, $b) === 0) { http_response_code(403); exit('Forbidden'); }
}

// ── 诊断路由：/mirror-debug 显示当前域名匹配状态（仅debug模式可用） ──
if ($requestUri === '/mirror-debug' && file_exists(DATA_DIR . '/debug.flag')) {
    header('Content-Type: text/html; charset=UTF-8');
    echo '<pre style="font-size:14px;padding:20px">';
    echo "=== Mirror Debug ===\n";
    echo "Host: " . htmlspecialchars($host) . "\n";
    echo "REQUEST_URI: " . htmlspecialchars($_SERVER['REQUEST_URI'] ?? '') . "\n";
    echo "REDIRECT_URL: " . htmlspecialchars($_SERVER['REDIRECT_URL'] ?? '(未设置)') . "\n";
    echo "SCRIPT_NAME: " . htmlspecialchars($_SERVER['SCRIPT_NAME'] ?? '') . "\n\n";
    try {
        $vodDB = VodDB::get();
        $vodSite = $vodDB->getSiteByDomain($host);
        echo "VOD查找: " . ($vodSite ? "✓ 匹配 (id={$vodSite['id']}, domain={$vodSite['domain']}, enabled={$vodSite['enabled']})" : "✗ 未匹配") . "\n";
    } catch (Throwable $e) {
        echo "VOD查找异常: " . htmlspecialchars($e->getMessage()) . "\n";
        echo "  at " . htmlspecialchars($e->getFile()) . ":" . $e->getLine() . "\n";
    }
    $config = new Config();
    $mirrorSite = $config->getSiteByDomain($host);
    echo "镜像查找: " . ($mirrorSite ? "✓ 匹配 (domain={$mirrorSite['my_domain']}, target={$mirrorSite['target_domain']})" : "✗ 未匹配") . "\n";
    echo '</pre>';
    exit;
}

// ── 路由3：影视站前台（先查VOD库） ──
$vodError = null;
try {
    $vodDB   = VodDB::get();
    $vodSite = $vodDB->getSiteByDomain($host);
    if ($vodSite) {
        VodStats::site($host, 'vod');
        $renderer = new VodRenderer($vodSite, $vodDB);
        $renderer->dispatch();
        exit;
    }
} catch (Throwable $e) {
    // 记录错误，不再静默吞掉
    $vodError = $e;
    Logger::error('VOD dispatch fail: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine(), $host);
}

// ── 路由4：镜像站前台 ──
try {
    $config   = new Config();
    $siteConf = $config->getSiteByDomain($host);

    if (!$siteConf) {
        http_response_code(404);
        echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>未配置</title></head><body>';
        echo '<h2>域名未配置</h2><p>当前域名 <b>' . htmlspecialchars($host) . '</b> 未在镜像站或影视站中配置。</p>';
        if ($vodError && file_exists(DATA_DIR . '/debug.flag')) {
            echo '<div style="background:#fff2f0;border:1px solid #ffa39e;padding:12px;margin:12px 0;border-radius:6px">';
            echo '<b>VOD 异常（debug模式）：</b><pre>' . htmlspecialchars($vodError->getMessage() . "\n" . $vodError->getFile() . ':' . $vodError->getLine() . "\n" . $vodError->getTraceAsString()) . '</pre>';
            echo '</div>';
        }
        echo '<p><a href="/mirror-admin/">镜像站后台</a> | <a href="/vod-admin/">影视站后台</a></p>';
        if (file_exists(DATA_DIR . '/debug.flag')) {
            echo '<p style="font-size:12px;color:#999">提示：访问 <a href="/mirror-debug">/mirror-debug</a> 查看完整诊断</p>';
        }
        echo '</body></html>';
        exit;
    }

    if (empty($siteConf['enabled'])) {
        http_response_code(503);
        echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>站点已停用</title></head><body>';
        echo '<h2>站点已停用</h2><p>当前站点已被管理员停用。</p></body></html>';
        exit;
    }

    VodStats::site($host, 'mirror');
    $engine = new MirrorEngine($siteConf, $config);
    $engine->dispatch($requestUri);

} catch (Throwable $e) {
    Logger::error('FATAL: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    if (file_exists(DATA_DIR . '/debug.flag')) {
        echo '<pre>' . htmlspecialchars($e->getMessage() . "\n" . $e->getTraceAsString()) . '</pre>';
    } else {
        echo '<!DOCTYPE html><html><body><h2>服务暂时不可用</h2></body></html>';
    }
}
