<?php
require_once __DIR__ . "/../auth/check-permission.php";
require_once __DIR__ . "/../services/db.php";

header("Content-Type: application/json");

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

// TEMP DEBUG: return payload directly so you can inspect it in DevTools
if (true) {
    echo json_encode([
        "debug" => true,
        "raw" => $raw,
        "decoded" => $data
    ]);
    exit;
}


// If missing fields, return full debug info to DevTools
if (!$data || !isset($data["project_id"], $data["task_id"])) {
    http_response_code(400);
    echo json_encode([
        "error" => true,
        "message" => "Missing project_id or task_id.",
        "received_raw" => $raw,
        "received_decoded" => $data
    ]);
    exit;
}

requireProjectRole($conn, $data["project_id"], ["owner", "member"]);

$sql = "DELETE FROM tasks WHERE id = ?";
$stmt = sqlsrv_query($conn, $sql, [$data["task_id"]]);

if ($stmt === false) {
    http_response_code(500);
    echo json_encode([
        "error" => true,
        "message" => "SQL DELETE failed.",
        "sqlsrv_errors" => sqlsrv_errors(),
        "received_raw" => $raw,
        "received_decoded" => $data
    ]);
    exit;
}

echo json_encode([
    "error" => false,
    "message" => "Task deleted successfully.",
    "received_raw" => $raw,
    "received_decoded" => $data
]);
