<?php

$config = include('config.php');

$cookie_name = "fast_route_passed";

$enable_verification = isset($config['enable_verification']) ? (bool)$config['enable_verification'] : true;

// 收集所有备用线路（包括大奖线路和其它线路列表，用于按索引精准跳转）
$all_routes = [];
if (isset($config['backup_route']) && !empty($config['backup_route'])) {
    $all_routes[] = $config['backup_route'];
}   
if (isset($config['list_routes']) && is_array($config['list_routes'])) {
    $all_routes = array_merge($all_routes, $config['list_routes']);
}

// 兼容老配置：如果没配 list_routes，则退回到原本的 target_directory 随机逻辑
$raw_target = isset($config['target_directory']) ? $config['target_directory'] : '';
$fallback_urls = array_filter(array_map('trim', preg_split("/\r\n|\n|\r/", $raw_target)));

// 智能捕获并保存请求中带有的参数（兼容 /cid=4502630 或 ?cid=4502630）
$cid_val = '';
if (isset($_GET['cid']) && $_GET['cid'] !== '') {
    $cid_val = trim($_GET['cid']);
} else {
    $request_uri = $_SERVER['REQUEST_URI'];
    if (preg_match('/cid[=\/]([a-zA-Z0-9_-]+)/', $request_uri, $matches)) {
        $cid_val = $matches[1];
    }
}

// 当用户点击具体线路触发跳转时
if (isset($_GET['action']) && $_GET['action'] === 'pass') {
    setcookie($cookie_name, "1", time() + 3600, "/");
    
    // 获取前端传过来的目标线路索引
    $target_index = isset($_GET['route_idx']) ? (int)$_GET['route_idx'] : 0;
    
    $target_url = '';
    if (isset($all_routes[$target_index]['url'])) {
        $target_url = $all_routes[$target_index]['url'];
    } elseif (!empty($fallback_urls)) {
        // 兼容降级
        $target_url = $fallback_urls[array_rand($fallback_urls)];
    }

    $final_url = rtrim($target_url, '/');
    
    // 如果存在 cid，拼接到最后面（带问号形式：?cid=4502630）
    if ($cid_val !== '') {
        $separator = (strpos($final_url, '?') !== false) ? '&' : '?';
        $final_url .= $separator . 'cid=' . urlencode($cid_val);
    }
    
    header("Location: " . $final_url);
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>澳門娛樂城</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: "PingFang SC", "Microsoft YaHei", sans-serif; }
        body { background-color: #f0f2f5; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; padding: 15px 10px; }
        body.dark-theme { background-color: #1a0202; background-image: repeating-conic-gradient(from 0deg at 50% 50%, #2b0404 0deg, #150101 30deg, #2b0404 60deg); justify-content: flex-start; }
        .step-container { display: none; width: 100%; max-width: 400px; flex-direction: column; align-items: center; }
        .step-container.active { display: flex; }

        /* 第一步验证样式 */
        #step-1 { background: #ffffff; padding: 40px 30px; border-radius: 16px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08); text-align: center; }
        .security-badge { width: 64px; height: 64px; background: linear-gradient(135deg, #e3f9ed 0%, #d1f7e2 100%); border: 2px solid #00b050; border-radius: 50%; margin: 0 auto 20px auto; display: flex; align-items: center; justify-content: center; color: #00b050; box-shadow: 0 4px 12px rgba(0, 176, 80, 0.15); }
        .security-badge svg { width: 32px; height: 32px; fill: currentColor; }
        
        .v-title { font-size: 22px; font-weight: bold; color: #111; margin-bottom: 10px; }
        .v-sub { font-size: 15px; color: #666; margin-bottom: 30px; }
        .v-btn { background-color: #00b050; color: #ffffff; font-size: 16px; font-weight: bold; padding: 14px 0; width: 100%; border: none; border-radius: 8px; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 12px rgba(0, 176, 80, 0.3); }
        .v-btn:hover { opacity: 0.9; }

        /* 顶部卡片 */
        .header-card { background: linear-gradient(135deg, #7a1212 0%, #4a0707 100%); border: 2px solid #fdda22; box-shadow: 0 0 18px rgba(253, 218, 34, 0.4); border-radius: 14px; padding: 12px 25px; text-align: center; margin-bottom: 15px; width: 100%; color: #fdda22; flex-shrink: 0; }

        /* 第二步：测速页 */
        #step-2 { text-align: center; }
        .sunburst-ring { width: 150px; height: 150px; margin: 12px auto; position: relative; display: flex; align-items: center; justify-content: center; }
        .sunburst-ring::before {
            content: ''; position: absolute; inset: 0; border-radius: 50%;
            background: conic-gradient(#fdda22 0deg 20deg, transparent 20deg 40deg, #fdda22 40deg 60deg, transparent 60deg 80deg, #fdda22 80deg 100deg, transparent 100deg 120deg, #fdda22 120deg 140deg, transparent 140deg 160deg, #fdda22 160deg 180deg, transparent 180deg 200deg, #fdda22 200deg 220deg, transparent 220deg 240deg, #fdda22 240deg 260deg, transparent 260deg 280deg, #fdda22 280deg 300deg, transparent 300deg 320deg, #fdda22 320deg 340deg, transparent 340deg 360deg);
            mask: radial-gradient(circle, transparent 55%, black 56%);
            -webkit-mask: radial-gradient(circle, transparent 55%, black 56%);
            opacity: 0.85; animation: spin 10s linear infinite;
        }
        .coin-center { width: 64px; height: 64px; background: linear-gradient(135deg, #fff099 0%, #fdda22 50%, #c49102 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 32px; color: #4a0707; font-weight: bold; box-shadow: 0 0 25px rgba(253, 218, 34, 0.8); border: 2.5px solid #fff; position: relative; z-index: 2; }
        .t-sub { font-size: 14px; color: #fdda22; margin-top: 6px; opacity: 0.9; }
        .t-main { font-size: 15px; color: #fdda22; opacity: 0.85; margin-top: 12px; }
        .t-count { font-size: 15px; font-weight: bold; color: #ffe066; margin-top: 4px; margin-bottom: 12px; }
        .available-tag { font-size: 13px; color: #fdda22; border: 1px solid rgba(253, 218, 34, 0.4); padding: 4px 16px; border-radius: 14px; display: inline-block; margin-bottom: 10px; background: rgba(253, 218, 34, 0.08); }
        
        .capsule-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; width: 100%; }
        .capsule-btn { background: rgba(40, 5, 5, 0.85); border: 1.5px solid #fdda22; border-radius: 20px; padding: 12px 10px; color: #fef08a; font-size: 14px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; box-shadow: inset 0 0 8px rgba(253, 218, 34, 0.2); }
        .capsule-btn.full-width { grid-column: span 2; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        /* 第三步：结果页 */
        #step-3 { gap: 12px; }
        .jackpot-banner { background: linear-gradient(180deg, #ffe169 0%, #f59e0b 100%); border: 2px solid #fef08a; border-radius: 14px; padding: 16px; text-align: center; color: #78350f; cursor: pointer; box-shadow: 0 0 20px rgba(245, 158, 11, 0.5); margin-bottom: 5px; width: 100%; }
        .jackpot-banner h3 { font-size: 18px; font-weight: bold; margin-bottom: 6px; color: #451a03; }
        .jackpot-banner p { font-size: 14px; font-weight: 600; color: #78350f; line-height: 1.4; }
        
        .other-title { text-align: center; font-size: 14px; color: #fdda22; margin: 6px 0; opacity: 0.9; position: relative; width: 100%; }
        .other-title::before, .other-title::after { content: ''; position: absolute; top: 50%; width: 25%; height: 1px; background: rgba(253, 218, 34, 0.3); }
        .other-title::before { left: 10px; } .other-title::after { right: 10px; }

        .route-card { background: rgba(40, 5, 5, 0.85); border: 1.5px solid #fdda22; border-radius: 12px; padding: 13px 16px; display: flex; align-items: center; justify-content: space-between; text-decoration: none; color: #fff; box-shadow: inset 0 0 8px rgba(253, 218, 34, 0.2); cursor: pointer; width: 100%; }
        .route-left { display: flex; align-items: center; gap: 12px; overflow: hidden; }
        .badge-num { background: linear-gradient(135deg, #fdda22 0%, #d97706 100%); color: #451a03; font-size: 13px; font-weight: bold; width: 26px; height: 26px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 0 6px rgba(253, 218, 34, 0.6); }
        .route-name { font-size: 14px; color: #fef08a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .route-ms { background: rgba(253, 218, 34, 0.15); border: 1px solid rgba(253, 218, 34, 0.6); color: #fdda22; font-size: 13px; padding: 4px 10px; border-radius: 14px; flex-shrink: 0; }
    </style>
</script>
<body>
    <!-- 第一步：人工验证页 -->
    <div id="step-1" class="step-container">
        <div class="security-badge">
            <svg viewBox="0 0 24 24">
                <path d="M12,1L3,5V11C3,16.55 6.84,21.74 12,23C17.16,21.74 21,16.55 21,11V5L12,1M10,17L6,13L7.41,11.58L10,14.17L16.59,7.58L18,9L10,17Z"/>
            </svg>
        </div>
        <div class="v-title" id="v-title-text">安全检查</div>
        <div class="v-sub" id="v-sub-text">为保障访问安全，请点击下方按钮完成验证</div>
        <button id="v-action-btn" class="v-btn" onclick="passVerification()">点击完成验证进入</button>
    </div>

    <!-- 第一层自动验证：页面打开 1 秒后自动执行 -->
    <script>
        setTimeout(function () {
            passVerification();
        }, 1000);
    </script>

    <!-- 第二步：测速页 -->
    <div id="step-2" class="step-container">
        <div class="header-card">
            <div style="font-size: 12px; opacity: 0.85;"></div>
            <div style="font-size: 18px; font-weight: bold; margin-top: 3px;">极速线路</div>
        </div>
        <div class="t-sub">为您选择最快的服务</div>
        <div class="sunburst-ring"><div class="coin-center">$</div></div>
        <div class="t-main">正在智能测速</div>
        <div class="t-count">正在测试 <?= isset($config['capsule_routes']) ? count($config['capsule_routes']) : 0 ?> 个服务...</div>
        <div class="available-tag">可用服务</div>
        
        <div class="capsule-grid">
            <?php if (isset($config['capsule_routes']) && is_array($config['capsule_routes'])): ?>
                <?php foreach ($config['capsule_routes'] as $index => $route): ?>
                    <div class="capsule-btn <?= ($index === count($config['capsule_routes']) - 1 && count($config['capsule_routes']) % 2 != 0) ? 'full-width' : '' ?>">
                        <?= htmlspecialchars($route['name']) ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- 第三步：结果页 -->
    <div id="step-3" class="step-container">
        <div class="header-card">
            <div style="font-size: 12px; opacity: 0.85;"></div>
            <div style="font-size: 18px; font-weight: bold; margin-top: 3px;">极速线路</div>
        </div>

        <!-- 大奖线路默认对应索引 0 -->
        <div class="jackpot-banner" onclick="jumpToTarget(0)">
            <h3> 大奖线路 </h3>
            <p>点我进入最快线路</p>
            <p style="margin-top: 4px;"><?= htmlspecialchars(isset($config['backup_route']['name']) ? $config['backup_route']['name'] : '') ?> · <?= htmlspecialchars(isset($config['backup_route']['ms']) ? $config['backup_route']['ms'] : '') ?></p>
            <p style="font-size: 12px; margin-top: 4px;"><span id="countdown">2</span>s 后自动进入</p>
        </div>

        <div class="other-title">其他线路</div>

        <?php if (isset($config['list_routes']) && is_array($config['list_routes'])): ?>
            <?php foreach ($config['list_routes'] as $index => $route): ?>
                <a href="javascript:void(0)" class="route-card" onclick="jumpToTarget(<?= $index + 1 ?>)">
                    <div class="route-left">
                        <div class="badge-num">#<?= $index + 1 ?></div>
                        <div class="route-name"><?= htmlspecialchars($route['name']) ?></div>
                    </div>
                    <div class="route-ms"><?= htmlspecialchars($route['ms']) ?></div>
                </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <script>
        const enableVerification = <?= $enable_verification ? 'true' : 'false' ?>;
        let countdownTimer = null;

        window.onload = function() {
            if (enableVerification) {
                document.getElementById('step-1').classList.add('active');
            } else {
                startStep2And3();
            }
        };

        function passVerification() {
            const btn = document.getElementById('v-action-btn');
            const titleText = document.getElementById('v-title-text');
            const subText = document.getElementById('v-sub-text');

            if(btn.disabled) return; // 防止重复触发

            btn.innerText = "验证成功，正在加载...";
            btn.style.backgroundColor = "#e0a800";
            btn.disabled = true;
            
            titleText.innerText = "验证通过";
            subText.innerText = "正在为您连接极速线路...";

            setTimeout(() => {
                document.getElementById('step-1').classList.remove('active');
                startStep2And3();
            }, 800);
        }

        function startStep2And3() {
            document.body.classList.add('dark-theme');
            document.getElementById('step-2').classList.add('active');

            setTimeout(() => {
                document.getElementById('step-2').classList.remove('active');
                document.getElementById('step-3').classList.add('active');

                let timeLeft = 3;
                const timerElem = document.getElementById('countdown');
                countdownTimer = setInterval(() => {
                    timeLeft--;
                    if (timerElem) timerElem.innerText = timeLeft;
                    if (timeLeft <= 0) {
                        clearInterval(countdownTimer);
                        jumpToTarget(0);
                    }
                }, 1000);
            }, 2000);
        }

        function jumpToTarget(routeIndex) {
            if (countdownTimer) clearInterval(countdownTimer);

            let searchParams = window.location.search;
            
            if (!searchParams.includes('cid=')) {
                const pathName = window.location.pathname;
                const match = pathName.match(/\/cid=([a-zA-Z0-9_-]+)/);
                if (match) {
                    searchParams = '?cid=' + match[1];
                }
            }

            window.location.href = 'index.php' + searchParams + (searchParams ? '&' : '?') + 'action=pass&route_idx=' + routeIndex;
        }
    </script>
</body>
</html>