<?php
// api/rescue.php - 統帥真身尋回與絕對補款系統
header("Content-Type: text/html; charset=utf-8");
require_once 'db.php';

try {
    // 1. 用名字尋找統帥在資料庫裡的「真實 ID」
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = 'rainzoowon' OR email LIKE '%rainzoowon%' LIMIT 1");
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $real_id = $user['id'];
        // 找到了！升級為 99 級，並存入 999,999 資金
        $pdo->exec("UPDATE users SET level = 99, coins = 999999 WHERE id = $real_id");
        $msg = "找到了！您的真實 ID 是 <b>$real_id</b> (難怪用 8 找不到！)";
    } else {
        // 萬一資料庫被清空了，直接幫您原地滿血復活創建一個
        $pdo->exec("INSERT INTO users (username, email, password, level, coins) VALUES ('rainzoowon', 'rainzoowon@zoo.com', '88888888', 99, 999999)");
        $real_id = $pdo->lastInsertId();
        $msg = "資料庫似乎重置過，已為您原地重建統帥帳號，真實 ID 為 <b>$real_id</b>！";
    }

    // 2. 準備最完美的瀏覽器鑰匙
    $json_data = json_encode([
        "user_id" => $real_id,
        "username" => "rainzoowon",
        "coins" => 999999,
        "level" => 99
    ]);

    echo "
    <!DOCTYPE html>
    <html lang='zh-TW'>
    <head>
        <meta charset='UTF-8'>
        <title>統帥真身尋回</title>
        <style>
            body { background:#121212; color:#00ff88; 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 #00ff88; text-align:center; box-shadow:0 0 30px rgba(0, 255, 136, 0.2); max-width:500px; }
            h1 { color:#ffd700; margin-top:0; }
            p { color:#ccc; line-height:1.6; font-size:18px; }
            .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; width:100%; }
            .btn:hover { background:#fff; transform:scale(1.05); }
        </style>
    </head>
    <body>
        <div class='box'>
            <h1>👑 統帥真身已對齊！</h1>
            <p>$msg</p>
            <p>已將 <b>999,999 Z幣</b> 準確存入該帳號。</p>
            <button class='btn' onclick='syncAndGo()'>🚀 點我同步憑證並返回發布台</button>
        </div>

        <script>
            function syncAndGo() {
                // 暴力寫入帶有【真實 ID】的數據
                localStorage.setItem('zoo_user', '" . addslashes($json_data) . "');
                alert('✅ 憑證已完美同步！發布任務通道已全面暢通。');
                window.location.href = '../projects.html';
            }
        </script>
    </body>
    </html>
    ";

} catch (Exception $e) {
    echo "<h2 style='color:red; text-align:center; padding:50px;'>❌ 系統錯誤：" . $e->getMessage() . "</h2>";
}
?>