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

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

$player_id = $_SESSION['user_id'];
$display_name = $_SESSION['display_name'];
$event_alert_msg = "";

try {
    $sqlite_db = getPlayerSQLiteConnection($_SESSION['sqlite_file']);
    $sqlite_db->exec("CREATE TABLE IF NOT EXISTS active_buffs (id INTEGER PRIMARY KEY AUTOINCREMENT, buff_type TEXT, effect_value REAL DEFAULT 1.0, active_count INTEGER DEFAULT 0, target_task_id INTEGER DEFAULT 0)");
    $sqlite_db->exec("CREATE TABLE IF NOT EXISTS claimed_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event_id INTEGER, claimed_date TEXT)");

    $today_date = date('Y-m-d');     
    $today_md = date('m-d');         
    $today_weekday = date('w');      

    $stmt_ev = $mysql_db->query("SELECT * FROM global_rewards_events");
    $global_events = $stmt_ev->fetchAll();

    if (count($global_events) > 0) {
        foreach ($global_events as $ev) {
            $is_triggered = false;
            if ($ev['trigger_type'] === 'weekly' && (string)$ev['trigger_value'] === (string)$today_weekday) {
                $is_triggered = true;
            } elseif ($ev['trigger_type'] === 'annual' && $ev['trigger_value'] === $today_md) {
                $is_triggered = true;
            } elseif ($ev['trigger_type'] === 'specific_date' && $ev['trigger_value'] === $today_date) {
                $is_triggered = true;
            }

            if ($is_triggered) {
                $stmt_chk_claim = $sqlite_db->prepare("SELECT id FROM claimed_events WHERE event_id = :eid AND claimed_date = :d");
                $stmt_chk_claim->execute([':eid' => $ev['id'], ':d' => $today_date]);
                
                if (!$stmt_chk_claim->fetch()) {
                    $reward = (int)$ev['reward_minutes'];
                    $sqlite_db->beginTransaction();
                    $sqlite_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $reward");
                    $log_desc = "🎁 全球大富翁福利：【{$ev['event_name']}】發放時間！";
                    $stmt_ins_log = $sqlite_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('system_gift', :amt, :desc)");
                    $stmt_ins_log->execute([':amt' => $reward, ':desc' => $log_desc]);
                    $stmt_mark = $sqlite_db->prepare("INSERT INTO claimed_events (event_id, claimed_date) VALUES (:eid, :d)");
                    $stmt_mark->execute([':eid' => $ev['id'], ':d' => $today_date]);
                    $sqlite_db->commit();
                    $event_alert_msg = "🎲 【{$ev['event_name']}】獲得獎勵金 +{$reward} 分鐘！已經放進你的錢包囉！✨";
                }
            }
        }
    }

    $stmt_wallet = $sqlite_db->query("SELECT balance_minutes FROM wallet LIMIT 1");
    $wallet_data = $stmt_wallet->fetch();
    $current_balance = $wallet_data ? (int)$wallet_data['balance_minutes'] : 0;

    $time_convert_str = "";
    if ($current_balance >= 60) {
        $d = floor($current_balance / 1440); $h = floor(($current_balance % 1440) / 60); $m = $current_balance % 60;
        $parts = []; if ($d > 0) $parts[] = "{$d}天"; if ($h > 0) $parts[] = "{$h}小時"; if ($m > 0) $parts[] = "{$m}分";
        $time_convert_str = "≈ " . implode(' ', $parts);
    } elseif ($current_balance < 0) {
        $time_convert_str = "⚠️ 嚴重警告：信用破產狀態！請盡速補足欠款！";
    }

    $stmt_limit = $mysql_db->query("SELECT daily_task_limit FROM global_settings WHERE id = 1");
    $global_limit = (int)$stmt_limit->fetch()['daily_task_limit'];

    $stmt_usage = $sqlite_db->prepare("SELECT SUM(estimated_time) as used_time FROM task_history WHERE substr(created_at, 1, 10) = :today");
    $stmt_usage->execute([':today' => $today_date]);
    $today_used = (int)$stmt_usage->fetch()['used_time'];

    $remaining_limit = max(0, $global_limit - $today_used);
    $usage_percent = min(100, ($today_used / $global_limit) * 100);

    $stmt_pending = $sqlite_db->query("SELECT * FROM task_history WHERE stars IS NULL");
    $pending_map = [];
    foreach ($stmt_pending->fetchAll() as $row) $pending_map[$row['task_id']] = $row;

    $stmt_completed = $sqlite_db->prepare("SELECT * FROM task_history WHERE stars IS NOT NULL AND substr(created_at, 1, 10) = :today");
    $stmt_completed->execute([':today' => $today_date]);
    $completed_today_map = [];
    foreach ($stmt_completed->fetchAll() as $row) $completed_today_map[$row['task_id']] = $row;

    $stmt_buffs = $sqlite_db->query("SELECT * FROM active_buffs WHERE active_count > 0");
    $task_buffs = [];
    foreach ($stmt_buffs->fetchAll() as $b) {
        $tid = $b['target_task_id'];
        if (!isset($task_buffs[$tid])) $task_buffs[$tid] = [];
        $task_buffs[$tid][] = $b;
    }

    $stmt_estate_alerts = $sqlite_db->prepare("SELECT description FROM transaction_logs WHERE action_type = 'estate_alert' AND created_at >= datetime('now', '-1 day') ORDER BY created_at DESC");
    $stmt_estate_alerts->execute();
    $estate_alerts = $stmt_estate_alerts->fetchAll(PDO::FETCH_COLUMN);

    // ==========================================
    // ★ 計算個人的股市、房產、任務與銀行總資產數據
    // ==========================================
    $stock_value = 0; $stock_earned = 0;
    $estate_value = 0; $estate_earned = 0;
    $total_task_earned = 0; $total_task_count = 0;
    $bank_balance = 0; // ★ 新增銀行定存追蹤

    $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'];

    // 1. 撈取「累計任務」主動收入
    if ($sqlite_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='task_history'")->fetch()) {
        $stmt_task_total = $sqlite_db->query("SELECT COUNT(id) as c, SUM(earned_minutes) as s FROM task_history WHERE stars IS NOT NULL");
        $task_total_data = $stmt_task_total->fetch();
        if ($task_total_data) {
            $total_task_count = (int)$task_total_data['c'];
            $total_task_earned = (int)$task_total_data['s'];
        }
    }

    // 2. 撈取「銀行定存」可用時間
    if ($sqlite_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='time_bank'")->fetch()) {
        $bank_balance = (int)$sqlite_db->query("SELECT balance_minutes FROM time_bank LIMIT 1")->fetchColumn();
    }

    // 3. 計算股市現值與收益
    if ($sqlite_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='stock_portfolio'")->fetch()) {
        foreach ($sqlite_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']]);
            }
        }
    }
    $stock_earn_stmt = $sqlite_db->query("SELECT SUM(amount) FROM transaction_logs WHERE action_type IN ('stock_profit', 'stock_dividend') OR (description LIKE '%股%' AND amount > 0 AND action_type='task_reward')");
    $stock_earned = $stock_earn_stmt ? (int)$stock_earn_stmt->fetchColumn() : 0;

    // 4. 計算房產現值與收益
    if ($sqlite_db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='estate_properties'")->fetch()) {
        foreach ($sqlite_db->query("SELECT * FROM estate_properties")->fetchAll() 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)));
            $estate_earned += (int)$prop['total_profit'];
        }
    }

    // ★ 總資產公式：錢包現金 + 銀行存款 + 股市現值 + 房產現值
    $total_assets = $current_balance + $bank_balance + $stock_value + $estate_value;

    $sql_assign = "
        SELECT a.id AS assign_id, a.schedule_type, a.schedule_value, t.id AS template_id, t.task_name, t.estimated_time, t.weight, t.description 
        FROM task_assignments a JOIN tasks_template t ON a.task_id = t.id WHERE a.player_id = :player_id
    ";
    $stmt_assign = $mysql_db->prepare($sql_assign);
    $stmt_assign->execute([':player_id' => $player_id]);
    $all_assignments = $stmt_assign->fetchAll();

    $tomorrow_date = date('Y-m-d', strtotime('+1 day')); $tomorrow_dow = date('w', strtotime('+1 day'));
    $today_tasks = []; $tomorrow_tasks = [];

    foreach ($all_assignments as $task) {
        $type = $task['schedule_type']; $val = $task['schedule_value']; $is_today = false;
        if ($type === 'daily' || $type === 'daily_deadline') $is_today = true; 
        elseif ($type === 'weekly' && in_array($today_weekday, explode(',', $val))) $is_today = true;
        elseif ($type === 'specific_date' && $val === $today_date) $is_today = true;
        if ($is_today) $today_tasks[] = $task;

        $is_tomorrow = false;
        if ($type === 'daily' || $type === 'daily_deadline') $is_tomorrow = true; 
        elseif ($type === 'weekly' && in_array($tomorrow_dow, explode(',', $val))) $is_tomorrow = true;
        elseif ($type === 'specific_date' && $val === $tomorrow_date) $is_tomorrow = true;
        if ($is_tomorrow) $tomorrow_tasks[] = $task;
    }

    $stmt_global_msg = $mysql_db->query("SELECT * FROM global_messages ORDER BY created_at DESC LIMIT 3");
    $global_messages = $stmt_global_msg->fetchAll();

} catch (PDOException $e) {
    die("資料讀取失敗：" . $e->getMessage());
}
?>

<!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: 30px; }
        .container { padding: 15px; max-width: 500px; margin: 0 auto; }
        
        .wallet-card { background: linear-gradient(135deg, #f6d365 0%, #fda085 100%); border-radius: 15px; padding: 20px; text-align: center; color: white; box-shadow: 0 4px 10px rgba(253, 160, 133, 0.3); margin-bottom: 20px; transition: 0.3s;}
        .wallet-card.debt-mode { background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); box-shadow: 0 4px 15px rgba(231, 76, 60, 0.5); animation: pulse-debt 1.5s infinite; }
        @keyframes pulse-debt { 0% { transform: scale(1); } 50% { transform: scale(1.02); } 100% { transform: scale(1); } }
        
        .wallet-balance { font-size: 3.5rem; font-weight: bold; margin: 0; line-height: 1; }
        .wallet-unit { font-size: 1rem; margin-top: 5px; opacity: 0.9; }
        .wallet-convert { font-size: 0.85rem; background: rgba(0,0,0,0.15); display: inline-block; padding: 4px 12px; border-radius: 20px; margin-top: 10px; }
        .wallet-card.debt-mode .wallet-convert { background: rgba(255,255,255,0.9); color: #c0392b; font-weight: bold; }

        .g-event-alert { background: linear-gradient(135deg, #00c6ff 0%, #0072ff 100%); color: white; border-radius: 12px; padding: 15px; text-align: center; font-weight: bold; font-size: 0.95rem; line-height: 1.4; box-shadow: 0 4px 15px rgba(0, 114, 255, 0.4); margin-bottom: 20px; border: 2px dashed #fff; animation: bounce 1s infinite alternate; }
        @keyframes bounce { 0% { transform: translateY(0); } 100% { transform: translateY(-4px); } }

        .estate-alert-box { background: #fdf2e9; border: 2px solid #e67e22; border-radius: 12px; padding: 15px; margin-bottom: 20px; box-shadow: 0 4px 10px rgba(230, 126, 34, 0.2); }
        .estate-alert-item { font-weight: bold; font-size: 0.95rem; line-height: 1.5; padding: 8px 0; border-bottom: 1px dashed #fad7a1; }
        .estate-alert-item:last-child { border-bottom: none; padding-bottom: 0; }
        .estate-alert-item.bad { color: #c0392b; }
        .estate-alert-item.good { color: #27ae60; }
        
        .accelerator-card { background: white; border-radius: 12px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-bottom: 20px; border-left: 5px solid #8e44ad; }
        .acc-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f5f5f6; }
        .acc-row:last-child { border-bottom: none; }
        .acc-title { font-weight: bold; font-size: 0.9rem; color: #2c3e50; }
        .acc-val { font-size: 0.95rem; }
        .edu-tips { background: #f4ecf7; padding: 10px; border-radius: 6px; color: #6c5ce7; font-size: 0.8rem; margin-top: 10px; font-weight: bold; line-height: 1.4; }

        .progress-container { background: white; border-radius: 12px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); margin-bottom: 20px; }
        .progress-header { display: flex; justify-content: space-between; font-size: 0.9rem; font-weight: bold; color: #2c3e50; margin-bottom: 8px; }
        .progress-bar-bg { background-color: #ecf0f1; height: 12px; border-radius: 6px; overflow: hidden; }
        .progress-bar-fill { height: 100%; border-radius: 6px; transition: width 0.5s ease-out; }
        .bg-safe { background-color: #2ecc71; }
        .bg-warn { background-color: #f39c12; }
        .bg-danger { background-color: #e74c3c; }

        .section-title { font-size: 1.1rem; color: #2c3e50; margin: 25px 0 10px 0; font-weight: bold; }
        .card-list { display: flex; flex-direction: column; gap: 12px; }
        .card { background: white; border-radius: 12px; padding: 15px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
        .task-info { flex: 1; }
        .task-name { font-weight: bold; color: #2c3e50; display: block; margin-bottom: 4px; font-size: 1.05rem; }
        .task-meta { font-size: 0.8rem; color: #7f8c8d; }
        
        .btn-start { background-color: #2ecc71; color: white; text-decoration: none; padding: 10px 18px; border-radius: 20px; font-weight: bold; font-size: 0.95rem; border: none; }
        .btn-checkin { background-color: #8e44ad; color: white; text-decoration: none; padding: 10px 18px; border-radius: 20px; font-weight: bold; font-size: 0.95rem; border: none; }
        .btn-disabled { background-color: #bdc3c7; color: white; padding: 10px 18px; border-radius: 20px; font-weight: bold; font-size: 0.95rem; cursor: not-allowed; }
        
        .badge-pending { background-color: #fff3e0; color: #e67e22; padding: 8px 12px; border-radius: 8px; text-align: center; }
        .badge-completed { background-color: #e8f8f5; color: #1abc9c; padding: 8px 12px; border-radius: 8px; text-align: center; border: 1px solid #a3e4d7; }
        .badge-punish { background-color: #fdf2e9; color: #e74c3c; padding: 8px 12px; border-radius: 8px; text-align: center; border: 1px solid #fadbd8; }
        
        .empty-hint { text-align: center; color: #95a5a6; padding: 20px; background: #f9f9f9; border-radius: 10px; border: 1px dashed #ccc; }
        .task-buff-badge { display: inline-block; background: #f4ecf7; color: #8e44ad; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; margin-top: 5px; border: 1px solid #d7bde2;}
    </style>
</head>
<body>

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

<div class="container">
    
    <?php if(isset($_GET['msg'])): ?>
        <script>setTimeout(() => { alert("✅ <?php echo str_replace(['"', "\r", "\n"], ['\"', '', ''], $_GET['msg']); ?>"); }, 100);</script>
    <?php endif; ?>

    <?php if (!empty($event_alert_msg)): ?>
        <div class="g-event-alert"><?php echo $event_alert_msg; ?></div>
    <?php endif; ?>

    <?php if (count($estate_alerts) > 0): ?>
        <div class="estate-alert-box">
            <?php foreach($estate_alerts as $alert): 
                $is_bad = strpos($alert, '遭受') !== false || strpos($alert, '天災') !== false;
                $class = $is_bad ? 'bad' : 'good';
            ?>
                <div class="estate-alert-item <?php echo $class; ?>"><?php echo htmlspecialchars($alert); ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="wallet-card <?php echo ($current_balance < 0) ? 'debt-mode' : ''; ?>">
        <p style="margin:0; font-size: 0.9rem; opacity:0.8;">我的可用時間</p>
        <p class="wallet-balance"><?php echo $current_balance; ?></p>
        <p class="wallet-unit">分鐘 (MINS)</p>
        <?php if ($time_convert_str): ?>
            <div class="wallet-convert"><?php echo $time_convert_str; ?></div>
        <?php endif; ?>
    </div>

    <div class="accelerator-card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; border-bottom: 2px solid #f4ecf7; padding-bottom: 8px;">
            <span style="font-weight:bold; color:#8e44ad; font-size:1.05rem; display:flex; align-items:center; gap:5px;">📊 我的多元資產加速器</span>
            <span style="font-size: 0.85rem; background: #8e44ad; color: white; padding: 3px 10px; border-radius: 12px; font-weight: bold;">
                💰 總資產現值: <?php echo number_format($total_assets); ?> 分
            </span>
        </div>
        
        <div class="acc-row">
            <span class="acc-title">🏃 累計次數 / 任務主動收入</span>
            <span class="acc-val">
                <span style="color:#7f8c8d;"><?php echo number_format($total_task_count); ?> 次</span> / 
                <span style="color:#2ecc71; font-weight:bold;">+<?php echo number_format($total_task_earned); ?> <span style="font-size:0.8rem; font-weight:normal; color:#7f8c8d;">分</span></span>
            </span>
        </div>
        <div class="acc-row">
            <span class="acc-title">📈 股市即時現值 / 累計賺取</span>
            <span class="acc-val">
                <span style="color:#f39c12; font-weight:bold;"><?php echo number_format($stock_value); ?> <span style="font-size:0.8rem; font-weight:normal; color:#7f8c8d;">分</span></span> / 
                <span style="color:#2ecc71; font-weight:bold;">+<?php echo number_format($stock_earned); ?> <span style="font-size:0.8rem; font-weight:normal; color:#7f8c8d;">分</span></span>
            </span>
        </div>
        <div class="acc-row">
            <span class="acc-title">🏘️ 房產抗通膨現值 / 營業淨利</span>
            <span class="acc-val">
                <span style="color:#9b59b6; font-weight:bold;"><?php echo number_format($estate_value); ?> <span style="font-size:0.8rem; font-weight:normal; color:#7f8c8d;">分</span></span> / 
                <span style="color:#2ecc71; font-weight:bold;">+<?php echo number_format($estate_earned); ?> <span style="font-size:0.8rem; font-weight:normal; color:#7f8c8d;">分</span></span>
            </span>
        </div>

        <?php 
        $ratio_total = $total_task_earned + $stock_value + $estate_value;
        $p_task = 0; $p_stock = 0; $p_estate = 0;
        if ($ratio_total > 0) {
            $p_task = round(($total_task_earned / $ratio_total) * 100);
            $p_stock = round(($stock_value / $ratio_total) * 100);
            $p_estate = round(($estate_value / $ratio_total) * 100);
        }
        ?>
        <div style="margin-top: 15px; font-size: 0.8rem; font-weight: bold; color: #555;">🧭 核心三大動力發展佔比：</div>
        <div class="proportion-bar" style="display: flex; height: 12px; border-radius: 6px; overflow: hidden; margin-top: 6px; background: #ecf0f1;">
            <div style="width: <?php echo $p_task; ?>%; background: #2ecc71;" title="任務主動收入"></div>
            <div style="width: <?php echo $p_stock; ?>%; background: #f39c12;" title="股市現值"></div>
            <div style="width: <?php echo $p_estate; ?>%; background: #9b59b6;" title="房產現值"></div>
        </div>
        <div style="display: flex; justify-content: space-between; font-size: 0.75rem; margin-top: 6px; font-weight: bold;">
            <span style="color:#2ecc71;">🏃 主動勞動: <?php echo $p_task; ?>%</span>
            <span style="color:#f39c12;">📈 股市干涉: <?php echo $p_stock; ?>%</span>
            <span style="color:#9b59b6;">🏘️ 房產抗通膨: <?php echo $p_estate; ?>%</span>
        </div>
        
        <?php 
            if ($stock_value == 0 && $estate_value == 0) {
                $tips = "💡 <b>小小財商提示：</b> 主動收入 (做任務) 是累積財富的基礎！有了第一桶金後，試著買張股票或開發新土地，啟動你的被動收入加速器吧！";
            } elseif ($estate_earned >= $stock_earned && $estate_value > 0) {
                $tips = "💡 <b>小小財商提示：</b> 目前<b>房地產</b>為你創造了豐厚的睡後被動收入！在對的地段持續升級建物，能讓時間資產複利滾動得更快！";
            } else {
                $tips = "💡 <b>小小財商提示：</b> 目前<b>時光股市</b>是你的主要獲利引擎！股票會隨著市場起伏，記得在賺到波段高點時，把一部分時間換成「保值增值」的房產進行避險喔！";
            }
        ?>
        <div class="edu-tips"><?php echo $tips; ?></div>
    </div>

    <div class="progress-container">
        <div class="progress-header">
            <span>⚡ 今日可賺取額度</span>
            <span>餘 <?php echo $remaining_limit; ?> / <?php echo $global_limit; ?> 分鐘</span>
        </div>
        <div class="progress-bar-bg">
            <?php 
                $bar_class = 'bg-safe';
                if ($usage_percent >= 80) $bar_class = 'bg-danger';
                elseif ($usage_percent >= 50) $bar_class = 'bg-warn';
            ?>
            <div class="progress-bar-fill <?php echo $bar_class; ?>" style="width: <?php echo $usage_percent; ?>%;"></div>
        </div>
    </div>

    <h3 class="section-title">🚀 今日專屬任務</h3>
    <div class="card-list">
        <?php if (count($today_tasks) > 0): ?>
            <?php foreach ($today_tasks as $task): $tid = $task['template_id']; ?>
            <div class="card">
                <div class="task-info">
                    <span class="task-name"><?php echo htmlspecialchars($task['task_name']); ?></span>
                    <?php if ($task['schedule_type'] === 'daily_deadline'): ?>
                        <div class="task-meta">⏰ 目標時間：<?php echo $task['schedule_value']; ?> 前 | 最高獎勵 <?php echo $task['estimated_time']; ?> 分</div>
                    <?php else: ?>
                        <div class="task-meta">⏱️ 預計 <?php echo $task['estimated_time']; ?> 分 | ⭐ x<?php echo $task['weight']; ?></div>
                    <?php endif; ?>
                    
                    <?php if (isset($task_buffs[$tid])): ?>
                        <?php foreach($task_buffs[$tid] as $tb): ?>
                            <div class="task-buff-badge">
                                🪄 已掛載：
                                <?php 
                                    if ($tb['buff_type'] == 'multiplier') echo "倍率卡 (x{$tb['effect_value']})";
                                    elseif ($tb['buff_type'] == 'shield') echo "護盾卡 (免扣分)";
                                    elseif ($tb['buff_type'] == 'fixed_time') echo "時光干涉 ({$tb['effect_value']}分)";
                                ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="task-action">
                    <?php if (isset($pending_map[$tid])): ?>
                        <div class="badge-pending"><strong>確認中</strong></div>
                    <?php elseif (isset($completed_today_map[$tid])): ?>
                        <?php 
                            $earned = (int)$completed_today_map[$tid]['earned_minutes'];
                            $sign = $earned > 0 ? '+' : '';
                            if ($earned < 0) {
                                $badge_class = 'badge-punish';
                                $status_text = '逾時扣分';
                            } else {
                                $badge_class = 'badge-completed';
                                $status_text = '已結算';
                            }
                        ?>
                        <div class="<?php echo $badge_class; ?>">
                            <div style="font-size: 0.75rem; margin-bottom: 2px; font-weight:bold; opacity: 0.9;"><?php echo $status_text; ?></div>
                            <strong style="font-size: 1.2rem;"><?php echo $sign . $earned; ?> 分</strong>
                        </div>
                    <?php else: ?>
                        <?php if ($task['schedule_type'] === 'daily_deadline'): ?>
                            <form method="POST" action="execute_deadline.php" style="margin:0;">
                                <input type="hidden" name="task_id" value="<?php echo $tid; ?>">
                                <input type="hidden" name="task_name" value="<?php echo htmlspecialchars($task['task_name']); ?>">
                                <input type="hidden" name="estimated_time" value="<?php echo $task['estimated_time']; ?>">
                                <input type="hidden" name="target_time" value="<?php echo htmlspecialchars($task['schedule_value']); ?>">
                                <button type="submit" class="btn-checkin" onclick="return confirm('準備好要打卡了嗎？將會以現在的時間結算差距喔！');">完成來打卡</button>
                            </form>
                        <?php else: ?>
                            <a href="execute_task.php?task_id=<?php echo $tid; ?>" class="btn-start">開始</a>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-hint">太棒了！今天沒有任務，或者您都做完了！</div>
        <?php endif; ?>
    </div>

    <h3 class="section-title" style="margin-top:35px;">📅 明日預告</h3>
    <div class="card-list">
        <?php if (count($tomorrow_tasks) > 0): ?>
            <?php foreach ($tomorrow_tasks as $task): ?>
            <div class="card" style="background-color: #fdfdfd; border: 1px dashed #e0e0e0; box-shadow: none;">
                <div class="task-info">
                    <span class="task-name" style="color: #7f8c8d;"><?php echo htmlspecialchars($task['task_name']); ?></span>
                    <div class="task-meta">
                        <?php echo ($task['schedule_type'] === 'daily_deadline') ? "⏰ 目標 {$task['schedule_value']} 前" : "⏱️ 預計 {$task['estimated_time']} 分"; ?>
                    </div>
                </div>
                <div class="task-action"><span class="btn-disabled">明天再戰</span></div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-hint">明天暫時還沒有被指派任務喔。</div>
        <?php endif; ?>
    </div>

    <div style="margin-top: 30px; background: #2c3e50; border-radius: 12px; padding: 20px; color: white; box-shadow: 0 4px 15px rgba(0,0,0,0.15); position: relative; overflow: hidden;">
        <div style="position: absolute; top: -10px; right: -10px; font-size: 5rem; opacity: 0.1;">📰</div>
        <h3 style="margin: 0 0 15px 0; font-size: 1.1rem; color: #f1c40f; text-align: center;">📡 世界政府廣播頻道</h3>
        <?php if (count($global_messages) > 0): ?>
            <?php foreach ($global_messages as $index => $msg): ?>
                <div style="margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px dashed #34495e;">
                    <div style="font-size: 0.75rem; color: #bdc3c7; margin-bottom: 4px;">📅 <?php echo date('Y/m/d H:i', strtotime($msg['created_at'])); ?></div>
                    <div style="font-size: 0.9rem; line-height: 1.5; color: #ecf0f1;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p style="text-align: center; color: #bdc3c7; font-size: 0.9rem;">目前尚無公告。</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>