<?php
// Start or resume the PHP session
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 = 'checked_in';

// check if room is available during selected dates
$sql = "SELECT * FROM bookings WHERE room_id = '$roomId' AND ((check_in_date <= '$checkInDate' AND check_out_date >= '$checkInDate') OR (check_in_date <= '$checkOutDate' AND check_out_date >= '$checkOutDate'))";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // room is not available, return error message
    echo "Sorry, the selected room is not available during the selected dates.";
} else {
    // room is available, book the room
   
    $sql = "INSERT INTO bookings (room_id, user_name, guest, check_in_date, check_out_date, status) 
            VALUES ('$roomId', '$username', '$guest', '$checkInDate', '$checkOutDate','$status')";
    if ($conn->query($sql) === TRUE) {
        // booking successful, retrieve the order details and store them in the cart and total session variables
        $sql = "SELECT room_id, room_name, price FROM rooms WHERE room_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $roomId);
        $stmt->execute();
        $result = $stmt->get_result();
        $order_details = array();
        while ($row = $result->fetch_assoc()) {
            $order_details[] = array(
                'id'    =>  $row['room_id'],
                'name'  =>  $row['room_name'] . ' room',
                'price' =>  $row['price'],
                'qty'   =>  1
            );
        }
        $_SESSION['cart'] = $order_details;

        $stmt->close();

        $sql = "SELECT `price` FROM `rooms` WHERE `room_id` = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $roomId);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $_SESSION['total'] = $row['price'];
             $response = "Room successfully booked.";
        } else {
            echo "Could not retrieve order details";
            header("Location: ../accommodation.php");
            exit;
        }
        $stmt->close();

        $conn->close();
        echo $response;
      
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>
