<?php
// api/mine_traffic.php - 流量礦池核銷發薪引擎 (雙宇宙通用 V3.3)
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;

try {
    $pdo->beginTransaction();
    
    // 1. 尋找該礦工的「佔位符 (pending)」，找不到代表作弊或已過期被掃地僧清掉了！
    $stmt = $pdo->prepare("SELECT id FROM task_submissions WHERE task_id = ? AND user_id = ? AND status = 'pending' FOR UPDATE");
    $stmt->execute([$task_id, $user_id]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sub) throw new Exception("找不到佔位紀錄或已超時失效！請重新接取任務。");

    // 2. 獲取任務資訊以發放獎勵
    $stmt = $pdo->prepare("SELECT title, reward FROM tasks WHERE id = ?");
    $stmt->execute([$task_id]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);

    // 3. 核銷成功！將狀態改為 approved，並更新時間以利計算下次冷卻
    $stmt = $pdo->prepare("UPDATE task_submissions SET status = 'approved', created_at = NOW() WHERE id = ?");
    $stmt->execute([$sub['id']]);

    // 4. 正式將 ZOO 幣發給礦工
    $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
    $stmt->execute([$task['reward'], $user_id]);

    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'TASK_REWARD', ?, ?)");
    $stmt->execute([$user_id, $task['reward'], "⚡ 自動挖礦發薪：{$task['title']}"]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "⚡ 任務核銷完成！入帳 {$task['reward']} ZOO！"]);

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