<?php
// 1. Database Connection
require_once '../../includes/config.php';

// 2. Set Header for JSON response
header('Content-Type: application/json');

try {
    // 3. Validate the ID from the GET request
    if (!isset($_GET['id']) || empty($_GET['id'])) {
        throw new Exception("Invalid request: No Section ID provided.");
    }

    $id = intval($_GET['id']);

    // 4. Check if the section exists before trying to delete
    $checkSql = "SELECT id FROM sections WHERE id = :id";
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([':id' => $id]);

    if (!$checkStmt->fetch()) {
        throw new Exception("Section not found.");
    }

    // 5. Execute Delete
    // We use a prepared statement to prevent SQL Injection
    $sql = "DELETE FROM sections WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute([':id' => $id]);

    // 6. Return Success Response
    if ($success) {
        echo json_encode([
            'status' => 'success',
            'message' => 'Section deleted successfully.'
        ]);
    } else {
        throw new Exception("Database error: Could not remove section.");
    }

} catch (Exception $e) {
    // 7. Return Error Response
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>