<?php
header("Content-Type: application/json");
require_once __DIR__ . "/../auth/require-auth.php";
require_once __DIR__ . "/../services/db.php";

$conn = db();

if (!$conn) {
    http_response_code(500);
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);
$sectionId = isset($data['section_id']) ? (int)$data['section_id'] : (isset($data['id']) ? (int)$data['id'] : null);

if (!$sectionId) {
    http_response_code(400);
    echo json_encode([
        "error" => "Missing parameter",
        "message" => "section_id is required."
    ]);
    exit;
}

// 1. Delete associated tasks first (or nullify their section_id)
sqlsrv_query($conn, "DELETE FROM tasks WHERE section_id = ?", [$sectionId]);

// 2. Delete the section
$sql = "DELETE FROM sections WHERE id = ?";
$stmt = sqlsrv_query($conn, $sql, [$sectionId]);

if ($stmt === false) {
    http_response_code(500);
    echo json_encode([
        "error" => "SQL DELETE failed",
        "details" => sqlsrv_errors()
    ]);
    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Section deleted successfully.",
    "section_id" => $sectionId
]);