<?php
/**
 * 時間大富翁 - 排行榜快照引擎 (Leaderboard Snapshot Engine)
 * 負責每日凌晨自動彙整全伺服器玩家的 SQLite 數據，存入 MySQL 快取表，保護系統效能。
 */
class LeaderboardEngine {
    
    public static function processDailyRanking($mysql_db) {
        $today_date = date('Y-m-d');

        // 1. 確保 MySQL 有快取表與排程紀錄表
        $mysql_db->exec("CREATE TABLE IF NOT EXISTS global_leaderboard_cache (
            player_id INT PRIMARY KEY,
            player_name VARCHAR(50),
            cash INT DEFAULT 0,
            deposit INT DEFAULT 0,
            task_earned INT DEFAULT 0,
            task_count INT DEFAULT 0,
            stock_value INT DEFAULT 0,
            stock_realized INT DEFAULT 0,
            stock_dividend INT DEFAULT 0,
            estate_value INT DEFAULT 0,
            land_count INT DEFAULT 0,
            upgrade_count INT DEFAULT 0,
            cards_count INT DEFAULT 0,
            total_assets INT DEFAULT 0
        )");

        $mysql_db->exec("CREATE TABLE IF NOT EXISTS system_cron_logs (
            cron_name VARCHAR(50) PRIMARY KEY,
            last_run_date DATE
        )");

        // 2. 檢查今天是否已經統計過 (Lazy Loading 核心)
        $stmt_check = $mysql_db->prepare("SELECT last_run_date FROM system_cron_logs WHERE cron_name = 'daily_leaderboard'");
        $stmt_check->execute();
        $log = $stmt_check->fetch();

        if ($log && $log['last_run_date'] === $today_date) {
            return false; // 今天已經做過快照，直接收工，不耗資源！
        }

        // 3. 開始執行全服大結算
        $global_prices = [];
        foreach ($mysql_db->query("SELECT id, current_price FROM global_stocks")->fetchAll() as $r) {
            $global_prices[$r['id']] = (float)$r['current_price'];
        }
        $growth_rate = 0.002;
        $global_estate = $mysql_db->query("SELECT daily_value_growth_rate FROM estate_global_settings WHERE id = 1")->fetch();
        if ($global_estate) $growth_rate = (float)$global_estate['daily_value_growth_rate'];

        $players = $mysql_db->query("SELECT id, display_name, sqlite_file FROM users WHERE role = 'player'")->fetchAll();

        // 開啟事務，清空舊排行榜，寫入新排行榜
        $mysql_db->beginTransaction();
        $mysql_db->exec("DELETE FROM global_leaderboard_cache");

        $stmt_insert = $mysql_db->prepare("
            INSERT INTO global_leaderboard_cache 
            (player_id, player_name, cash, deposit, task_earned, task_count, stock_value, stock_realized, stock_dividend, estate_value, land_count, upgrade_count, cards_count, total_assets) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        foreach ($players as $p) {
            $pid = $p['id'];
            $pname = $p['display_name'];
            $cash = 0; $deposit = 0; $task_earned = 0; $task_count = 0;
            $stock_value = 0; $stock_realized = 0; $stock_dividend = 0;
            $estate_value = 0; $land_count = 0; $upgrade_count = 0; $cards_count = 0;

            if (!empty($p['sqlite_file']) && file_exists(__DIR__ . '/' . $p['sqlite_file'])) {
                try {
                    // 安全建立 SQLite 連線
                    $p_db = new PDO('sqlite:' . __DIR__ . '/' . $p['sqlite_file']);
                    $p_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    // A. 現金
                    $c_row = $p_db->query("SELECT balance_minutes FROM wallet LIMIT 1")->fetch();
                    if ($c_row) $cash = (int)$c_row['balance_minutes'];

                    // B. 銀行
                    if ($p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='time_bank'")->fetch()) {
                        $deposit = (int)$p_db->query("SELECT balance_minutes FROM time_bank LIMIT 1")->fetchColumn();
                    }

                    // C. 任務收入
                    if ($p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='task_history'")->fetch()) {
                        $th = $p_db->query("SELECT SUM(earned_minutes) as sm, COUNT(id) as ct FROM task_history WHERE stars IS NOT NULL")->fetch();
                        if ($th) { $task_earned = (int)$th['sm']; $task_count = (int)$th['ct']; }
                    }

                    // D. 股市現值
                    if ($p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='stock_portfolio'")->fetch()) {
                        foreach ($p_db->query("SELECT * FROM stock_portfolio WHERE total_shares > 0")->fetchAll() as $row) {
                            if (isset($global_prices[$row['stock_id']])) {
                                $stock_value += ((int)$row['total_shares'] * $global_prices[$row['stock_id']]);
                            }
                        }
                    }

                    // E. 股市損益與除息
                    if ($p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='transaction_logs'")->fetch()) {
                        $sr = $p_db->query("SELECT SUM(amount) FROM transaction_logs WHERE action_type IN ('stock_profit', 'stock_sell_profit')")->fetchColumn();
                        $stock_realized = $sr ? (int)$sr : 0;
                        $sd = $p_db->query("SELECT SUM(amount) FROM transaction_logs WHERE action_type = 'stock_dividend' OR (description LIKE '%除息%' AND amount > 0)")->fetchColumn();
                        $stock_dividend = $sd ? (int)$sd : 0;
                        $uc = $p_db->query("SELECT COUNT(*) FROM transaction_logs WHERE action_type = 'upgrade_building'")->fetchColumn();
                        $upgrade_count = (int)$uc;
                    }

                    // F. 房產現值
                    if ($p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='estate_properties'")->fetch()) {
                        $props = $p_db->query("SELECT * FROM estate_properties")->fetchAll();
                        $land_count = count($props);
                        foreach ($props as $prop) {
                            $d1 = new DateTime($prop['purchase_date']); $d2 = new DateTime($today_date);
                            $days = (int)$d1->diff($d2)->format('%a');
                            $principal = (int)$prop['land_purchase_price'] + (int)$prop['build_cost'];
                            $estate_value += (int)round($principal * (1 + ($growth_rate * $days)));
                        }
                    }

                    // G. 卡牌
                    if ($p_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='inventory'")->fetch()) {
                        $cards_count = (int)$p_db->query("SELECT SUM(quantity) FROM inventory WHERE quantity > 0")->fetchColumn();
                    }
                } catch (Exception $e) { /* 忽略單一損壞的資料庫，保護排行榜不崩潰 */ }
            }

            $total_assets = $cash + $deposit + $stock_value + $estate_value;

            $stmt_insert->execute([
                $pid, $pname, $cash, $deposit, $task_earned, $task_count, 
                $stock_value, $stock_realized, $stock_dividend, 
                $estate_value, $land_count, $upgrade_count, $cards_count, $total_assets
            ]);
        }

        // 4. 寫入今天的完成紀錄，明天之前都不會再重算
        $mysql_db->exec("INSERT INTO system_cron_logs (cron_name, last_run_date) VALUES ('daily_leaderboard', '$today_date') ON DUPLICATE KEY UPDATE last_run_date = '$today_date'");

        $mysql_db->commit();
        return true;
    }
}
?>