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

// 安全防護：檢查超級管理員登入
if (!isset($_SESSION['super_admin_logged_in']) || $_SESSION['super_admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

$success_msg = '';
$error_msg = '';

// ★ 自動防呆：擴充資料庫欄位精度以支援 0.1% (0.001) 與股市新機制
try {
    $mysql_db->query("SELECT interest_frequency FROM global_settings LIMIT 1");
} catch (Exception $e) {
    $mysql_db->exec("ALTER TABLE global_settings ADD COLUMN interest_frequency VARCHAR(20) DEFAULT 'weekly' AFTER global_interest_rate");
}
try {
    $mysql_db->exec("ALTER TABLE global_settings MODIFY COLUMN global_interest_rate DECIMAL(10,4) DEFAULT 0.001");
    $mysql_db->exec("ALTER TABLE global_stocks ADD COLUMN target_month VARCHAR(7) DEFAULT '' AFTER volatility_limit");
    $mysql_db->exec("ALTER TABLE global_stocks ADD COLUMN target_price DECIMAL(10,2) DEFAULT 0 AFTER target_month");
} catch (Exception $e) { }

// ==========================================
// 1. 處理 POST 動作
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'update_global') {
        $rate = (float)$_POST['interest_rate'];
        $freq = trim($_POST['interest_frequency']); 
        $limit = (int)$_POST['task_limit'];
        $tz = trim($_POST['timezone']); 
        $new_message = trim($_POST['message']);

        try {
            $mysql_db->beginTransaction();
            $sql = "UPDATE global_settings SET global_interest_rate = :rate, interest_frequency = :freq, daily_task_limit = :limit, timezone = :tz WHERE id = 1";
            $stmt = $mysql_db->prepare($sql);
            $stmt->execute([':rate' => $rate, ':freq' => $freq, ':limit' => $limit, ':tz' => $tz]);

            if (!empty($new_message)) {
                $sql_msg = "INSERT INTO global_messages (message) VALUES (:msg)";
                $stmt_msg = $mysql_db->prepare($sql_msg);
                $stmt_msg->execute([':msg' => $new_message]);
            }

            $mysql_db->commit();
            $success_msg = "🌍 全球政府營運設定已成功發布！";
            date_default_timezone_set($tz);
        } catch (PDOException $e) {
            $mysql_db->rollBack();
            $error_msg = "更新失敗：" . $e->getMessage();
        }
    } 
    // --- 動作 B：新增起點金/節日事件 ---
    elseif ($action === 'add_event') {
        $event_name = trim($_POST['event_name']);
        $trigger_type = $_POST['trigger_type'];
        $reward_minutes = (int)$_POST['reward_minutes'];
        
        // ★ 依據三種類型，組合出正確的觸發值
        if ($trigger_type === 'weekly') {
            $trigger_value = $_POST['trigger_weekday'];
        } elseif ($trigger_type === 'annual') {
            $trigger_value = sprintf('%02d-%02d', $_POST['annual_month'], $_POST['annual_day']);
        } else {
            $trigger_type = 'specific_date';
            $trigger_value = $_POST['trigger_date'];
        }

        if (empty($event_name) || $reward_minutes <= 0 || empty($trigger_value)) {
            $error_msg = "請確認所有活動欄位皆填寫正確，且獎勵必須大於 0 分鐘！";
        } else {
            try {
                $sql = "INSERT INTO global_rewards_events (event_name, trigger_type, trigger_value, reward_minutes) VALUES (:n, :t, :v, :r)";
                $stmt = $mysql_db->prepare($sql);
                $stmt->execute([':n' => $event_name, ':t' => $trigger_type, ':v' => $trigger_value, ':r' => $reward_minutes]);
                $success_msg = "🎁 成功創立全球起點獎勵事件：【{$event_name}】！";
            } catch (PDOException $e) {
                $error_msg = "創立活動失敗：" . $e->getMessage();
            }
        }
    }
    elseif ($action === 'delete_event' && !empty($_POST['event_id'])) {
        try {
            $stmt = $mysql_db->prepare("DELETE FROM global_rewards_events WHERE id = :id");
            $stmt->execute([':id' => $_POST['event_id']]);
            $success_msg = "🗑️ 該項起點獎勵事件已成功下架銷毀。";
        } catch (PDOException $e) {
            $error_msg = "刪除活動失敗。";
        }
    }
    elseif ($action === 'delete_message' && !empty($_POST['message_id'])) {
        try {
            $stmt_del = $mysql_db->prepare("DELETE FROM global_messages WHERE id = :id");
            $stmt_del->execute([':id' => $_POST['message_id']]);
            $success_msg = "🗑️ 該則系統公告已成功刪除！";
        } catch (PDOException $e) {
            $error_msg = "刪除失敗。";
        }
    } 
    elseif ($action === 'logout') {
        unset($_SESSION['super_admin_logged_in']);
        header("Location: login.php");
        exit;
    }
}

// ==========================================
// 2. 讀取畫面所需資料 (GET)
// ==========================================
$stmt = $mysql_db->query("SELECT * FROM global_settings WHERE id = 1");
$global = $stmt->fetch();

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

$events = $mysql_db->query("SELECT * FROM global_rewards_events ORDER BY trigger_type ASC, trigger_value ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>世界政府控制台 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #1a1a2e; color: #e9ecef; margin: 0; padding: 40px 20px; }
        .container { max-width: 1000px; margin: 0 auto; display: flex; flex-direction: column; gap: 30px; box-sizing: border-box; }
        .card { background: #16213e; padding: 30px; border-radius: 15px; border: 1px solid #0f3460; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
        h1, h2 { color: #f1c40f; border-bottom: 2px solid #e94560; padding-bottom: 10px; margin-top: 0; }
        h2 { font-size: 1.3rem; border-color: #3498db; color: #3498db; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-weight: bold; color: #4facfe; }
        input, textarea, select { width: 100%; padding: 12px; background: #1a1a2e; border: 1px solid #0f3460; color: #fff; border-radius: 8px; font-size: 1rem; box-sizing: border-box;}
        textarea { height: 70px; }
        .btn-submit { background: #e94560; color: white; border: none; padding: 12px; width: 100%; border-radius: 8px; font-size: 1.05rem; font-weight: bold; cursor: pointer; transition: 0.3s; }
        .btn-submit:hover { background: #ff4d6d; }
        .btn-event { background: #3498db; }
        .btn-event:hover { background: #2980b9; }
        .alert { background: #27ae60; color: white; padding: 12px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-weight: bold; }
        
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; }
        th { color: #4facfe; background: rgba(0,0,0,0.2); }
        .btn-del-msg { background: transparent; color: #e74c3c; border: none; cursor: pointer; font-size: 1.1rem; }
    </style>
</head>
<body>

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

<div class="container">
    
    <?php if ($success_msg): ?><div class="alert"><?php echo $success_msg; ?></div><?php endif; ?>
    <?php if ($error_msg): ?><div class="alert" style="background:#e74c3c;"><?php echo $error_msg; ?></div><?php endif; ?>

    <div class="card">
        <h1>🌍 世界政府核心控制台</h1>
        <form method="POST">
            <input type="hidden" name="action" value="update_global">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                <div class="form-group">
                    <label>🏦 銀行基準利率 (如 0.001 即 0.1%)</label>
                    <input type="number" name="interest_rate" step="0.001" value="<?php echo htmlspecialchars($global['global_interest_rate']); ?>" required>
                </div>
                <div class="form-group">
                    <label>🔄 銀行計息頻率</label>
                    <select name="interest_frequency" required>
                        <option value="daily" <?php echo ($global['interest_frequency'] === 'daily') ? 'selected' : ''; ?>>每日 (每天凌晨過夜結算)</option>
                        <option value="weekly" <?php echo ($global['interest_frequency'] === 'weekly') ? 'selected' : ''; ?>>每週 (每週一凌晨結算)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>🛡️ 每日任務原始額度 (分鐘)</label>
                    <input type="number" name="task_limit" value="<?php echo $global['daily_task_limit']; ?>" required>
                </div>
                <div class="form-group">
                    <label>🌐 營運核心時區</label>
                    <select name="timezone" required>
                        <option value="Asia/Taipei" <?php echo ($global['timezone'] == 'Asia/Taipei') ? 'selected' : ''; ?>>Asia/Taipei (台灣時間)</option>
                        <option value="America/New_York" <?php echo ($global['timezone'] == 'America/New_York') ? 'selected' : ''; ?>>America/New_York (美東時間)</option>
                        <option value="UTC" <?php echo ($global['timezone'] == 'UTC') ? 'selected' : ''; ?>>UTC (世界協調時間)</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>📡 發布全域系統廣播公告 (選填)</label>
                <textarea name="message" placeholder="輸入新的廣播公告訊息..."></textarea>
            </div>
            <button type="submit" class="btn-submit">發布核心參數變更</button>
        </form>
    </div>

    <div class="card" style="border-color: #8e44ad;">
        <h1 style="color: #9b59b6; border-color: #9b59b6;">🎲 大富翁「經過起點」與節日發財金設定庫</h1>
        
        <form method="POST" style="background: rgba(0,0,0,0.15); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
            <input type="hidden" name="action" value="add_event">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; align-items: end;">
                <div class="form-group" style="margin:0;">
                    <label>🎈 福利事件名稱</label>
                    <input type="text" name="event_name" placeholder="例: 經過起點補給、中秋禮金" required>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>⏰ 發放規則類型</label>
                    <select name="trigger_type" id="trigger_type" onchange="toggleEventInputs()" required>
                        <option value="weekly">🔄 每週固定發放</option>
                        <option value="annual">🎂 每年固定 (國曆節日)</option>
                        <option value="specific_date">📅 單次指定 (適合農曆節日)</option>
                    </select>
                </div>
                
                <div class="form-group" style="margin:0;" id="grp_weekly">
                    <label>指定星期幾</label>
                    <select name="trigger_weekday">
                        <option value="1">星期一 (每週發薪)</option>
                        <option value="2">星期二</option>
                        <option value="3">星期三</option>
                        <option value="4">星期四</option>
                        <option value="5">星期五</option>
                        <option value="6">星期六</option>
                        <option value="0">星期日</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0; display:none;" id="grp_annual">
                    <label>選擇固定月份/日期</label>
                    <div style="display:flex; gap:5px;">
                        <select name="annual_month">
                            <?php for($i=1; $i<=12; $i++) echo "<option value='".sprintf("%02d", $i)."'>{$i}月</option>"; ?>
                        </select>
                        <select name="annual_day">
                            <?php for($i=1; $i<=31; $i++) echo "<option value='".sprintf("%02d", $i)."'>{$i}日</option>"; ?>
                        </select>
                    </div>
                </div>
                
                <div class="form-group" style="margin:0; display:none;" id="grp_date">
                    <label>指定確切日期</label>
                    <input type="date" name="trigger_date">
                </div>

                <div class="form-group" style="margin:0;">
                    <label>💰 發放金額 (分)</label>
                    <input type="number" name="reward_minutes" min="1" placeholder="分" required>
                </div>
                <button type="submit" class="btn-submit btn-event">🎨 發布活動</button>
            </div>
        </form>

        <h2>📜 目前發行中的全域發放事件</h2>
        <?php if(count($events) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>事件福利名稱</th>
                        <th>類型</th>
                        <th>觸發條件</th>
                        <th>金額</th>
                        <th width="50">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($events as $ev): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($ev['event_name']); ?></strong></td>
                        <td>
                            <?php 
                                if($ev['trigger_type'] === 'weekly') echo '🔄 每週重複';
                                elseif($ev['trigger_type'] === 'annual') echo '🎂 每年固定';
                                else echo '📅 單次指定';
                            ?>
                        </td>
                        <td>
                            <?php 
                                if($ev['trigger_type'] === 'weekly') {
                                    $w_map = ['0'=>'日','1'=>'一','2'=>'二','3'=>'三','4'=>'四','5'=>'五','6'=>'六'];
                                    echo "星期" . $w_map[$ev['trigger_value']];
                                } elseif($ev['trigger_type'] === 'annual') {
                                    echo "每年 " . htmlspecialchars($ev['trigger_value']);
                                } else {
                                    echo htmlspecialchars($ev['trigger_value']);
                                }
                            ?>
                        </td>
                        <td style="color:#2ecc71; font-weight:bold;">+ <?php echo $ev['reward_minutes']; ?> 分</td>
                        <td>
                            <form method="POST" onsubmit="return confirm('確定要下架此活動嗎？');" style="margin:0;">
                                <input type="hidden" name="action" value="delete_event">
                                <input type="hidden" name="event_id" value="<?php echo $ev['id']; ?>">
                                <button type="submit" class="btn-del-msg">🗑️</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="color:#888; text-align:center; padding:15px;">目前尚未規劃任何福利活動。</p>
        <?php endif; ?>
    </div>

    <div class="card">
        <h2>📜 廣播頻道歷史公告 (營運時間: <?php echo date('Y-m-d H:i'); ?>)</h2>
        <?php if(count($history_msgs) > 0): ?>
            <?php foreach($history_msgs as $m): ?>
                <div style="border-bottom: 1px solid #0f3460; padding:12px 0; position:relative;">
                    <div style="font-size:0.8rem; color:#888;"><?php echo $m['created_at']; ?></div>
                    <div style="color:#ecf0f1; margin-top:5px; padding-right:40px;"><?php echo nl2br(htmlspecialchars($m['message'])); ?></div>
                    <form method="POST" onsubmit="return confirm('確定要刪除此公告嗎？');" style="position:absolute; right:0; top:10px;">
                        <input type="hidden" name="action" value="delete_message">
                        <input type="hidden" name="message_id" value="<?php echo $m['id']; ?>">
                        <button type="submit" class="btn-del-msg">🗑️</button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script>
    function toggleEventInputs() {
        const type = document.getElementById('trigger_type').value;
        document.getElementById('grp_weekly').style.display = (type === 'weekly') ? 'block' : 'none';
        document.getElementById('grp_annual').style.display = (type === 'annual') ? 'block' : 'none';
        document.getElementById('grp_date').style.display = (type === 'specific_date') ? 'block' : 'none';
    }
    // 確保頁面載入時正確顯示對應欄位
    window.onload = toggleEventInputs;
</script>
</body>
</html>