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

// 安全防護
if (!isset($_SESSION['super_admin_logged_in']) || $_SESSION['super_admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

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

// ★ 自動防呆：擴充評等與月初基準價欄位
try {
    $mysql_db->query("SELECT rating FROM global_stocks LIMIT 1");
} catch (Exception $e) {
    $mysql_db->exec("ALTER TABLE global_stocks ADD COLUMN rating INT DEFAULT 3 AFTER stock_name");
}
try {
    $mysql_db->query("SELECT month_start_price FROM global_stocks LIMIT 1");
} catch (Exception $e) {
    $mysql_db->exec("ALTER TABLE global_stocks ADD COLUMN month_start_price DECIMAL(10,2) DEFAULT 0 AFTER target_price");
}

// 觸發大盤自動更新
StockEngine::updateDailyPrices($mysql_db);

// 處理發行、修改與發布新聞
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // --- 動作 A：儲存/修改股票 ---
    if ($_POST['action'] === 'save_stock') {
        $id = !empty($_POST['stock_id']) ? (int)$_POST['stock_id'] : null;
        $code = strtoupper(trim($_POST['stock_code']));
        $name = trim($_POST['stock_name']);
        $rating = (int)$_POST['rating']; 
        $initial_price = (float)$_POST['initial_price'];
        $volatility = (float)$_POST['volatility_limit'] / 100; 
        $active = isset($_POST['is_active']) ? 1 : 0;

        if (empty($code) || empty($name) || $initial_price <= 0) {
            $error_msg = "代號、名稱不可空白，且初始發行價必須大於 0！";
        } else {
            try {
                if ($id) {
                    $sql = "UPDATE global_stocks SET stock_code=:c, stock_name=:n, rating=:r, volatility_limit=:v, is_active=:a WHERE id=:id";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':c'=>$code, ':n'=>$name, ':r'=>$rating, ':v'=>$volatility, ':a'=>$active, ':id'=>$id]);
                    $success_msg = "股票 {$code} 設定已更新！";
                } else {
                    $sql = "INSERT INTO global_stocks (stock_code, stock_name, rating, base_price, current_price, month_start_price, volatility_limit, is_active) 
                            VALUES (:c, :n, :r, :p, :p, :p, :v, :a)";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':c'=>$code, ':n'=>$name, ':r'=>$rating, ':p'=>$initial_price, ':v'=>$volatility, ':a'=>$active]);
                    $success_msg = "🎊 恭喜！新股票 {$name} ({$code}) 正式 IPO 上市！";
                }
            } catch (PDOException $e) {
                $error_msg = "儲存失敗，請檢查股票代號是否重複：" . $e->getMessage();
            }
        }
    }
    // --- 動作 B：發布財經新聞 (上帝之手) ---
    elseif ($_POST['action'] === 'publish_news') {
        $target_stock = $_POST['target_stock'];
        $news_title = trim($_POST['news_title']);
        $impact_value = (float)$_POST['impact_value'];

        if (empty($news_title)) {
            $error_msg = "新聞標題不可空白！";
        } else {
            try {
                $mysql_db->beginTransaction();
                
                $icon = ($impact_value > 0) ? '🚀' : '⚠️';
                $full_msg = "【財經快訊】{$icon} {$news_title}";
                $stmt_msg = $mysql_db->prepare("INSERT INTO global_messages (message) VALUES (:msg)");
                $stmt_msg->execute([':msg' => $full_msg]);

                $stmt_magic = $mysql_db->prepare("INSERT INTO stock_market_events (player_id, stock_code, effect_type, effect_value) VALUES (0, :code, 'news_impact', :val)");
                $stmt_magic->execute([':code' => $target_stock, ':val' => $impact_value]);

                $mysql_db->commit();
                $success_msg = "📰 財經新聞已發布！市場將於明日開盤時反應此消息。";
            } catch (Exception $e) {
                $mysql_db->rollBack();
                $error_msg = "發布新聞失敗：" . $e->getMessage();
            }
        }
    }
}

// 取得修改資料
$edit_stock = null;
if (isset($_GET['edit_id'])) {
    $stmt = $mysql_db->prepare("SELECT * FROM global_stocks WHERE id = :id");
    $stmt->execute([':id' => $_GET['edit_id']]);
    $edit_stock = $stmt->fetch();
}

// 取得大盤所有股票清單
$stocks = $mysql_db->query("SELECT * FROM global_stocks ORDER BY is_active DESC, stock_code 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: 1100px; margin: 0 auto; display: grid; grid-template-columns: 350px 1fr; gap: 20px; box-sizing: border-box; }
        @media (max-width: 768px) { .container { grid-template-columns: 1fr; } }
        .card { background: #16213e; padding: 25px; border-radius: 12px; border: 1px solid #0f3460; box-shadow: 0 5px 15px rgba(0,0,0,0.3);}
        h2 { color: #4facfe; margin-top: 0; font-size: 1.2rem; border-bottom: 1px solid #0f3460; padding-bottom: 10px;}
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 0.9rem; color: #bdc3c7; font-weight: bold;}
        input[type="text"], input[type="number"], select, textarea { width: 100%; padding: 10px; background: #1a1a2e; border: 1px solid #0f3460; color: #fff; border-radius: 6px; box-sizing: border-box; }
        input:disabled { opacity: 0.5; cursor: not-allowed; }
        .btn-save { background: #e94560; color: white; border: none; padding: 12px; width: 100%; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.3s;}
        .btn-save:hover { background: #ff4d6d; }
        .btn-news { background: #8e44ad; }
        .btn-news:hover { background: #9b59b6; }
        
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; }
        th { color: #bdc3c7; font-size: 0.9rem; }
        .up { color: #e74c3c; font-weight: bold; } 
        .down { color: #2ecc71; font-weight: bold; }
        .flat { color: #f1c40f; font-weight: bold; }
        .rating-stars { color: #f1c40f; font-size: 0.9rem; }
        
        .alert { padding: 12px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: bold; }
        .alert-success { background: #27ae60; color: white; }
        .alert-error { background: #e74c3c; color: white; }
    </style>
</head>
<body>

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

<div class="container">
    
    <div>
        <div class="card" style="margin-bottom: 20px;">
            <h2><?php echo $edit_stock ? '✏️ 修改股票設定' : '🚀 IPO 新股發行'; ?></h2>
            
            <?php if ($success_msg): ?><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>
            <?php if ($error_msg): ?><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
            
            <form method="POST" action="stocks.php">
                <input type="hidden" name="action" value="save_stock">
                <input type="hidden" name="stock_id" value="<?php echo $edit_stock['id'] ?? ''; ?>">
                
                <div style="display: flex; gap:10px;">
                    <div class="form-group" style="flex:1;">
                        <label>代號 (英數字)</label>
                        <input type="text" name="stock_code" value="<?php echo htmlspecialchars($edit_stock['stock_code'] ?? ''); ?>" placeholder="例: TIME" required>
                    </div>
                    <div class="form-group" style="flex:2;">
                        <label>公司名稱</label>
                        <input type="text" name="stock_name" value="<?php echo htmlspecialchars($edit_stock['stock_name'] ?? ''); ?>" placeholder="例: 時光科技" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>⭐ 公司評等 (體質與願景)</label>
                    <select name="rating" required>
                        <option value="5" <?php echo (($edit_stock['rating'] ?? 3) == 5) ? 'selected' : ''; ?>>⭐⭐⭐⭐⭐ (高成長潛力股)</option>
                        <option value="4" <?php echo (($edit_stock['rating'] ?? 3) == 4) ? 'selected' : ''; ?>>⭐⭐⭐⭐ (優質藍籌股)</option>
                        <option value="3" <?php echo (($edit_stock['rating'] ?? 3) == 3) ? 'selected' : ''; ?>>⭐⭐⭐ (穩定發展股)</option>
                        <option value="2" <?php echo (($edit_stock['rating'] ?? 3) == 2) ? 'selected' : ''; ?>>⭐⭐ (風險波動股)</option>
                        <option value="1" <?php echo (($edit_stock['rating'] ?? 3) == 1) ? 'selected' : ''; ?>>⭐ (夕陽產業股)</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>初始掛牌價 (單位:分鐘)</label>
                    <input type="number" step="0.01" name="initial_price" value="<?php echo $edit_stock ? $edit_stock['current_price'] : '10.00'; ?>" <?php echo $edit_stock ? 'disabled title="上市後不可隨意修改股價"' : 'required'; ?>>
                    <?php if ($edit_stock): ?>
                        <input type="hidden" name="initial_price" value="<?php echo $edit_stock['current_price']; ?>">
                    <?php endif; ?>
                </div>

                <div class="form-group">
                    <label>單日漲跌幅限制 (%)</label>
                    <input type="number" step="0.1" name="volatility_limit" value="<?php echo isset($edit_stock['volatility_limit']) ? ($edit_stock['volatility_limit'] * 100) : '10.0'; ?>" required>
                </div>

                <div class="form-group">
                    <label style="cursor: pointer; color: #ecf0f1; font-weight: normal; display:flex; align-items:center; gap:5px;">
                        <input type="checkbox" name="is_active" <?php echo (!isset($edit_stock) || $edit_stock['is_active']) ? 'checked' : ''; ?> style="width:auto;"> 
                        開放交易 (取消打勾即下市)
                    </label>
                </div>

                <button type="submit" class="btn-save"><?php echo $edit_stock ? '儲存變更' : '敲鐘發行'; ?></button>
                <?php if ($edit_stock): ?><a href="stocks.php" style="display: block; text-align: center; color: #888; margin-top: 15px; text-decoration: none;">取消</a><?php endif; ?>
            </form>
        </div>

        <div class="card" style="border-color: #8e44ad;">
            <h2 style="color: #9b59b6; border-color: #9b59b6;">📰 發布財經新聞 (上帝之手)</h2>
            <form method="POST" action="stocks.php">
                <input type="hidden" name="action" value="publish_news">
                
                <div class="form-group">
                    <label>受影響對象</label>
                    <select name="target_stock" required>
                        <option value="ALL">🌍 全體大盤 (總體經濟新聞)</option>
                        <?php foreach($stocks as $s): if($s['is_active']): ?>
                            <option value="<?php echo $s['stock_code']; ?>">🎯 <?php echo $s['stock_name']; ?> (<?php echo $s['stock_code']; ?>)</option>
                        <?php endif; endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>新聞標題 (會廣播給所有玩家)</label>
                    <textarea name="news_title" placeholder="例如：時光科技取得獨家大單！" required></textarea>
                </div>

                <div class="form-group">
                    <label>隱藏消息面影響力</label>
                    <select name="impact_value" required>
                        <option value="0.20">🚀 史詩級重大利多 (+20%)</option>
                        <option value="0.10">📈 明顯利多 (+10%)</option>
                        <option value="0.05">🙂 小幅利多 (+5%)</option>
                        <option value="-0.05">😕 小幅利空 (-5%)</option>
                        <option value="-0.10">📉 明顯利空 (-10%)</option>
                        <option value="-0.20">⚠️ 史詩級重大利空 (-20%)</option>
                    </select>
                </div>

                <button type="submit" class="btn-save btn-news">發送新聞並干預明日股市</button>
            </form>
        </div>
    </div>

    <div class="card">
        <h2 style="display: flex; justify-content: space-between;">
            <span>📈 大盤報價看板 (上帝視角)</span>
            <span style="font-size: 0.8rem; color: #7f8c8d;">更新基準日：<?php echo date('Y-m-d'); ?></span>
        </h2>
        <?php if(count($stocks) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>代號/公司</th>
                        <th>評等</th>
                        <th>昨收</th>
                        <th>現價</th>
                        <th>上帝指標</th>
                        <th width="40">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($stocks as $s): 
                        $diff = $s['current_price'] - $s['base_price'];
                        $percent = ($s['base_price'] > 0) ? ($diff / $s['base_price']) * 100 : 0;
                        
                        $color_class = 'flat'; $arrow = '-';
                        if ($diff > 0) { $color_class = 'up'; $arrow = '▲'; }
                        elseif ($diff < 0) { $color_class = 'down'; $arrow = '▼'; }
                        
                        $rating = $s['rating'] ?? 3;
                        $stars_html = str_repeat('★', $rating) . str_repeat('☆', 5 - $rating);
                    ?>
                    <tr style="<?php echo $s['is_active'] ? '' : 'opacity:0.4;'; ?>">
                        <td>
                            <strong style="color:#f1c40f;"><?php echo htmlspecialchars($s['stock_code']); ?></strong><br>
                            <small style="color:#bdc3c7;"><?php echo htmlspecialchars($s['stock_name']); ?></small>
                        </td>
                        <td class="rating-stars"><?php echo $stars_html; ?></td>
                        <td><?php echo number_format($s['base_price'], 2); ?></td>
                        <td>
                            <strong style="font-size:1.1rem;"><?php echo number_format($s['current_price'], 2); ?></strong><br>
                            <span class="<?php echo $color_class; ?>" style="font-size:0.8rem;"><?php echo $arrow . ' ' . number_format(abs($percent), 2); ?>%</span>
                        </td>
                        <td>
                            <div style="font-size: 0.75rem; color: #8e44ad; font-weight:bold;">🎯 目標: <?php echo number_format($s['target_price'], 2); ?></div>
                            <div style="font-size: 0.75rem; color: #95a5a6;">📍 月初: <?php echo number_format($s['month_start_price'], 2); ?></div>
                        </td>
                        <td>
                            <a href="stocks.php?edit_id=<?php echo $s['id']; ?>" style="color: #4facfe; text-decoration: none; font-weight:bold; font-size:0.9rem;">設定</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="color:#888; text-align:center; padding:20px;">目前大盤沒有任何股票，請在左側發行新股！</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>