<?php
require_once '../config.php';
require_once '../leaderboard_engine.php'; // ★ 載入排行榜快照引擎

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'player') {
    header("Location: ../login.php");
    exit;
}

$player_id = $_SESSION['user_id'];

try {
    // ★ 觸發每日快照引擎 (只有每天第一個看排行榜的人會引發系統運算，後續皆為快取)
    LeaderboardEngine::processDailyRanking($mysql_db);

    // ★ 直接從 MySQL 的輕量級快取表中撈取全服資料，極致效能！
    $leaderboard_data = [];
    $raw_data = $mysql_db->query("SELECT * FROM global_leaderboard_cache")->fetchAll();
    
    foreach ($raw_data as $row) {
        $leaderboard_data[] = [
            'name' => $row['player_name'],
            'is_me' => ($row['player_id'] == $player_id),
            'cash' => (int)$row['cash'],
            'deposit' => (int)$row['deposit'],
            'task_earned' => (int)$row['task_earned'],
            'task_count' => (int)$row['task_count'],
            'stock_value' => (int)$row['stock_value'],
            'stock_realized' => (int)$row['stock_realized'],
            'stock_dividend' => (int)$row['stock_dividend'],
            'estate_value' => (int)$row['estate_value'],
            'land_count' => (int)$row['land_count'],
            'upgrade_count' => (int)$row['upgrade_count'],
            'cards_count' => (int)$row['cards_count'],
            'total_assets' => (int)$row['total_assets']
        ];
    }

} catch (Exception $e) {
    die("排行榜生成失敗：" . $e->getMessage());
}

// 接收當前分頁類別
$tab = $_GET['tab'] ?? 'assets';
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>全球財富星光榜 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding-bottom: 40px; }
        .container { padding: 15px; max-width: 600px; margin: 0 auto; }
        
        .header-box { background: linear-gradient(135deg, #6c5ce7 0%, #a8a5ff 100%); border-radius: 15px; padding: 15px; text-align: center; color: white; box-shadow: 0 4px 10px rgba(108, 92, 231, 0.3); margin-bottom: 10px; }
        
        /* ★ 財商教育警語標籤 */
        .cache-notice { background: rgba(241, 196, 15, 0.2); border: 1px dashed #f1c40f; color: #d35400; padding: 8px 12px; border-radius: 8px; font-size: 0.8rem; text-align: center; margin-bottom: 20px; line-height: 1.4; font-weight: bold;}
        
        .sub-tabs { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; margin-bottom: 20px; }
        .sub-tab-btn { background: white; color: #7f8c8d; padding: 8px 16px; border-radius: 20px; font-size: 0.85rem; font-weight: bold; cursor: pointer; text-decoration: none; white-space: nowrap; border: 1px solid #e0e0e0; transition: 0.2s; flex-shrink: 0; }
        .sub-tab-btn.active { background: #6c5ce7; color: white; border-color: #6c5ce7; box-shadow: 0 2px 6px rgba(108, 92, 231, 0.3); }
        
        .rank-list { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .rank-item { display: flex; align-items: center; padding: 12px 15px; border-bottom: 1px solid #f5f5f6; transition: 0.2s; }
        .rank-item.me { background-color: #f4ecf7; border-left: 5px solid #6c5ce7; }
        .rank-item:last-child { border-bottom: none; }
        
        .rank-num { width: 35px; font-size: 1.1rem; font-weight: bold; text-align: center; color: #7f8c8d; }
        .rank-medal { width: 35px; text-align: center; font-size: 1.3rem; }
        .rank-name { flex: 1; font-weight: bold; color: #2c3e50; font-size: 1rem; margin-left: 10px; }
        .rank-me-tag { background: #6c5ce7; color: white; font-size: 0.7rem; padding: 1px 5px; border-radius: 4px; margin-left: 5px; vertical-align: middle;}
        
        .rank-score { text-align: right; font-weight: bold; font-size: 1.1rem; color: #e67e22; }
        .rank-sub-score { font-size: 0.75rem; color: #7f8c8d; font-weight: normal; margin-top: 2px; }
    </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container">
    <div class="header-box">
        <h2 style="margin:0; font-size:1.4rem;">🏆 全球財富星光大盤榜</h2>
        <p style="margin:5px 0 0 0; font-size:0.8rem; opacity:0.8;">看誰才是時間世界裡最具商業思維的終極理財大師！</p>
    </div>

    <div class="cache-notice">
        🕒 <b>資料更新時間：今日凌晨 00:00</b><br>
        (排行榜為每日盤後結算，今日辛苦賺取的財富將於明日榜單展現！)
    </div>

    <div class="sub-tabs">
        <a href="?tab=assets" class="sub-tab-btn <?php echo $tab=='assets'?'active':''; ?>">🌍 總資產霸榜</a>
        <a href="?tab=tasks" class="sub-tab-btn <?php echo $tab=='tasks'?'active':''; ?>">🏃 任務達人榜</a>
        <a href="?tab=stock" class="sub-tab-btn <?php echo $tab=='stock'?'active':''; ?>">📈 股市操盤王</a>
        <a href="?tab=estate" class="sub-tab-btn <?php echo $tab=='estate'?'active':''; ?>">🏘️ 不動產大亨</a>
        <a href="?tab=cash" class="sub-tab-btn <?php echo $tab=='cash'?'active':''; ?>">👛 現金與定存</a>
        <a href="?tab=cards" class="sub-tab-btn <?php echo $tab=='cards'?'active':''; ?>">🎒 卡牌搜集狂</a>
    </div>

    <div class="rank-list">
        <?php 
        if ($tab === 'cash') {
            usort($leaderboard_data, function($a, $b) { return ($b['cash'] + $b['deposit']) <=> ($a['cash'] + $a['deposit']); });
        } elseif ($tab === 'tasks') { 
            usort($leaderboard_data, function($a, $b) { return $b['task_earned'] <=> $a['task_earned']; });
        } elseif ($tab === 'stock') {
            usort($leaderboard_data, function($a, $b) { return $b['stock_value'] <=> $a['stock_value']; });
        } elseif ($tab === 'estate') {
            usort($leaderboard_data, function($a, $b) { return $b['estate_value'] <=> $a['estate_value']; });
        } elseif ($tab === 'cards') {
            usort($leaderboard_data, function($a, $b) { return $b['cards_count'] <=> $a['cards_count']; });
        } else {
            usort($leaderboard_data, function($a, $b) { return $b['total_assets'] <=> $a['total_assets']; });
        }

        foreach ($leaderboard_data as $index => $item): 
            $rank = $index + 1;
            $is_medal = ($rank <= 3);
            $medal_emoji = ($rank == 1) ? '🥇' : (($rank == 2) ? '🥈' : '🥉');
        ?>
            <div class="rank-item <?php echo $item['is_me'] ? 'me' : ''; ?>">
                <?php if ($is_medal): ?>
                    <div class="rank-medal"><?php echo $medal_emoji; ?></div>
                <?php else: ?>
                    <div class="rank-num"><?php echo $rank; ?></div>
                <?php endif; ?>

                <div class="rank-name">
                    <?php echo htmlspecialchars($item['name']); ?>
                    <?php if ($item['is_me']): ?><span class="rank-me-tag">我</span><?php endif; ?>
                </div>

                <div class="rank-score">
                    <?php if ($tab === 'cash'): ?>
                        <?php echo number_format($item['cash'] + $item['deposit']); ?> <span style="font-size:0.8rem; font-weight:normal;">分</span>
                        <div class="rank-sub-score">現金: <?php echo number_format($item['cash']); ?> | 定存: <?php echo number_format($item['deposit']); ?></div>
                    
                    <?php elseif ($tab === 'tasks'): ?>
                        <?php echo number_format($item['task_earned']); ?> <span style="font-size:0.8rem; font-weight:normal;">分</span>
                        <div class="rank-sub-score">累計完成: <?php echo number_format($item['task_count']); ?> 次</div>

                    <?php elseif ($tab === 'stock'): ?>
                        <?php echo number_format($item['stock_value']); ?> <span style="font-size:0.8rem; font-weight:normal;">分</span>
                        <div class="rank-sub-score" style="color:#2ecc71;">已實現: +<?php echo number_format($item['stock_realized']); ?> | 除息: +<?php echo number_format($item['stock_dividend']); ?></div>
                    
                    <?php elseif ($tab === 'estate'): ?>
                        <?php echo number_format($item['estate_value']); ?> <span style="font-size:0.8rem; font-weight:normal;">分</span>
                        <div class="rank-sub-score" style="color:#9b59b6;">土地: <?php echo $item['land_count']; ?> 塊 | 升級: <?php echo $item['upgrade_count']; ?> 次</div>
                    
                    <?php elseif ($tab === 'cards'): ?>
                        <?php echo number_format($item['cards_count']); ?> <span style="font-size:0.8rem; font-weight:normal;">張</span>
                        <div class="rank-sub-score">背包卡牌總儲備量</div>
                    
                    <?php else: ?>
                        <?php echo number_format($item['total_assets']); ?> <span style="font-size:0.8rem; font-weight:normal;">分</span>
                        <div class="rank-sub-score">現金定存 + 股市持股 + 房產現值</div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

</body>
</html>