<?php
// rebuild_foundation.php - 強制重建基石 (修復欄位遺失問題)
// --------------------------------------------------
header("Content-Type: text/plain; charset=utf-8");
require_once 'db.php';

echo "🦁 Zoo Team 地基重塑程序啟動...\n";
echo "⚠️ 警告：這將清除舊有的 tasks 與 task_proofs 資料表\n\n";

try {
    // 1. 拆除舊屋 (DROP)
    $pdo->exec("DROP TABLE IF EXISTS tasks");
    $pdo->exec("DROP TABLE IF EXISTS task_proofs");
    echo "🏗️ [拆除] 舊有的資料表已移除。\n";

    // 2. 重建任務倉 (Tasks) - 包含 platform 欄位
    $sql_tasks = "CREATE TABLE tasks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        platform VARCHAR(20) NOT NULL COMMENT '平台類型',
        action_type VARCHAR(20) NOT NULL COMMENT '按讚/留言/瀏覽',
        target_url TEXT NOT NULL COMMENT '目標網址',
        cost INT DEFAULT 20 COMMENT '發布成本',
        reward INT DEFAULT 15 COMMENT '完成獎勵',
        proof_req VARCHAR(20) DEFAULT 'AUTO' COMMENT '驗證方式',
        warmth_bonus TINYINT DEFAULT 0 COMMENT '是否開啟打賞',
        status ENUM('active', 'paused', 'completed') DEFAULT 'active',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX (status),
        INDEX (platform)
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;";

    $pdo->exec($sql_tasks);
    echo "✅ [重建] 資料表 'tasks' (含 platform 欄位) 已建立。\n";

    // 3. 重建證物倉 (Proofs)
    $sql_proofs = "CREATE TABLE task_proofs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        task_id INT NOT NULL,
        worker_id INT NOT NULL COMMENT '執行者ID',
        proof_data TEXT COMMENT '截圖路徑或連結',
        comment TEXT COMMENT '暖心留言',
        status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX (task_id),
        INDEX (worker_id),
        INDEX (status)
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;";

    $pdo->exec($sql_proofs);
    echo "✅ [重建] 資料表 'task_proofs' 已建立。\n";

} catch (PDOException $e) {
    echo "❌ [失敗] 重建錯誤：" . $e->getMessage();
    exit;
}

echo "\n--------------------------------\n";
echo "🎉 地基已修復完畢！\n";
echo "請現在立刻去執行 'seed_tasks.php' 進行播種。";
?>