<?php
// api/claim_task.php - 天啟防超刷：0.1秒極速佔位引擎 (雙宇宙通用)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$input = json_decode(file_get_contents("php://input"), true);
$user_id = $input['user_id'] ?? 0;
$task_id = $input['task_id'] ?? 0;

if (!$user_id || !$task_id) { echo json_encode(["status" => "error", "message" => "參數錯誤"]); exit; }

try {
    $pdo->beginTransaction();
    
    // 1. 鎖定任務，檢查預算是否足夠 (防超賣核心)
    $stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = ? AND is_active = 1 AND task_type = 'timer' FOR UPDATE");
    $stmt->execute([$task_id]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$task) throw new Exception("任務已下架或不存在！");
    if ($task['budget'] < $task['reward']) throw new Exception("手腳太慢啦！名額已被其他礦工搶光！");

    // 2. 檢查礦工是否已經佔位，或還在冷卻中
    $stmt = $pdo->prepare("SELECT MAX(created_at) as last_time, status FROM task_submissions WHERE task_id = ? AND user_id = ? GROUP BY status ORDER BY last_time DESC LIMIT 1");
    $stmt->execute([$task_id, $user_id]);
    $last_sub = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($last_sub) {
        if ($last_sub['status'] === 'pending') throw new Exception("您已經搶到名額，請勿重複點擊！");
        if ($last_sub['status'] === 'approved') {
            $diff = time() - strtotime($last_sub['last_time']);
            if ($diff < ($task['cooldown_minutes'] * 60)) throw new Exception("任務還在休息冷卻中！");
        }
    }

    // 3. 預先扣留預算 (把金主的錢先鎖起來)
    $stmt = $pdo->prepare("UPDATE tasks SET budget = budget - ? WHERE id = ?");
    $stmt->execute([$task['reward'], $task_id]);

    // 4. 發放佔位符 (pending)
    $stmt = $pdo->prepare("INSERT INTO task_submissions (task_id, user_id, status, created_at) VALUES (?, ?, 'pending', NOW())");
    $stmt->execute([$task_id, $user_id]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "佔位成功！允許放行！"]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>