<?php
// api/get_tasks.php - 雷達大廳任務派發引擎 (加入天啟掃地僧防超刷版)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 🛡️ 屠龍刀四神裝：確保資料庫欄位完整
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN task_type VARCHAR(20) NOT NULL DEFAULT 'screenshot'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN cooldown_minutes INT NOT NULL DEFAULT 0"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN duration INT NOT NULL DEFAULT 15"); } catch (Exception $e) {}

// 🧹 天啟掃地僧：自動釋放超時 (2分鐘) 未完成的幽靈佔位
try {
    // 1. 把逾期的預算還給金主任務池
    $pdo->exec("UPDATE tasks t 
                INNER JOIN task_submissions s ON t.id = s.task_id 
                SET t.budget = t.budget + t.reward 
                WHERE s.status = 'pending' AND s.created_at < DATE_SUB(NOW(), INTERVAL 2 MINUTE)");
    // 2. 刪除這些逾期的佔位紀錄，讓名額重新釋出
    $pdo->exec("DELETE FROM task_submissions WHERE status = 'pending' AND created_at < DATE_SUB(NOW(), INTERVAL 2 MINUTE)");
} catch (Exception $e) {}
// --------------------------------------------------------

$user_id = $_GET['user_id'] ?? 0;

try {
    // ✨ 嚴格篩選：只有 is_active=1 且【剩餘預算大於單次獎勵】的任務才會顯示在大廳
    $sql = "SELECT t.*,
            (SELECT MAX(created_at) FROM task_submissions s WHERE s.task_id = t.id AND s.user_id = ?) as last_submission_time,
            (SELECT status FROM task_submissions s WHERE s.task_id = t.id AND s.user_id = ? ORDER BY created_at DESC LIMIT 1) as last_status
        FROM tasks t WHERE t.is_active = 1 AND t.budget >= t.reward ORDER BY t.task_type DESC, t.id DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $user_id]);
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response_data = [];
    $now = time();

    foreach ($tasks as $task) {
        $status = 'available'; 
        $cooldown_left = 0;    

        if ($task['task_type'] === 'screenshot') {
            if ($task['last_submission_time']) {
                $status = ($task['last_status'] === 'rejected') ? 'available' : 'completed';
            }
        } else if ($task['task_type'] === 'timer') {
            if ($task['last_submission_time']) {
                if ($task['last_status'] === 'pending') {
                    // 如果他剛剛佔了位還沒核銷，讓他等一下，或者等掃地僧掃掉
                    $status = 'cooldown';
                    $cooldown_left = 60; 
                } else {
                    $last_time = strtotime($task['last_submission_time']);
                    $diff = $now - $last_time;
                    $cd_seconds = ($task['cooldown_minutes'] * 60);

                    if ($diff < $cd_seconds) {
                        $status = 'cooldown';
                        $cooldown_left = $cd_seconds - $diff;
                    }
                }
            }
        }

        $response_data[] = [
            'id' => $task['id'],
            'title' => $task['title'],
            'url' => $task['url'],
            'reward' => $task['reward'],
            'icon' => $task['icon'] ?? '⚡',
            'description' => $task['description'],
            'task_type' => $task['task_type'], 
            'status' => $status,               
            'cooldown_left' => $cooldown_left, 
            'last_status' => $task['last_status'],
            'duration' => (int)($task['duration'] ?? 15)
        ];
    }
    echo json_encode(["status" => "success", "data" => $response_data]);
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>