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

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

$family_id = $_SESSION['family_id'];
$success_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fix_wallet') {
    $pid = (int)$_POST['player_id'];
    $new_balance = (int)$_POST['new_balance'];
    $reset_stock = isset($_POST['reset_stock']) ? true : false;

    // 取得小孩的資料庫路徑
    $stmt = $mysql_db->prepare("SELECT sqlite_file, display_name FROM users WHERE id = ? AND family_id = ?");
    $stmt->execute([$pid, $family_id]);
    $p = $stmt->fetch();

    if ($p && file_exists('../' . $p['sqlite_file'])) {
        $p_db = getPlayerSQLiteConnection($p['sqlite_file']);
        
        // 1. 強制覆寫錢包餘額
        $p_db->prepare("UPDATE wallet SET balance_minutes = ?")->execute([$new_balance]);
        
        $log_desc = "🔧 家長啟動資產重組法案：錢包餘額強制校正為 {$new_balance} 分鐘。";
        $p_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('admin_fix', 0, ?)")->execute([$log_desc]);

        // 2. 如果打勾，強制沒收所有異常股票
        if ($reset_stock) {
            $p_db->exec("UPDATE stock_portfolio SET total_shares = 0, average_cost = 0, total_dividends = 0");
        }
        
        $success_msg = "✅ 已成功將玩家 【{$p['display_name']}】 的錢包餘額強制變更為 {$new_balance} 分鐘！" . ($reset_stock ? " (並已強制沒收所有異常股票)" : "");
    }
}

// 取得家裡所有小孩清單
$players = $mysql_db->prepare("SELECT id, display_name FROM users WHERE role = 'player' AND family_id = ?");
$players->execute([$family_id]);
$player_list = $players->fetchAll();
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>上帝之手：玩家資產強制校正</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background-color: #f4f7f6; color: #333; padding: 40px 20px; }
        .card { max-width: 500px; margin: 0 auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); border-top: 5px solid #e74c3c; }
        h1 { color: #e74c3c; margin-top: 0; font-size: 1.4rem; text-align: center; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-weight: bold; color: #2c3e50; }
        select, input[type="number"] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 6px; font-size: 1rem; box-sizing: border-box; }
        .checkbox-label { display: flex; align-items: center; font-weight: normal; cursor: pointer; color: #e67e22; background: #fef9e7; padding: 10px; border-radius: 6px; border: 1px dashed #f39c12;}
        .checkbox-label input { width: auto; margin-right: 10px; transform: scale(1.2); }
        .btn-submit { background: #e74c3c; color: white; border: none; padding: 12px; width: 100%; border-radius: 6px; font-weight: bold; font-size: 1.1rem; cursor: pointer; transition: 0.3s; }
        .btn-submit:hover { background: #c0392b; }
        .alert-success { background: #27ae60; color: white; padding: 15px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: bold; }
    </style>
</head>
<body>

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

<div class="card">
    <h1>⚠️ 玩家資產強制校正工具</h1>
    
    <?php if ($success_msg): ?><div class="alert-success"><?php echo $success_msg; ?></div><?php endif; ?>
    
    <p style="color: #7f8c8d; font-size:0.9rem; line-height:1.6; text-align: justify;">
        當發生程式數值溢位、或小孩利用系統漏洞獲取不當鉅款時，家長可使用此工具強制執行「財富沒收與重組」。
    </p>

    <form method="POST" onsubmit="return confirm('確定要強制覆寫該玩家的資產嗎？此動作無法復原！');">
        <input type="hidden" name="action" value="fix_wallet">
        
        <div class="form-group">
            <label>👤 選擇要制裁的玩家</label>
            <select name="player_id" required>
                <option value="">-- 請選擇 --</option>
                <?php foreach($player_list as $p): ?>
                    <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['display_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>💰 強制覆寫錢包餘額 (分鐘)</label>
            <input type="number" name="new_balance" placeholder="請輸入要校正回歸的正確數字 (例如: 100)" required>
            <small style="color: #95a5a6; display:block; margin-top:5px;">注意：這是「覆寫」而非加減。輸入 50，他的錢包就會變成 50 分鐘。</small>
        </div>

        <div class="form-group">
            <label class="checkbox-label">
                <input type="checkbox" name="reset_stock" value="1" checked> 
                🚨 同步沒收所有庫存股票 (持股歸零)
            </label>
        </div>
        
        <button type="submit" class="btn-submit">執行判決：強制沒收與重組</button>
    </form>
</div>

</body>
</html>