<?php
session_start();

// Check if the user is authorized to update the booking
if (isset($_SESSION['type']) && ($_SESSION['type'] == 'Manager' || $_SESSION['type'] == 'Receptionist')) {
    // Check if the booking id is provided in the POST data
    if (isset($_POST['booking_id'])) {
        $booking_id = $_POST['booking_id'];
        $timezone = new DateTimeZone('Africa/Nairobi');
        $date = (new DateTime('now', $timezone))->format('Y-m-d H:i:s');
        $status = 'checked_out';

        // Retrieve booking details including total debt, total payments, and balance
        include_once 'shikanisha.kts.php';

        $sql = "SELECT
            b.`booking_id`,
            r.`room_name`,
            COALESCE(total_debt.total_debt, 0) AS `total_debt`,
            COALESCE(total_payments.total_payments, 0) AS `total_payments`
        FROM
            `bookings` b
        JOIN
            `rooms` r ON b.`room_id` = r.`room_id`
        LEFT JOIN (
            SELECT
                rb.`booking_id`,
                SUM(rb.`amount`) AS `total_debt`
            FROM
                `room_bills` rb
            GROUP BY
                rb.`booking_id`
        ) AS total_debt ON b.`booking_id` = total_debt.`booking_id`
        LEFT JOIN (
            SELECT
                rp.`booking_id`,
                SUM(rp.`paid_amount`) AS `total_payments`
            FROM
                `room_payments` rp
            GROUP BY
                rp.`booking_id`
        ) AS total_payments ON b.`booking_id` = total_payments.`booking_id`
        WHERE
            b.`booking_id` = $booking_id";

        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            $data = $result->fetch_assoc();

            // Assuming you have a variable $data with the required information
            // Check if the balance is 0
            if (($data['total_debt'] - $data['total_payments']) == 0) {
                // Proceed with checkout
                $stmt = $conn->prepare("UPDATE bookings SET check_out_date=?, status=? WHERE booking_id = ?");
                if (!$stmt) {
                    die('Error preparing statement: ' . $conn->error);
                }

                // Bind parameters and execute the statement
                $stmt->bind_param('ssi', $date, $status, $booking_id);
                if ($stmt->execute()) {
                    // Respond with success
                    echo json_encode(['status' => 'success', 'message' => 'Check Out successful.']);
                } else {
                    // Respond with an error
                    echo json_encode(['status' => 'error', 'message' => 'Error updating booking: ' . $stmt->error]);
                }

                // Close the statement
                $stmt->close();
                // Close the connection
                $conn->close();
            } else {
                // Respond with an error if there is an existing balance
                echo json_encode(['status' => 'error', 'message' => 'Client has an existing balance. Cannot proceed with checkout.']);
            }
        } else {
            // Respond with an error if no booking details found
            echo json_encode(['status' => 'error', 'message' => 'No booking details found.']);
        }
    } else {
        // Respond with an error if booking_id is not provided in POST data
        echo json_encode(['status' => 'error', 'message' => 'Booking id not provided.']);
    }
} else {
    // Respond with an error for unauthorized access
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized access.']);
}
?>
