<?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 = '';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'patch_dividend') {
    $past_start_prices = $_POST['past_start_prices'] ?? []; 
    
    try {
        $mysql_db->beginTransaction();
        $broadcast_news = [];

        foreach ($past_start_prices as $sid => $start_price) {
            $start_price = (float)$start_price;
            if ($start_price <= 0) continue; 

            $stmt_s = $mysql_db->prepare("SELECT * FROM global_stocks WHERE id = ? AND is_active = 1 FOR UPDATE");
            $stmt_s->execute([$sid]);
            $stock = $stmt_s->fetch();
            if (!$stock) continue;

            $current_price = (float)$stock['current_price'];
            
            $dividend_per_share = 0;
            if ($current_price > $start_price) {
                $monthly_profit = $current_price - $start_price;
                $dividend_per_share = $monthly_profit * 0.80; 
            }

            if ($dividend_per_share <= 0) continue;

            $dividend_per_share = round($dividend_per_share, 2);

            foreach ($players as $p) {
                if (!empty($p['sqlite_file']) && file_exists('../' . $p['sqlite_file'])) {
                    $p_db = getPlayerSQLiteConnection($p['sqlite_file']);
                    
                    try { $p_db->exec("ALTER TABLE stock_portfolio ADD COLUMN total_dividends REAL DEFAULT 0.0"); } catch (Exception $e) {}

                    $stmt_hold = $p_db->prepare("SELECT total_shares, average_cost FROM stock_portfolio WHERE stock_id = ? AND total_shares > 0");
                    $stmt_hold->execute([$sid]);
                    $hold = $stmt_hold->fetch();

                    if ($hold) {
                        $shares = (int)$hold['total_shares'];
                        $total_div_payout = (int)round($shares * $dividend_per_share); 

                        if ($total_div_payout > 0) {
                            $p_db->beginTransaction();
                            
                            $p_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $total_div_payout");
                            
                            // ★ 核心修正：只增加「累計領息」，不再扣減均價
                            $p_db->prepare("UPDATE stock_portfolio SET total_dividends = total_dividends + ? WHERE stock_id = ?")
                                 ->execute([$total_div_payout, $sid]);
                            
                            $log_desc = "💸 5月自動配息：【{$stock['stock_name']}】每股配發 {$dividend_per_share} 分，共獲得 {$total_div_payout} 分鐘！";
                            $p_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('stock_dividend', ?, ?)")
                                 ->execute([$total_div_payout, $log_desc]);
                            
                            $p_db->commit();
                        }
                    }
                }
            }

            $new_current_price = max(0.01, $current_price - $dividend_per_share);
            
            $stmt_up_market = $mysql_db->prepare("UPDATE global_stocks SET current_price = ?, month_start_price = ?, base_price = ? WHERE id = ?");
            $stmt_up_market->execute([round($new_current_price, 2), round($new_current_price, 2), round($new_current_price, 2), $sid]);

            $broadcast_news[] = "【{$stock['stock_name']}】每股配發 {$dividend_per_share} 分鐘 (股價已由 " . number_format($current_price, 2) . " 除息至 " . number_format($new_current_price, 2) . ")";
        }

        if (count($broadcast_news) > 0) {
            $msg = "【世界政府公告】💸 5 月份除權息完成！大盤系統已依據上月獲利自動發放 80% 現金股利！配息內容：" . implode('、', $broadcast_news) . "。請玩家重整帳戶查看被動收入！";
            $stmt_msg = $mysql_db->prepare("INSERT INTO global_messages (message) VALUES (?)");
            $stmt_msg->execute([$msg]);
        }

        $mysql_db->commit();
        $success_msg = "🚀 5月份時光回溯除權息補做成功！已依據原始邏輯完成發錢、大盤除息與新聞發布！";
    } catch (Exception $e) {
        $mysql_db->rollBack();
        $error_msg = "結算失敗：" . $e->getMessage();
    }
}

$stocks = $mysql_db->query("SELECT * FROM global_stocks WHERE is_active = 1 ORDER BY 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; padding: 40px 20px; }
        .card { max-width: 750px; margin: 0 auto; background: #16213e; padding: 30px; border-radius: 12px; border: 1px solid #0f3460; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        h1 { color: #4facfe; margin-top: 0; font-size: 1.4rem; text-align: center; border-bottom: 2px solid #0f3460; padding-bottom: 15px;}
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; }
        th { color: #bdc3c7; font-size: 0.9rem; }
        input[type="number"] { width: 120px; padding: 8px; background: #1a1a2e; border: 1px solid #0f3460; color: #fff; border-radius: 6px; text-align: center; font-size: 1rem; }
        .btn-submit { background: #e94560; color: white; border: none; padding: 14px; width: 100%; border-radius: 6px; font-weight: bold; font-size: 1.1rem; cursor: pointer; margin-top: 25px; transition: 0.3s; }
        .btn-submit:hover { background: #ff4d6d; }
        .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="card">
    <h1>🏛️ 5 月份除權息「時光回溯自動結算中心」</h1>
    
    <?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; ?>
    
    <p style="color: #bdc3c7; font-size:0.9rem; line-height:1.6;">
        💡 <b>運作原理：</b> 系統會拿 5/31 的結算價（現價）與您填寫的「5/1 原始起漲價」進行對比。若有獲利，系統將自動提取 <b>80% 作為股利</b> 發放，並自動將大盤與玩家持股成本進行「除息調降」。
    </p>

    <form method="POST">
        <input type="hidden" name="action" value="patch_dividend">
        <table>
            <thead>
                <tr>
                    <th>股票</th>
                    <th>5/31 結算價 (現價)</th>
                    <th>🧱 請輸入 5/1 原始起漲價</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($stocks as $s): ?>
                <tr>
                    <td>
                        <b style="color:#f1c40f; font-size:1.1rem;"><?php echo htmlspecialchars($s['stock_code']); ?></b><br>
                        <small style="color:#bdc3c7;"><?php echo htmlspecialchars($s['stock_name']); ?></small>
                    </td>
                    <td><strong style="font-size:1.1rem; color:#4facfe;"><?php echo number_format($s['current_price'], 2); ?></strong> 分鐘</td>
                    <td>
                        <input type="number" step="0.01" min="0.01" name="past_start_prices[<?php echo $s['id']; ?>]" placeholder="例: 10.00" required> 分鐘
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <button type="submit" class="btn-submit" onclick="return confirm('確定要啟動時光回溯結算嗎？系統將自動為有持股的小孩算錢、除息並發布大盤新聞！');">執行 5 月份自動除權息結算 🔔</button>
    </form>
</div>

</body>
</html>