<?php
// api/auto_claim.php - 互動區自動領賞 (會計室精準扣款版)
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 = isset($input['user_id']) ? intval($input['user_id']) : 0;
$task_id = isset($input['task_id']) ? intval($input['task_id']) : 0;

if ($user_id <= 0 || $task_id <= 0) {
    echo json_encode(["status" => "error", "message" => "參數遺失，請重新操作"]); exit;
}

try {
    $pdo->beginTransaction();

    // 1. 鎖定任務，檢查預算
    $stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = ? FOR UPDATE");
    $stmt->execute([$task_id]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$task) throw new Exception("任務不存在");

    // 🦁 關鍵修復：還原總成本。原本 reward 是扣除 25% 的，所以原本的預算消耗 = reward / 0.75
    $gross_cost = round($task['reward'] / 0.75);
    if ($gross_cost <= 0) $gross_cost = $task['reward'];

    if ($task['budget'] < $gross_cost) {
        // 如果剩下的錢不夠付總成本，但還夠付給飼育員，就梭哈扣光
        if ($task['budget'] >= $task['reward']) {
            $gross_cost = $task['budget']; 
        } else {
            throw new Exception("啊歐！這隻動物已經被其他飼育員餵飽囉！");
        }
    }

    // 2. 檢查是否已經照顧過
    $stmt = $pdo->prepare("SELECT id FROM task_submissions WHERE user_id = ? AND task_id = ?");
    $stmt->execute([$user_id, $task_id]);
    if ($stmt->rowCount() > 0) throw new Exception("您已經照顧過這隻動物，不能重複領獎喔！");

    // 3. 寫入照顧紀錄
    $stmt = $pdo->prepare("INSERT INTO task_submissions (task_id, user_id, status, created_at) VALUES (?, ?, 'approved', NOW())");
    $stmt->execute([$task_id, $user_id]);

    // 4. 正確扣除總預算 (包含稅金)
    $stmt = $pdo->prepare("UPDATE tasks SET budget = budget - ? WHERE id = ?");
    $stmt->execute([$gross_cost, $task_id]);

    // 5. 發放 ZOO 幣給飼育員
    $reward = intval($task['reward']);
    $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
    $stmt->execute([$reward, $user_id]);

    // 6. 記帳
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'REWARD', ?, ?)");
    $stmt->execute([$user_id, $reward, "完成照顧任務: " . $task['title']]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "太棒了！獲得 {$reward} 顆胡蘿蔔 🥕！"]);

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