<?php
// delete_hostel_process.php - Handles deleting a hostel from the database

require_once 'config.php'; // Include database configuration
header('Content-Type: application/json'); // Set header to return JSON response

// Check if the request method is POST and if hostel_id is provided
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw POST data (JSON sent from fetch API)
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $hostelId = filter_var($data['hostel_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);

    // Server-side validation
    if (empty($hostelId)) {
        echo json_encode(['success' => false, 'message' => 'Hostel ID is required for deletion.']);
        exit;
    }

    // Prepare a DELETE SQL statement
    // Using prepared statements is crucial for security
    $sql = "DELETE FROM hostels WHERE hostel_id = :hostel_id";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':hostel_id', $hostelId, PDO::PARAM_INT);

        if ($stmt->execute()) {
            // Check if any rows were actually affected by the deletion
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Hostel deleted successfully!']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Hostel not found or already deleted.']);
            }
        } else {
            // This case is less common with PDO, but handles generic execution failures
            echo json_encode(['success' => false, 'message' => 'Failed to delete hostel. Please try again.']);
        }
    } catch (PDOException $e) {
        // Catch PDO exceptions (e.g., foreign key constraints if other tables depend on hostels)
        error_log("Database error deleting hostel: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'A database error occurred during deletion. It might be linked to other records.']);
    }
} else {
    // If the request method is not POST, deny access
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
