<?php
// mflowzoo/api/admin_tasks_action.php - 手機版天啟退款引擎 (V3.1 完美解卡版同步)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        $sql = "SELECT t.*, u.username as creator_name 
                FROM tasks t 
                LEFT JOIN users u ON t.creator_id = u.id 
                ORDER BY t.budget DESC, t.id DESC";
        $stmt = $pdo->query($sql);
        $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(["status" => "success", "data" => $tasks]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
    exit;
}

if ($method === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    $admin_id = $input['admin_id'] ?? 0;
    $task_id = $input['task_id'] ?? 0;

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

    try {
        $pdo->beginTransaction();

        // 1. 驗證權限
        $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        if ($stmt->fetchColumn() < 99) throw new Exception("天啟禁區，權限不足！");

        // 2. 鎖定任務
        $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("找不到該任務！");
        
        $budget = (int)$task['budget'];
        $creator_id = $task['creator_id'];

        // ✨ 只要還有預算，就絕對允許退款 (無視 is_active)
        if ($task['is_active'] == 0 && $budget <= 0) {
            throw new Exception("此任務已經被徹底下架且結清，無法重複操作！");
        }

        // 3. 邏輯下架並歸零
        $stmt = $pdo->prepare("UPDATE tasks SET is_active = 0, budget = 0 WHERE id = ?");
        $stmt->execute([$task_id]);

        // 4. 強制退款
        if ($budget > 0) {
            $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
            $stmt->execute([$budget, $creator_id]);

            $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'REFUND', ?, ?)");
            $stmt->execute([$creator_id, $budget, "⚠️ 天啟者行動版強制下架退款：{$task['title']}"]);
        }

        $pdo->commit();
        
        if ($budget > 0) {
            echo json_encode(["status" => "success", "message" => "🌪️ 任務解卡成功！已將剩餘預算 {$budget} ZOO 退還。"]);
        } else {
            echo json_encode(["status" => "success", "message" => "🗑️ 任務屍體已徹底隱藏清理！"]);
        }

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