<?php
session_start();
include_once 'shikanisha.kts.php';

date_default_timezone_set('Africa/Nairobi');

$roomId = $_POST['roomId'];
$checkInDate = date("Y-m-d H:i:s", strtotime($_POST['checkInDate']));
$checkOutDate = date("Y-m-d H:i:s", strtotime($_POST['checkOutDate']));
$guest = $_POST['guestName'];
$username = $_SESSION['user'];
$status = 'Booked';

// Initialize response array
$response = array();

// Check if room is available during selected dates
$sqlAvailability = "SELECT * FROM bookings WHERE room_id = ? AND 
        NOT (check_out_date <= ? OR check_in_date >= ?)";

$stmtAvailability = $conn->prepare($sqlAvailability);
$stmtAvailability->bind_param("iss", $roomId, $checkInDate, $checkOutDate);
$stmtAvailability->execute();
$resultAvailability = $stmtAvailability->get_result();

if ($resultAvailability->num_rows > 0) {
    // Room is not available, set error message in response
    $response['status'] = 'error';
    $response['message'] = 'Sorry, the selected room is not available during the selected dates.';
} else {
    // Room is available, book the room
    $stmtAvailability->close();

    $sqlBooking = "INSERT INTO bookings (room_id, user_name, guest, check_in_date, check_out_date, status) 
            VALUES (?, ?, ?, ?, ?, ?)";
    
    $stmtBooking = $conn->prepare($sqlBooking);
    $stmtBooking->bind_param("isssss", $roomId, $username, $guest, $checkInDate, $checkOutDate, $status);

    if ($stmtBooking->execute()) {
        // Booking successful, set success message in response
        $response['status'] = 'success';
        $response['message'] = 'Room booked successfully!';
    } else {
        // Booking failed, set error message in response
        $response['status'] = 'error';
        $response['message'] = 'Error during booking: ' . $stmtBooking->error;
    }

    $stmtBooking->close();
    $conn->close();
}

// Encode the response array as JSON and echo it
echo json_encode($response);
?>
