<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

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

try {
    if (!isset($_POST['booking_id'])) {
        throw new Exception('Booking ID is required');
    }

    $booking_id = intval($_POST['booking_id']);

    // Begin transaction
    $conn->begin_transaction();

    // First check if the booking exists
    $check_query = "SELECT booking_id FROM cargo_bookings WHERE booking_id = ?";
    $stmt = $conn->prepare($check_query);
    $stmt->bind_param("i", $booking_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Booking not found');
    }

    // Delete the booking
    $delete_query = "DELETE FROM cargo_bookings WHERE booking_id = ?";
    $stmt = $conn->prepare($delete_query);
    $stmt->bind_param("i", $booking_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete booking');
    }

    // Commit transaction
    $conn->commit();

    echo json_encode(['success' => true, 'message' => 'Booking deleted successfully']);

} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn && $conn->ping()) {
        $conn->rollback();
    }
    
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

// Close connections
if (isset($stmt)) {
    $stmt->close();
}
if (isset($conn)) {
    $conn->close();
}
?>