<?php
// Start or resume the PHP session
session_start();
include_once 'shikanisha.kts.php';

date_default_timezone_set('Africa/Nairobi');

$response = array(); // Initialize an array to store the response data

try {
    // Your existing code...
 $bookid = $_POST['bookid'];
    $phone = $_POST['phone'];
    $cname = $_POST['cname'];
    $idno = $_POST['idno'];
    $payamount = isset($_POST['payamount']) ? $_POST['payamount'] : 0; // Use a default value if not set
    $COutDate = date('Y-m-d H:i:s', strtotime($_POST['COutDate'])); // Convert to datetime format
    $paymethod = $_POST['paymethod'];
    $status = 'checked_in';
    $username = $_SESSION['user'];

    // Example query to get the room price based on the room_id from the booking
    $getRoomPriceQuery = "SELECT r.price, r.room_name, r.room_id FROM rooms r
                          INNER JOIN bookings b ON r.room_id = b.room_id
                          WHERE b.booking_id = ?";
    $stmt = $conn->prepare($getRoomPriceQuery);
    $stmt->bind_param("i", $bookid);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $roomPrice = $row['price'];
        $roomName = $row['room_name'];
        $roomId = $row['room_id'];
        $checkInDate = date('Y-m-d H:i:s'); // Current datetime
              $checkOutDate = date('Y-m-d H:i:s', strtotime($COutDate));


        // Check room availability
     $sql = "SELECT * FROM bookings 
        WHERE room_id = ? AND (
            (check_out_date >= ? AND check_out_date <= ?) AND
            (status = 'Booked' OR status = 'checked_in' )
        ) AND booking_id != ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("isss", $roomId, $checkInDate, $COutDate, $bookid);
$stmt->execute();
$result = $stmt->get_result();

        if ($result->num_rows > 0) {
            // Room is not available, handle accordingly
            $response['status'] = 'error';
            $response['message'] = 'Sorry, the selected room is not available during the selected dates.';
        } else {
           $checkOutDate = date('Y-m-d H:i:s', strtotime($COutDate));
$checkInDateTime = strtotime($checkInDate);
$checkOutDateTime = strtotime($checkOutDate);
            // Calculate the total based on the room price and number of days
            $checkInDate = strtotime($checkInDate);
    $days = ceil(($checkOutDateTime - $checkInDateTime) / (60 * 60 * 24));

            $total = $roomPrice * $days;

            // Insert the sale transaction
            $insertSaleTransactionQuery = "INSERT INTO transaction_receipts (phone_number, total, payment_method, seller_date, seller_name, amount_received, booking_id) VALUES (?, ?, ?, NOW(), ?, ?, ?)";
            $stmt = $conn->prepare($insertSaleTransactionQuery);
            $stmt->bind_param("sdssii", $phone, $total, $paymethod, $username, $payamount, $bookid);
            $stmt->execute();

            if ($stmt->affected_rows <= 0) {
                throw new Exception("Error inserting sale transaction: " . $stmt->error);
            }

            // Get the last inserted sale_transaction ID
            $stid = $stmt->insert_id;

            // Insert the sale payment details
            $insertSalePaymentQuery = "INSERT INTO payments (payment_method, trans_id, amount) VALUES (?, ?, ?)";
            $stmt = $conn->prepare($insertSalePaymentQuery);
            $stmt->bind_param("sdd", $paymethod, $stid, $payamount);
            $stmt->execute();

            if ($stmt->affected_rows <= 0) {
                throw new Exception("Error inserting Payment details: " . $stmt->error);
            }

            // Update the booking status
            $updateBookingStatusQuery = "UPDATE bookings SET status = ?, trans_id = ?, check_out_date = ?, check_in_date = NOW() WHERE booking_id = ?";
            $stmt = $conn->prepare($updateBookingStatusQuery);
            $stmt->bind_param("sisi", $status, $stid, $checkOutDate,  $bookid);
            $stmt->execute();

            if ($stmt->affected_rows <= 0) {
                throw new Exception("Room Already Checked in: " . $stmt->error);
            }

            // Insert sales details
            $sqlInsertItemSales = "INSERT INTO room_sales (trans_id, room_name, room_id, nod, room_price, subtotal) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sqlInsertItemSales);
            $stmt->bind_param("isiidd", $stid, $roomName, $roomId, $days, $roomPrice, $total);
            $stmt->execute();

            if ($stmt->affected_rows <= 0) {
                throw new Exception("Error inserting sales details: " . $stmt->error);
            }

            // Update session variables
            $_SESSION['transactionc'][] = ['total' => $total, 'book' => $bookid, 'balance' => $total - $payamount];
            $_SESSION['cartc'][] = ['name' => $roomName, 'qty' => $days, 'price' => $roomPrice, 'subtotal' => $total];

            // Populate the response array for success
            $response['status'] = 'success';
            $response['message'] = 'Check In Successful';
        }
    } else {
        throw new Exception("Error fetching room price: Room not found.");
    }
} catch (Exception $e) {
    // In case of an exception, populate the response array with an error message
    $response['status'] = 'error';
    $response['message'] = 'Check In Failed: ' . $e->getMessage();
}

// Send the JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>
