<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>

<style>

    /* Common table cell styling */
    #myTableAgent th, #myTableAgent td,
    #myTableRoom th, #myTableRoom td,
    #myTableGuest th, #myTableGuest td {
        text-align: left; /* Adjust to 'right' if needed */
    }

    /* Hover effect for table rows */
    #myTableAgent tbody tr:hover,
    #myTableRoom tbody tr:hover,
    #myTableGuest tbody tr:hover {
        background-color: #f1f1f1; /* Adjust hover color */
        cursor: pointer;
    }
</style>


<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Edit Return</h2>
                <!-- <button class="btn btn-outline-success" id="btnOpenReservationForm">New Reservation</button> -->
                <!-- <button class="btn btn-outline-success" id="btnOpenReservationListForm" style="display: none;">Reservation List</button> -->
            </div>
        </div>
    </div>
</div>


<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="card mb-3" id="newReservation">
                    <div class="card-body">
                        <form id="reservationForm">
                            <div class="row">
                                <div class="col-4">
                                    <div class="row">
                                        <div class="col-12">
                                            <div class="mb-3" >
                                                <label for="dateTime" class="form-label">Date Time</label>
                                                <input type="text" class="flatpickr flatpickr-input active form-control" id="dateTime" required>
                                            </div>
                                            <div class="mb-3" >
                                                <label for="reservationNo" class="form-label">Booking No.</label>
                                                <input type="text" class="form-control" id="reservationNo"  >
                                                <input type="text" class="form-control" id="reservationNoOld" hidden >
                                            </div>
                                            <div class="mb-3" hidden>
                                                <label for="folioNo" class="form-label"></label>
                                                <input type="text" class="form-control" id="folioNo"  >
                                            </div>
                                            <div class="">
                                                <label for="agentName" class="form-label">Driver Name</label>
                                                <div class="mb-3">
                                                    <select class="form-select" id="agentName" name="agentName" placeholder="Choose Driver">
                                                        <option value="" disabled selected>Select a driver</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="">
                                            <label for="guestName" class="form-label">Customer Name</label>
                                            <div class="input-group mb-3">
                                                <input type="hidden" class="form-control" id="guestId">
                                                <input type="text" class="form-control" id="guestName" placeholder="Enter customer name" disabled>
                                                <button class="btn btn-md" type="button" onclick="getGuestList()">...</button>
                                            </div>
                                            </div>
                                            <div class="row" hidden>
                                                <div class="col-6 mb-3">
                                                    <label for="extraBedInput" class="form-label">No. of Ex. Bed</label>
                                                    <input type="number" class="form-control" id="extraBedInput" name="extraBed" value="0" min="0" step="1" placeholder="Enter number of extra beds">
                                                </div>
                                                <div class="col-6 mb-3">
                                                    <label for="extraPersonInput" class="form-label">No. of Ex. Pax</label>
                                                    <input type="number" class="form-control" id="extraPersonInput" name="extraPerson" value="0" min="0" step="1" placeholder="Enter number of extra pax">
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-12  mb-3">
                                                    <label for="remark" class="form-label">Remark</label>
                                                    <textarea class="form-control" id="remark" name="remark" data-bs-toggle="autosize" style="overflow: hidden; overflow-wrap: break-word; resize: none;"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                </div>
             
                                <input type="hidden" class="form-control" id="roomType" disabled>
                                <input type="hidden" class="form-control" id="bedType" disabled>
                                <input type="hidden" class="form-control" id="roomRate" disabled>
                                <input type="hidden" class="form-control" id="extraBed" disabled>
                                <input type="hidden" class="form-control" id="extraPerson" disabled>

                                <div class="col-8">
                                    <div class="row">
                                        <div class="col-4">
                                            <div class="mb-3">
                                                <label for="checkInOutDate" class="form-label">Pickup & Return</label>
                                                <input class="form-control mb-3" id="checkInOutDate" disabled>
                                            </div>
                                        </div>
                                        <div class="col-1">
                                            <label for="" class="form-label">&nbsp;</label>
                                            <button class="btn btn-outline-primary" type="button" id="addDateButton">
                                                <span class="fs-4">+</span>
                                            </button>
                                        </div>
                                        <div class="col-3">
                                            <label for="roomNumber" class="form-label">Vehicle No.</label>
                                            <input type="text" class="form-control" id="roomNumber"  disabled>
                                        </div>
                                        <div class="col-4 row" hidden>
                                            <div class="col-md-6 col-sm-12 mb-3">
                                                <label for="adult" class="form-label"></label>
                                                <input type="number" class="form-control" id="adult" name="adult" value="1" required >
                                            </div>

                                            <div class="col-md-6 col-sm-12 mb-3">
                                                <label for="child" class="form-label"></label>
                                                <input type="number" class="form-control" id="child" name="child" value="0"  >
                                            </div>

                                            <!-- <div class="col-md-4 col-sm-12 mb-3">
                                                <label for="addGuest" class="form-label" style="visibility: hidden;">&nbsp;</label>
                                                <button type="button" id="btnGuestList" class="btn btn-outline-primary mb-3">Customer</button>
                                            </div> -->
                                        </div>
                                    </div>
                                    <div class="mb-3 table-responsive" style="min-height: 169px;background-color: #f0ebeb;">
                                        <table class="table table-vcenter card-table" id="stayDetailsTable">
                                            <thead style="position: sticky; top: 0; z-index: 10;">
                                                <tr>
                                                    <th>Date</th>
                                                    <!-- <th>Vehicle No.</th> -->
                                                    <th>Rental Rate</th>
                                                    <th>Add-on</th>
                                                    <th>Extra Driver</th>
                                                    <th>Total</th>
                                                    <th class="w-1">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody class="stay-grid">
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="">
                                        <div class="row mb-1">
                                            <div class="col-3 offset-9 mb-3">
                                                <label for="totalAmount" class="form-label">Total Amount</label>
                                                <input type="text" class="form-control" id="totalAmount" name="totalAmount" disabled>                                              
                                            </div>
                                            <div class="col-3 offset-9 text-end">
                                                <button type="button" id="btnSubmitReservation" class="btn btn-outline-success">Update Return</button>
                                            </div>
                                        </div>
                                        
                                        
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- <div class="text-end">
                    <button type="button" id="btnSubmitReservation" class="btn btn-outline-success">Reserve</button>
                </div> -->
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="guestModel" tabindex="-1" aria-labelledby="guestModelLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content">

            <div class="modal-body">
                <!-- Tab Navigation -->
                <ul class="nav nav-tabs" id="guestTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="existing-guest-tab" data-bs-toggle="tab" data-bs-target="#existing-guest" type="button" role="tab" aria-controls="existing-guest" aria-selected="true">
                            Existing Customer
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="new-guest-tab" data-bs-toggle="tab" data-bs-target="#new-guest" type="button" role="tab" aria-controls="new-guest" aria-selected="false">
                            New Customer
                        </button>
                    </li>
                </ul>

                <!-- Tab Content -->
                <div class="tab-content" id="guestTabsContent">
                    <!-- Existing Customer Tab -->
                    <div class="tab-pane fade show active" id="existing-guest" role="tabpanel" aria-labelledby="existing-guest-tab">
                        <div class="table-responsive mt-3">
                            <table id="myTableGuest" class="table card-table table-vcenter text-nowrap datatable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Phone</th>
                                        <th>Email</th>
                                        <th>ID No.</th>
                                        <th>Address</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Existing customer rows will be populated dynamically -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- New Customer Tab -->
                    <div class="tab-pane fade" id="new-guest" role="tabpanel" aria-labelledby="new-guest-tab">
                        <div class="row mt-3">
                            <div class="col-6 mb-3">
                                <label for="guestNameE" class="form-label">Name</label>
                                <input type="text" class="form-control" id="guestNameE" placeholder="Enter customer name" required>
                            </div>
                            <div class="col-6 mb-3">
                                <label for="contactNumberE" class="form-label">Phone</label>
                                <input type="tel" class="form-control" id="contactNumberE" placeholder="Enter contact number" required>
                            </div>
                            <div class="col-6 mb-3">
                                <label for="emailE" class="form-label">Email</label>
                                <input type="email" class="form-control" id="emailE" placeholder="Enter email">
                            </div>
                            <div class="col-6 mb-3">
                                <label for="ppNRCE" class="form-label">ID No.</label>
                                <input type="text" class="form-control" id="ppNRCE" placeholder="Enter passport/nrc">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 ">
                                <label for="addressE" class="form-label">Address</label>
                                <textarea class="form-control" id="addressE" placeholder="Enter address" style="resize: none;"></textarea>
                            </div>
                            <div class="col-12 mb-3 text-end">
                                <label for="" class="form-label">&nbsp;</label>
                                <button type="button" onclick="addGuest()" class="btn btn-outline-success">Add Customer</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal modal-blur fade" id="myModalRoomRate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Rental Rate</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3 row">
                        <label for="mtxtRoomRate" class="col-md-6 col-form-label text-end">Rental Rate:</label>
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="mtxtRoomRate" name="mtxtRoomRate" 
                                   onkeypress="return isNumber(event)" onkeyup="btozero(this);" 
                                   value="0" maxlength="11" style="text-align: right;">
                        </div>
                    </div>
                    <div class="text-end mt-3">
                        <button type="button" class="btn btn-success" onclick="updRate()">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal modal-blur fade" id="myModalExtraBedRate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add-on Rate</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3 row">
                        <label for="mtxtExtraBed" class="col-md-3 col-form-label text-end">Add-on:</label>
                        <div class="col-md-3">
                            <input id="mtxtExtraBed" name="ExtraBed" class="form-control" type="number" min="0" max="2"  value="0">
                        </div>
                        <label for="mtxtBedRate" class="col-md-2 col-form-label text-end">Rate:</label>
                        <div class="col-md-4">
                            <input id="mtxtBedRate" name="BedRate" class="form-control" type="text" maxlength="7" 
                                   onkeypress="return isNumber(event)" onkeyup="btozero(this);" value="0">
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-success" onclick="updBedRate()">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal modal-blur fade" id="myModalExtraPaxRate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Extra Driver Rate</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3 row">
                        <label for="mtxtExtraPax" class="col-md-3 col-form-label text-end">Extra Driver:</label>
                        <div class="col-md-3">
                            <input id="mtxtExtraPax" name="ExtraPax" class="form-control" type="number" min="0" max="2" 
                                   onchange="mextraPax()" onkeypress="return isNumber(event)" onkeyup="btozero(this);" value="0">
                        </div>
                        <label for="mtxtPaxRate" class="col-md-2 col-form-label text-end">Rate:</label>
                        <div class="col-md-4">
                            <input id="mtxtPaxRate" name="PaxRate" class="form-control" type="text" maxlength="7" 
                                   onkeypress="return isNumber(event)" onkeyup="btozero(this);" value="0">
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-success" onclick="updPaxRate()">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal modal-blur fade" id="passwordModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Enter Password</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <input type="password" class="form-control" id="passwordInput" placeholder="Enter your password">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="submitPassword">Submit</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

<?php include '../footer.php'; ?>

<script>
    const currentUrl = window.location.href;
    const url = new URL(currentUrl);
    const params = new URLSearchParams(url.search);
    const reservationNo_P = params.get('reservationNo');
    const roomNo_P = params.get('roomNo');

    $(document).ready(function() {
        getAgentList();
        getOneRoomReservation();

    });

    function getAgentList(){
        $.ajax({
            url: APP_URL + "api/agent/get_all_rows.php"
        }).done(function(data) {
            $("#agentName").find("option").remove();
            $("#agentName").append("<option value = '' data-id = ''>Select an agent</option>");
            $.each(data.records, function(i, v) {
                console.log(v);
                $("#agentName").append("<option value= '" + v.agent_name + "' data-id = '"+ v.id +"' data-commission = '"+ v.commission +"'>" + v.agent_name + "</option>");
            });
        });
    }

    function setAgentValueWithDelay(agentName, retries = 5) {
        if (retries <= 0) return;

        if ($("#agentName option[value='" + agentName + "']").length > 0) {
            $("#agentName").val(agentName);
        } else {
            setTimeout(function() {
                setAgentValueWithDelay(agentName, retries - 1);
            }, 100); // Retry after 100ms
        }
    }

    function getGuestList() {
    $('#guestModel').on('shown.bs.modal', function () {
        $('#myTableGuest_filter input').focus();
    });
    $('#guestModel').modal('show');

    table = $('#myTableGuest').DataTable({
        "destroy": true,
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "responsive": true,
        "lengthMenu": [5, 10, 50, 100],
        "pageLength": 5,
        "ajax": {
            "url": APP_URL + "api/guest/get_all_rows_datatable.php",
            "dataSrc": "records"
        },
        "columns": [
            { "title": "ID", "visible": false }, 
            { "title": "Name" },
            { "title": "Phone" },
            { "title": "Email" },
            { "title": "ID No." },
            { "title": "Address" },
        ],
        "order": [[0, "desc"]]
    });

    $('#myTableGuest').on('click', 'tbody td', function(e) {
        var rowData = table.row($(this).parents('tr')).data(); 
        $("#guestId").val(rowData[0]);        
        $("#guestName").val(rowData[1]);   
        $('#guestModel').modal('hide');
    });

}

    function getOneRoomReservation() {
        $.ajax({
            type: "POST",
            url: APP_URL + "api/reservation/get_one_room_reservation.php",
            data: JSON.stringify({ reservation_no: reservationNo_P, room_no: roomNo_P }),
            contentType: "application/json",
        }).done(function(data) {
            $("#dateTime").val(data.date_time);
            $("#reservationNo").val(data.reservation_no);
            $("#reservationNoOld").val(data.reservation_no);
            $("#folioNo").val(data.folio_no);
            setAgentValueWithDelay(data.agent_name);
            $("#guestId").val(data.guest_id);
            $("#guestName").val(data.guest_name);
            $("#roomNumber").val(data.room_no);
            $("#roomType").val(data.room_type);
            $("#bedType").val(data.bed_type);
            $("#adult").val(data.adult);
            $("#child").val(data.child);
            $("#remark").val(data.remark);

            $('#stayDetailsTable .stay-grid').empty();

            let totalSum = 0;

            $.each(data.reservation_items, function(i, v) {
                totalSum += v.total; // Add total for summation
                
                const today = new Date().toISOString().split('T')[0];

                // const isValidDate = v.date >= today;
                          const isValidDate = true;

                $('#stayDetailsTable .stay-grid').append(`
                    <tr data-date="${v.date}">
                        <td>${v.date}</td>

                        <td class="roomRate" 
                            ${isValidDate ? `onclick='getRoomRate(this)' style="background-color: #e1ece2;cursor: pointer;"` : ''}>
                            ${v.room_rate.toLocaleString()}
                        </td>
                        <td class="extraBedRate" 
                            ${isValidDate ? `onclick='getExtraBedRate(this)' style="background-color: #e1ece2;cursor: pointer;"` : ''}>
                            ${v.extra_bed} x ${v.extra_bed_rate}
                        </td>
                        <td class="extraPersonRate" 
                            ${isValidDate ? `onclick='getExtraPaxRate(this)' style="background-color: #e1ece2;cursor: pointer;"` : ''}>
                            ${v.extra_person} x ${v.extra_person_rate}
                        </td>
                        <td class="total">${v.total.toLocaleString()}</td>
                        <td>
                            <button type="button" class="btn btn-outline-danger btn-sm remove-btn" 
                                    onclick="removeStayRow(this)" 
                                    ${i === data.reservation_items.length - 1 ? '' : 'style="display:none;"'}>
                                Remove
                            </button>
                        </td>
                    </tr>
                `);
            });


            $("#totalAmount").val(totalSum.toLocaleString());
            updateCheckInOutDate();
        });
    }

    $('#addDateButton').on('click', function() {
        addNewStayRow();
    });

    function addNewStayRow() {
    // Get the last row's date (max date)
    const lastRow = $('#stayDetailsTable .stay-grid tr').last();
    const lastDate = lastRow.data('date');  // Get the date from the last row
    const lastRowData = {
        room_rate: lastRow.find('.roomRate').text(),
        extra_bed: lastRow.find('.extraBedRate').text(),
        extra_bed_rate: lastRow.find('.extraBedRate').text().split(' x ')[1],
        extra_person: lastRow.find('.extraPersonRate').text(),
        extra_person_rate: lastRow.find('.extraPersonRate').text().split(' x ')[1],
        total: lastRow.find('.total').text()
    };

    // Increment the last date by 1 day to get the next date
    const nextDate = new Date(lastDate);
    nextDate.setDate(nextDate.getDate() + 1);
    const formattedNextDate = nextDate.toISOString().split('T')[0];  // Format as yyyy-mm-dd

    // Append the new row
    $('#stayDetailsTable .stay-grid').append(`
        <tr data-date="${formattedNextDate}">
            <td>${formattedNextDate}</td>
            <td class="roomRate" style="background-color: #e1ece2; cursor: pointer;" onclick="getRoomRate(this)">
                ${lastRowData.room_rate}
            </td>
            <td class="extraBedRate" style="background-color: #e1ece2; cursor: pointer;" onclick="getExtraBedRate(this)">
                ${lastRowData.extra_bed}
            </td>
            <td class="extraPersonRate" style="background-color: #e1ece2; cursor: pointer;" onclick="getExtraPaxRate(this)">
                ${lastRowData.extra_person}
            </td>
            <td class="total">${lastRowData.total}</td>
            <td>
                <button type="button" class="btn btn-outline-danger btn-sm remove-btn" onclick="removeStayRow(this)">Remove</button>
            </td>
        </tr>
    `);

    // Call manageRemoveButtonVisibility to hide the remove button for the new max date
    manageRemoveButtonVisibility();
    updateCheckInOutDate();
    updateAllTotals();
}

    function removeStayRow(button) {
        const row = $(button).closest('tr');
        const dateToRemove = row.data('date'); // Get the date of the row
        const totalValue = parseFloat(row.find('.total').text().replace(/,/g, '')); // Get the total value of the row
        const currentTotal = parseFloat($("#totalAmount").val().replace(/,/g, '')); // Current total amount
        const newTotal = currentTotal - totalValue; // Calculate new total

        // Use SweetAlert2 for confirmation
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to remove the reservation for ${dateToRemove}.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, remove it!',
            cancelButtonText: 'No, cancel!'
        }).then((result) => {
            if (result.isConfirmed) {
                row.remove(); // Remove the row from the table
                $("#totalAmount").val(newTotal.toLocaleString()); // Update total amount in the UI
                updateCheckInOutDate();
            }
        });
    }

    function updateCheckInOutDate() {
        let minDate = null;
        let maxDate = null;

        // Iterate through remaining rows to find new min and max dates
        $('#stayDetailsTable .stay-grid tr').each(function() {
            const date = new Date($(this).data('date'));
            
            if (!minDate || date < minDate) {
                minDate = date;
            }
            if (!maxDate || date > maxDate) {
                maxDate = date;
            }
        });

        // Set the #checkInOutDate value to the range between min and max dates
        if (minDate && maxDate) {
            const formattedMinDate = minDate.toISOString().split('T')[0]; // Format as YYYY-MM-DD
            const formattedMaxDate = new Date(maxDate);
            formattedMaxDate.setDate(maxDate.getDate() + 1); // Increment max date by 1 day
            const formattedNewMaxDate = formattedMaxDate.toISOString().split('T')[0]; // Format as YYYY-MM-DD
            $("#checkInOutDate").val(`${formattedMinDate} to ${formattedNewMaxDate}`);
            manageRemoveButtonVisibility(maxDate);
        } else {
            $("#checkInOutDate").val(""); 
        }
    }

    function updateAllTotals() {
        let grandTotal = 0; // Initialize grand total

        // Iterate through each row in the stay details table
        $('#stayDetailsTable .stay-grid tr').each(function() {
            const roomRate = parseFloat($(this).find(".roomRate").text().replace(/,/g, '')) || 0;
            const extraBedCount = parseFloat($(this).find(".extraBedRate").text().split(' x ')[0]) || 0;
            const extraBedRate = parseFloat($(this).find(".extraBedRate").text().split(' x ')[1].replace(/,/g, '')) || 0;
            const extraPersonCount = parseFloat($(this).find(".extraPersonRate").text().split(' x ')[0]) || 0;
            const extraPersonRate = parseFloat($(this).find(".extraPersonRate").text().split(' x ')[1].replace(/,/g, '')) || 0;

            // Calculate total for the row
            const total = roomRate + (extraBedCount * extraBedRate) + (extraPersonCount * extraPersonRate);
            $(this).find(".total").text(total.toLocaleString()); // Update the total cell

            grandTotal += total; // Add to grand total
        });

        const finalTotal = grandTotal;

        // Update the display for the total amount
        $('#totalAmount').val(finalTotal.toLocaleString()); // Display in the totalAmount input field
    }

    function manageRemoveButtonVisibility() {
        let rows = $('#stayDetailsTable .stay-grid tr');
        let today = new Date().toISOString().split('T')[0];  // Get today's date in 'YYYY-MM-DD' format

        // If there are rows, find the row with the max date
        if (rows.length > 0) {
            // Sort rows by date in descending order to find the max date
            let maxDateRow = rows.sort(function(a, b) {
                return new Date($(b).data('date')) - new Date($(a).data('date')); // Sort descending by date
            }).first(); // Get the row with the max date (first in the sorted order)

            // Hide remove buttons for all rows
            rows.find('.remove-btn').hide();

            // Show remove button only for the max date row, and only if it's after today
            rows.each(function() {
                let rowDate = $(this).data('date');
                if (rowDate > today) { // Show remove button only for future dates
                    if ($(this).is(maxDateRow)) {
                        $(this).find('.remove-btn').show();
                    }
                }
            });
        }
    }




    function getRoomRate(obj){
        // checkPassword(function() {
            $("#myModalRoomRate").modal('show');
            $("#mtxtRoomRate").val($(obj).text().replace(/,/g, '').trim());
        // });
        OBJ = obj;
    }
    function updRate(){
		$("#myModalRoomRate").modal('hide');
		$(OBJ).text(parseFloat($("#mtxtRoomRate").val()).toLocaleString());
		var room_rate = extra_bed = extra_bed_rate = extra_person = extra_person_rate = amount = 0;
		extra_bed = parseFloat($(OBJ).next().text().split(" x ")[0]);
		extra_bed_rate = parseFloat($(OBJ).next().text().split(" x ")[1].replace(/,/g, ''));

		extra_person = parseFloat($(OBJ).next().next().text().split(" x ")[0]);
		extra_person_rate = parseFloat($(OBJ).next().next().text().split(" x ")[1].replace(/,/g, ''));
		room_rate = parseFloat($(OBJ).text().replace(/,/g, ''));
		amount = room_rate + (extra_bed * extra_bed_rate) + (extra_person * extra_person_rate);

		$(OBJ).next().next().next().text(amount.toLocaleString());
		updateAllTotals();
	}

    function getExtraBedRate(obj){
		
        // checkPassword(function() {
            $("#myModalExtraBedRate").modal('show');
            $("#mtxtExtraBed").val($(obj).text().split(" x ")[0].trim());
            $("#mtxtBedRate").val($(obj).text().split(" x ")[1].replace(/,/g, ''));
        // });
		OBJ = obj;
	}

	function updBedRate(){
		$("#myModalExtraBedRate").modal('hide');
		$(OBJ).text($("#mtxtExtraBed").val() + " x " + parseFloat($("#mtxtBedRate").val()).toLocaleString());
		var room_rate = extra_bed = extra_bed_rate = extra_person = extra_person_rate = amount = 0;
		extra_bed = parseFloat($("#mtxtExtraBed").val());
		extra_bed_rate = parseFloat($("#mtxtBedRate").val());

		extra_person = parseFloat($(OBJ).next().text().split(" x ")[0]);
		extra_person_rate = parseFloat($(OBJ).next().text().split(" x ")[1].replace(/,/g, ''));
		room_rate = parseFloat($(OBJ).prev().text().replace(/,/g, ''));
		amount = room_rate + (extra_bed * extra_bed_rate) + (extra_person * extra_person_rate);

		$(OBJ).next().next().text(amount.toLocaleString());
		updateAllTotals();
	}
	//End Extra Bed Update//

	//Start Extra Pax Update//
	function getExtraPaxRate(obj){
        // checkPassword(function() {
            $("#myModalExtraPaxRate").modal('show');
            $("#mtxtExtraPax").val($(obj).text().split(" x ")[0].trim());
            $("#mtxtPaxRate").val($(obj).text().split(" x ")[1].replace(/,/g, ''));
        // });
		OBJ = obj;
	}

	function updPaxRate(){
		$("#myModalExtraPaxRate").modal('hide');
		$(OBJ).text($("#mtxtExtraPax").val() + " x " + parseFloat($("#mtxtPaxRate").val()).toLocaleString());
		var room_rate = extra_bed = extra_bed_rate = extra_person = extra_person_rate = amount = 0;
		extra_bed = parseFloat($(OBJ).prev().text().split(" x ")[0]);
		extra_bed_rate = parseFloat($(OBJ).prev().text().split(" x ")[1].replace(/,/g, ''));

		extra_person = parseFloat($("#mtxtExtraPax").val());
		extra_person_rate = parseFloat($("#mtxtPaxRate").val());
		room_rate = parseFloat($(OBJ).prev().prev().text().replace(/,/g, ''));
		amount = room_rate + (extra_bed * extra_bed_rate) + (extra_person * extra_person_rate);

		$(OBJ).next().text(amount.toLocaleString());
		updateAllTotals();
	}

    let isPasswordCorrect = false;

    function checkPassword(callback) {
        if (!isPasswordCorrect) {
            const passwordModal = new bootstrap.Modal(document.getElementById('passwordModal'), {
                backdrop: 'static',
                keyboard: false
            });
            passwordModal.show();

            document.getElementById('submitPassword').onclick = function () {
                const password = document.getElementById('passwordInput').value;
                const correctPassword = "12345";

                if (password === correctPassword) {
                    isPasswordCorrect = true;
                    passwordModal.hide();
                    callback(); // Call the provided function after password validation
                } else {
                    alert("Incorrect password. Change not allowed."); // Use Tabler's alert components if required
                    document.getElementById('passwordInput').value = ""; // Clear the input field
                }
            };
        } else {
            callback(); // If password is already validated, proceed directly
        }
    }

    $('#btnSubmitReservation').click(function() {

        const reservationData = {
            date_time: $('#dateTime').val(),
            reservation_no: $('#reservationNo').val(),
            reservation_no_old: $('#reservationNoOld').val(),
            folio_no: $('#folioNo').val(),
            agent_id: $('#agentName option:selected').attr('data-id'),
            agent_name: $('#agentName').val(),
            guest_id: $('#guestId').val(),
            guest_name: $('#guestName').val(),
            remark: $('#remark').val(),
            adult: $('#adult').val(),
            child: $('#child').val(),
            room_no: $('#roomNumber').val(),
            room_type: $('#roomType').val(),
            bed_type: $('#bedType').val(),
            stayDetails: getStayDetails() 
        };

        console.log(reservationData); 

        $.ajax({
            type: "POST",
            url: APP_URL + "api/reservation/update.php",
            contentType: "application/json", 
            data: JSON.stringify(reservationData),
            success: function(response) {
                if (response.message === "created") {
                    $("#reservationForm")[0].reset();
                    $("#stayDetailsTable tbody").empty();
                        Swal.fire({
                        icon: 'success',
                        title: 'Updated',
                        text: 'Return has been successfully updated.',
                        timer: 2000,  // Set timer for 2 seconds (2000 milliseconds)
                        timerProgressBar: true,  // Optionally show progress bar
                        willClose: () => {
                            window.location.href = 'return_list.php';
                        }
                    });
                } else if (response.message === "updated") {
                    $("#reservationForm")[0].reset();
                    $("#stayDetailsTable tbody").empty();
                    showAlert("Return updated successfully!", "success");
                } else if (response.message === "duplicate") {
                    showAlert("Duplicate Return found!", "warning");
                } else {
                    showAlert("Error on server side!", "error");
                }
            },
            error: function() {
                showAlert("Error on server side!", "error");
            },
            complete: function() {
                $('#reservationModal').modal('hide'); 
            }
        });

    });

    function getStayDetails() {
        const stayDetails = [];
        $('#stayDetailsTable .stay-grid tr').each(function() {
            const row = $(this);
            const stayDetail = {
                date: row.find('td').eq(0).text(),                
                room_rate: parseFloat($(this).find("td").eq(1).text().replace(/,/g, '')),           
                extra_bed : $(this).find("td").eq(2).text().split(' x ')[0],
                extra_bed_rate : parseFloat($(this).find("td").eq(2).text().split(' x ')[1].replace(/,/g, '')),
                extra_person : $(this).find("td").eq(3).text().split(' x ')[0],
                extra_person_rate : parseFloat($(this).find("td").eq(3).text().split(' x ')[1].replace(/,/g, '')),            
            };
            stayDetails.push(stayDetail);
        });
        return stayDetails;
    }

    function showAlert(message, type) {
        Swal.fire({
            title: type === 'success' ? 'Success!' : 'Oops!',
            text: message,
            icon: type,
            // confirmButtonText: 'OK',
            timer: 1000, // Auto close after 3000 milliseconds (3 seconds)
            timerProgressBar: true, // Optional: Show a progress bar
            willClose: () => {
                // Optional: Execute code just before the alert closes
                console.log('Alert closed');
            }
        });
    }

</script>
