<?php
// api/super_upgrade.php - 終極資料庫升級金鎚 (相容所有 MySQL 版本)
header("Content-Type: text/html; charset=utf-8");
require_once 'db.php';

echo "<body style='background:#0a0a0a; color:#00ff88; font-family:sans-serif; padding:30px;'>";
echo "<h2>🚀 帝國資料庫終極升級中...</h2>";

// 1. 建立禮品兌換訂單表 (這句語法很安全)
try {
    $sql_exchange = "CREATE TABLE IF NOT EXISTS exchange_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        item_name VARCHAR(100) NOT NULL,
        item_type VARCHAR(20) NOT NULL,
        cost INT NOT NULL,
        contact_info TEXT NOT NULL,
        status VARCHAR(20) DEFAULT 'pending',
        admin_note TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
    $pdo->exec($sql_exchange);
    echo "<p>✅ `exchange_requests` (禮品兌換倉庫) 就緒！</p>";
} catch (PDOException $e) {
    echo "<p style='color:red;'>❌ 建立兌換表失敗: " . $e->getMessage() . "</p>";
}

// 2. 暴力新增所有缺少的欄位 (使用 try-catch 避開語法報錯)
$columns_to_add = [
    // KYC 相關
    "ALTER TABLE users ADD COLUMN is_verified TINYINT(1) NOT NULL DEFAULT 0",
    "ALTER TABLE users ADD COLUMN id_photo VARCHAR(255) DEFAULT NULL",
    // 任務擴充相關 (補回遺失的平台與說明)
    "ALTER TABLE tasks ADD COLUMN platform VARCHAR(50) DEFAULT 'Website'",
    "ALTER TABLE tasks ADD COLUMN action_type VARCHAR(50) DEFAULT 'view'",
    "ALTER TABLE tasks ADD COLUMN description TEXT DEFAULT NULL"
];

foreach ($columns_to_add as $sql) {
    try {
        $pdo->exec($sql);
        echo "<p>✅ 成功擴建：" . htmlspecialchars($sql) . "</p>";
    } catch (PDOException $e) {
        // 錯誤碼 42S21 代表 "Duplicate column name" (欄位已存在，這是好消息)
        if ($e->getCode() == '42S21') {
            echo "<p style='color:#888;'>👌 欄位已存在，跳過：" . htmlspecialchars($sql) . "</p>";
        } else {
            echo "<p style='color:red;'>❌ 執行失敗: " . $e->getMessage() . "</p>";
        }
    }
}

// 建立上傳資料夾
if (!is_dir('../uploads/kyc/')) {
    @mkdir('../uploads/kyc/', 0777, true);
}

echo "<h3 style='color:#ffd700; margin-top:30px;'>🎉 終極升級完成！資料庫已無死角！</h3>";
echo "</body>";
?>