<?php
// claim_reward.php - 任務結算收銀台
// --------------------------------------------------
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$input = file_get_contents("php://input");
$data = json_decode($input, true);

if (!isset($data['user_id']) || !isset($data['task_id'])) {
    echo json_encode(["status" => "error", "message" => "資料不完整"]);
    exit;
}

$worker_id = $data['user_id'];
$task_id = $data['task_id'];

try {
    $pdo->beginTransaction(); // 開啟交易模式 (確保錢不會算錯)

    // 1. 鎖定任務資料
    $stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = :id AND status = 'active'");
    $stmt->execute([':id' => $task_id]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$task) {
        throw new Exception("任務已結束或不存在");
    }

    // 2. 檢查發布者餘額 (扣款)
    // 這裡簡化邏輯：假設系統已先凍結或發布者餘額無限 (示範用)
    // 在正式版應檢查 user_id = $task['user_id'] 的餘額

    // 3. 發放獎勵給執行者
    $stmt = $pdo->prepare("UPDATE users SET coins = coins + :reward WHERE id = :worker_id");
    $stmt->execute([':reward' => $task['reward'], ':worker_id' => $worker_id]);

    // 4. 記錄證物 (Proof) - 標記為自動完成
    $stmt = $pdo->prepare("INSERT INTO task_proofs (task_id, worker_id, proof_data, status) VALUES (:tid, :wid, 'AUTO_VIEW_20S', 'approved')");
    $stmt->execute([':tid' => $task_id, ':wid' => $worker_id]);

    $pdo->commit(); // 提交交易

    // 5. 回傳最新餘額
    $stmt = $pdo->prepare("SELECT coins FROM users WHERE id = :id");
    $stmt->execute([':id' => $worker_id]);
    $new_balance = $stmt->fetchColumn();

    echo json_encode([
        "status" => "success",
        "message" => "任務完成！獲得 " . $task['reward'] . " Z幣",
        "new_coins" => $new_balance
    ]);

} catch (Exception $e) {
    $pdo->rollBack(); // 發生錯誤，回溯交易
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>