<?php
include_once 'model/bookings_model.php';
$bookings_model = new bookings_model();

if (isset($_POST['booking_id']) && isset($_POST['action'])) {
    $bookingId = $_POST['booking_id'];
    $action = $_POST['action'];

    // Validate action
    if ($action !== 'confirm' && $action !== 'cancel') {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit();
    }

    // Perform action based on the booking status
    $newStatus = ($action === 'confirm') ? 2 : 0;
    
    try {
        // Attempt to update the booking status
        $confirm_booking = $bookings_model->updateBookingState($bookingId, $newStatus);

        if ($confirm_booking) {
            echo json_encode(['success' => true, 'message' => ucfirst($action) . 'ed successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update booking status']);
        }
    } catch (Exception $e) {
        // Catch any errors from the model and provide a detailed message
        error_log("Error updating booking status: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'An error occurred while updating the booking status']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>
