<?php
// api/fix_money.php - 強制同步金庫與錢包 (手動確認版)
header("Content-Type: text/html; charset=utf-8");
require_once 'db.php';

$user_id = 8; // 鎖定您的統帥 ID
$amount = 999999;

try {
    // 1. 強制更新資料庫 (銀行端)
    $stmt = $pdo->prepare("UPDATE users SET coins = ? WHERE id = ?");
    $stmt->execute([$amount, $user_id]);

    // 2. 重新撈取確認 (確保錢真的進去了)
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // 準備要寫入瀏覽器的 JSON
    $json_data = json_encode([
        "user_id" => $user['id'],
        "username" => $user['username'],
        "coins" => $user['coins'], // 這時候一定是 999999
        "level" => $user['level']
    ]);

    echo "
    <!DOCTYPE html>
    <html lang='zh-TW'>
    <head>
        <meta charset='UTF-8'>
        <title>金流同步中心</title>
        <style>
            body { background:#121212; color:#fff; font-family:sans-serif; display:flex; flex-direction:column; align-items:center; justify-content:center; height:100vh; margin:0; }
            .box { background:#1e1e1e; padding:40px; border-radius:15px; border:1px solid #ffd700; text-align:center; box-shadow:0 0 30px rgba(255, 215, 0, 0.2); max-width:400px; }
            h1 { color:#ffd700; margin-top:0; }
            p { color:#ccc; line-height:1.6; }
            .btn { background:#ffd700; color:#000; border:none; padding:15px 30px; font-size:18px; font-weight:bold; border-radius:50px; cursor:pointer; margin-top:20px; transition:0.3s; display:block; width:100%; }
            .btn:hover { background:#fff; transform:scale(1.05); }
        </style>
    </head>
    <body>
        <div class='box'>
            <h1>💰 撥款成功！</h1>
            <p>資料庫已存入 <b>999,999</b> Z幣。</p>
            <p>請點擊下方按鈕，強制更新您的瀏覽器錢包，並返回發布台。</p>
            
            <button class='btn' onclick='syncAndGo()'>🔄 同步錢包並返回</button>
        </div>

        <script>
            function syncAndGo() {
                // 暴力寫入最新數據
                localStorage.setItem('zoo_user', '$json_data');
                alert('✅ 錢包已更新！現在您可以發布任務了。');
                window.location.href = '../projects.html';
            }
        </script>
    </body>
    </html>
    ";

} catch (Exception $e) {
    echo "<h2 style='color:red;'>❌ 錯誤：" . $e->getMessage() . "</h2>";
}
?>