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

// 權限檢查 (僅限家長)
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

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

    foreach ($players as $p) {
        if (!empty($p['sqlite_file']) && file_exists('../' . $p['sqlite_file'])) {
            $p_db = getPlayerSQLiteConnection($p['sqlite_file']);
            // ★ 外科手術：只把變成「負數」的異常股票強制歸零，絕不傷害正常的股票
            $p_db->exec("UPDATE stock_portfolio SET total_shares = 0, average_cost = 0 WHERE total_shares < 0");
        }
    }
    $msg = "✅ 手術成功！系統中所有的「負數黑洞」已完美清除！您現在可以正常買賣股票了！";
} catch (Exception $e) {
    $msg = "執行失敗：" . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>黑洞清除工具</title>
    <style>
        body { font-family: sans-serif; background: #f4f7f6; text-align: center; padding: 100px 20px; }
        .card { background: white; padding: 40px; border-radius: 12px; display: inline-block; box-shadow: 0 4px 15px rgba(0,0,0,0.1); border-top: 5px solid #27ae60; }
    </style>
</head>
<body>
    <div class="card">
        <h2>🛠️ 異常資產修復中心</h2>
        <p style="font-size: 1.2rem; color: #2c3e50; font-weight: bold;"><?php echo $msg; ?></p>
    </div>
</body>
</html>