<?php
// api/admin_delete_task.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);
$admin_id = isset($input['admin_id']) ? intval($input['admin_id']) : 0;
$task_id = isset($input['task_id']) ? intval($input['task_id']) : 0;

try {
    $pdo->beginTransaction();

    // 1. 🛡️ 終極防護：驗證是否為天啟者 (LV.99)
    $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 creator_id, budget, title FROM tasks WHERE id = ? FOR UPDATE");
    $stmt->execute([$task_id]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$task) {
        throw new Exception("任務不存在或已被刪除");
    }

    // 3. 💰 經濟平衡：如果任務還有剩餘預算，退還給發布者
    if ($task['budget'] > 0 && $task['creator_id'] > 0) {
        // 退錢
        $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
        $stmt->execute([$task['budget'], $task['creator_id']]);
        
        // 寫入總帳 (REFUND)
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'REFUND', ?, ?)");
        $memo = "天啟者強制下架任務退款: " . $task['title'];
        $stmt->execute([$task['creator_id'], $task['budget'], $memo]);
    }

    // 4. ☠️ 抹除任務
    $stmt = $pdo->prepare("DELETE FROM tasks WHERE id = ?");
    $stmt->execute([$task_id]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "☠️ 任務已強制抹除！剩餘預算已退還給發布者。"]);

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