<?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;
    }

    #newReservation.booking-card {
        border: 1px solid #d7e3ee;
        border-top: 4px solid #f59f00;
        box-shadow: 0 10px 28px rgba(31, 78, 121, 0.08);
    }

    .booking-panel {
        border-radius: 8px;
        padding: 18px;
        min-height: 100%;
    }

    .booking-panel-details {
        background: #f1f6fb;
        border: 1px solid #dbe8f3;
    }

    .booking-panel-rental {
        background: #fff8eb;
        border: 1px solid #f5dfb8;
    }

    .booking-panel-title {
        color: #1f4e79;
        font-size: 0.86rem;
        font-weight: 700;
        margin-bottom: 14px;
        text-transform: uppercase;
    }

    #newReservation .form-label {
        color: #153957;
        font-weight: 650;
    }

    #newReservation .form-control:focus,
    #newReservation .form-select:focus {
        border-color: #1f4e79;
        box-shadow: 0 0 0 0.18rem rgba(31, 78, 121, 0.16);
    }

    .booking-rate-table {
        min-height: 184px;
        background: #fffdf8;
        border: 1px solid #f2d79e;
        border-radius: 8px;
        overflow: hidden;
    }

    .booking-rate-table thead {
        position: sticky;
        top: 0;
        z-index: 10;
        background: #1f4e79;
        color: #fff;
    }

    .booking-total-panel {
        background: #eef5fb;
        border: 1px solid #d5e4f0;
        border-radius: 8px;
        padding: 14px;
    }

    #btnSubmitReservation {
        background: #1f4e79;
        border-color: #1f4e79;
        color: #fff;
    }

    #btnSubmitReservation:hover {
        background: #153957;
        border-color: #153957;
    }
</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">Booking</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 booking-card" id="newReservation">
                    <div class="card-body">
                        <form id="reservationForm">
                            <div class="row">
                                <div class="col-4">
                                    <div class="booking-panel booking-panel-details">
                                    <div class="booking-panel-title">Booking Details</div>
                                    <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" readonly>
                                            </div>
                                            <div class="mb-3" >
                                                <label for="invoiceNo" class="form-label">Invoice No.</label>
                                                <input type="text" class="form-control" id="invoiceNo" placeholder="Enter invoice number">
                                            </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="Select customer" 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">Add-on Qty</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">Extra Driver</label>
                                                    <input type="number" class="form-control" id="extraPersonInput" name="extraPerson" value="0" min="0" step="1" placeholder="Enter extra driver count">
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-12 mb-3">
                                                    <label for="pickupLocation" class="form-label">Pickup Location</label>
                                                    <input type="text" class="form-control" id="pickupLocation" placeholder="Enter pickup location">
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <label for="returnLocation" class="form-label">Return Location</label>
                                                    <input type="text" class="form-control" id="returnLocation" placeholder="Enter return location">
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-12 mb-3">
                                                    <label for="rentalPurpose" class="form-label">Rental Purpose</label>
                                                    <input type="text" class="form-control" id="rentalPurpose" placeholder="Business, airport transfer, leisure...">
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-12  mb-3">
                                                    <label for="remark" class="form-label">Booking Note</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>
                                    
                                </div>
             
                                <div class="col-8">
                                    <div class="booking-panel booking-panel-rental">
                                    <div class="booking-panel-title">Rental Schedule</div>
                                    <div class="row">
                                        <div class="col-md-2 col-sm-12">
                                            <div class="mb-3">
                                                <label for="rentalMode" class="form-label">Rental Mode</label>
                                                <select class="form-select" id="rentalMode">
                                                    <option value="daily" selected>Daily</option>
                                                    <option value="hourly">Hourly</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-7 col-sm-12" id="dailyPeriodWrap">
                                            <div class="mb-3">
                                                <label for="checkInOutDate" class="form-label">Pickup & Return</label>
                                                <input class="form-control mb-3" placeholder="Select a date" id="checkInOutDate">
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-sm-12 d-none" id="hourlyDateWrap">
                                            <div class="mb-3">
                                                <label for="pickupDate" class="form-label">Pickup Date</label>
                                                <input class="form-control mb-3" placeholder="Select pickup date" id="pickupDate">
                                            </div>
                                        </div>
                                        <div class="col-md-2 col-sm-6 d-none" id="pickupTimeWrap">
                                            <div class="mb-3">
                                                <label for="pickupTime" class="form-label">Pickup Time</label>
                                                <input type="time" class="form-control mb-3" id="pickupTime" value="09:00">
                                            </div>
                                        </div>
                                        <div class="col-md-2 col-sm-6 d-none" id="returnTimeWrap">
                                            <div class="mb-3">
                                                <label for="returnTime" class="form-label">Return Time</label>
                                                <input type="time" class="form-control mb-3" id="returnTime" value="12:00">
                                            </div>
                                        </div>
                                        <div class="col-md-3 col-sm-12" id="vehicleScheduleCol">
                                            <label for="roomNumber" class="form-label">Vehicle No.</label>
                                            <div class="input-group mb-3">
                                                <input type="hidden" class="form-control" id="roomId" disabled>
                                                <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>
                                                <input type="text" class="form-control" id="roomNumber" placeholder="Enter vehicle number" disabled>
                                                <button class="btn btn-md" type="button" onclick="getRoomList()">...</button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="rentalDescription" class="form-label">Description</label>
                                        <textarea class="form-control" id="rentalDescription" rows="3" placeholder="Enter rental description"></textarea>
                                    </div>
                                    <div class="mb-3 table-responsive booking-rate-table">
                                        <table class="table table-vcenter card-table" id="stayDetailsTable">
                                            <thead>
                                                <tr>
                                                    <th>Period</th>
                                                    <th>Description</th>
                                                    <th>Rate</th>
                                                    <th>Add-on Qty</th>
                                                    <th>Extra Driver</th>
                                                    <th>Total</th>
                                                </tr>
                                            </thead>
                                            <tbody class="stay-grid">
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="booking-total-panel">
                                        <div class="row mb-1">
                                            <div class="col-3 offset-3 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 mb-3">
                                                <label for="discountAmount" class="form-label">Discount Amount</label>
                                                <input type="text" class="form-control text-end" id="discountAmount" name="discountAmount" value="0">
                                            </div>
                                            <div class="col-3 mb-3">
                                                <label for="netAmount" class="form-label">Net Amount</label>
                                                <input type="text" class="form-control" id="netAmount" name="netAmount" disabled>
                                            </div>
                                            <div class="col-3 offset-9 text-end">
                                                <button type="button" id="btnSubmitReservation" class="btn btn-outline-success">Create Booking</button>
                                            </div>
                                            <!-- <div class="col-3 offset-9" hidden>
                                                <select class="form-select" id="status" required>
                                                    <option value="reserve" selected>Reserve</option>
                                                    <option value="confirm">Confirm</option>
                                                </select>
                                            </div>  -->
                                        </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 Guest 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>License / ID</th>
                                        <th>Address</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Existing guest rows will be populated dynamically -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- New Guest Tab -->
                    <div class="tab-pane fade" id="new-guest" role="tabpanel" aria-labelledby="new-guest-tab">
                        <div class="row mt-3">
                            <div class="col-4 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-4 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-4 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-4 mb-3">
                                <label for="country" class="form-label">Country</label>
                                <input list="countryList" class="form-control" id="country" placeholder="Enter country" required>
                                <datalist id="countryList">
                                    <option value="Afghanistan">
                                    <option value="Albania">
                                    <option value="Algeria">
                                    <option value="Andorra">
                                    <option value="Angola">
                                    <option value="Argentina">
                                    <option value="Armenia">
                                    <option value="Australia">
                                    <option value="Austria">
                                    <option value="Azerbaijan">
                                    <option value="Bahamas">
                                    <option value="Bahrain">
                                    <option value="Bangladesh">
                                    <option value="Barbados">
                                    <option value="Belarus">
                                    <option value="Belgium">
                                    <option value="Belize">
                                    <option value="Benin">
                                    <option value="Bhutan">
                                    <option value="Bolivia">
                                    <option value="Bosnia and Herzegovina">
                                    <option value="Botswana">
                                    <option value="Brazil">
                                    <option value="Brunei">
                                    <option value="Bulgaria">
                                    <option value="Burkina Faso">
                                    <option value="Burundi">
                                    <option value="Cabo Verde">
                                    <option value="Cambodia">
                                    <option value="Cameroon">
                                    <option value="Canada">
                                    <option value="Central African Republic">
                                    <option value="Chad">
                                    <option value="Chile">
                                    <option value="China">
                                    <option value="Colombia">
                                    <option value="Comoros">
                                    <option value="Congo (Congo-Brazzaville)">
                                    <option value="Congo (Congo-Kinshasa)">
                                    <option value="Costa Rica">
                                    <option value="Croatia">
                                    <option value="Cuba">
                                    <option value="Cyprus">
                                    <option value="Czechia (Czech Republic)">
                                    <option value="Denmark">
                                    <option value="Djibouti">
                                    <option value="Dominica">
                                    <option value="Dominican Republic">
                                    <option value="Ecuador">
                                    <option value="Egypt">
                                    <option value="El Salvador">
                                    <option value="Equatorial Guinea">
                                    <option value="Eritrea">
                                    <option value="Estonia">
                                    <option value="Eswatini (fmr. Swaziland)">
                                    <option value="Ethiopia">
                                    <option value="Fiji">
                                    <option value="Finland">
                                    <option value="France">
                                    <option value="Gabon">
                                    <option value="Gambia">
                                    <option value="Georgia">
                                    <option value="Germany">
                                    <option value="Ghana">
                                    <option value="Greece">
                                    <option value="Grenada">
                                    <option value="Guatemala">
                                    <option value="Guinea">
                                    <option value="Guinea-Bissau">
                                    <option value="Guyana">
                                    <option value="Haiti">
                                    <option value="Honduras">
                                    <option value="Hungary">
                                    <option value="Iceland">
                                    <option value="India">
                                    <option value="Indonesia">
                                    <option value="Iran">
                                    <option value="Iraq">
                                    <option value="Ireland">
                                    <option value="Israel">
                                    <option value="Italy">
                                    <option value="Jamaica">
                                    <option value="Japan">
                                    <option value="Jordan">
                                    <option value="Kazakhstan">
                                    <option value="Kenya">
                                    <option value="Kiribati">
                                    <option value="Korea (North)">
                                    <option value="Korea (South)">
                                    <option value="Kuwait">
                                    <option value="Kyrgyzstan">
                                    <option value="Laos">
                                    <option value="Latvia">
                                    <option value="Lebanon">
                                    <option value="Lesotho">
                                    <option value="Liberia">
                                    <option value="Libya">
                                    <option value="Liechtenstein">
                                    <option value="Lithuania">
                                    <option value="Luxembourg">
                                    <option value="Madagascar">
                                    <option value="Malawi">
                                    <option value="Malaysia">
                                    <option value="Maldives">
                                    <option value="Mali">
                                    <option value="Malta">
                                    <option value="Marshall Islands">
                                    <option value="Mauritania">
                                    <option value="Mauritius">
                                    <option value="Mexico">
                                    <option value="Micronesia">
                                    <option value="Moldova">
                                    <option value="Monaco">
                                    <option value="Mongolia">
                                    <option value="Montenegro">
                                    <option value="Morocco">
                                    <option value="Mozambique">
                                    <option value="Myanmar">
                                    <option value="Namibia">
                                    <option value="Nauru">
                                    <option value="Nepal">
                                    <option value="Netherlands">
                                    <option value="New Zealand">
                                    <option value="Nicaragua">
                                    <option value="Niger">
                                    <option value="Nigeria">
                                    <option value="North Macedonia (formerly Macedonia)">
                                    <option value="Norway">
                                    <option value="Oman">
                                    <option value="Pakistan">
                                    <option value="Palau">
                                    <option value="Panama">
                                    <option value="Papua New Guinea">
                                    <option value="Paraguay">
                                    <option value="Peru">
                                    <option value="Philippines">
                                    <option value="Poland">
                                    <option value="Portugal">
                                    <option value="Qatar">
                                    <option value="Romania">
                                    <option value="Russia">
                                    <option value="Rwanda">
                                    <option value="Saint Kitts and Nevis">
                                    <option value="Saint Lucia">
                                    <option value="Saint Vincent and the Grenadines">
                                    <option value="Samoa">
                                    <option value="San Marino">
                                    <option value="Sao Tome and Principe">
                                    <option value="Saudi Arabia">
                                    <option value="Senegal">
                                    <option value="Serbia">
                                    <option value="Seychelles">
                                    <option value="Sierra Leone">
                                    <option value="Singapore">
                                    <option value="Slovakia">
                                    <option value="Slovenia">
                                    <option value="Solomon Islands">
                                    <option value="Somalia">
                                    <option value="South Africa">
                                    <option value="South Sudan">
                                    <option value="Spain">
                                    <option value="Sri Lanka">
                                    <option value="Sudan">
                                    <option value="Suriname">
                                    <option value="Sweden">
                                    <option value="Switzerland">
                                    <option value="Syria">
                                    <option value="Taiwan">
                                    <option value="Tajikistan">
                                    <option value="Tanzania">
                                    <option value="Thailand">
                                    <option value="Timor-Leste">
                                    <option value="Togo">
                                    <option value="Tonga">
                                    <option value="Trinidad and Tobago">
                                    <option value="Tunisia">
                                    <option value="Turkey">
                                    <option value="Turkmenistan">
                                    <option value="Tuvalu">
                                    <option value="Uganda">
                                    <option value="Ukraine">
                                    <option value="United Arab Emirates">
                                    <option value="United Kingdom">
                                    <option value="United States of America">
                                    <option value="Uruguay">
                                    <option value="Uzbekistan">
                                    <option value="Vanuatu">
                                    <option value="Vatican City">
                                    <option value="Venezuela">
                                    <option value="Vietnam">
                                    <option value="Yemen">
                                    <option value="Zambia">
                                    <option value="Zimbabwe">
                                </datalist>
                            </div>

                            <div class="col-4 mb-3">
                                <label for="documentTypeE" class="form-label">Document Type</label>
                                <select class="form-select" id="documentTypeE">
                                    <option value="Driving License">Driving License</option>
                                    <option value="Passport">Passport</option>
                                    <option value="National ID">National ID</option>
                                </select>
                            </div>
                            <div class="col-4 mb-3">
                                <label for="ppNRCE" class="form-label">License / ID No.</label>
                                <input type="text" class="form-control" id="ppNRCE" placeholder="Enter driving license or ID no.">
                            </div>
                            <div class="col-4 mb-3">
                                <label for="licenseExpiryE" class="form-label">License Expiry</label>
                                <input type="date" class="form-control" id="licenseExpiryE">
                            </div>
                            <div class="col-4 mb-3">
                                <label for="photoUpload" class="form-label">Upload Photo</label>
                                <input type="file" class="form-control" id="photoUpload" accept="image/*">
                            </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 fade" id="roomModel" tabindex="-1" aria-labelledby="roomModelLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="roomModelLabel">Vehicle List</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="myTableRoom" class="table card-table table-vcenter text-nowrap datatable" >
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th class="w-1">Vehicle No.</th>
                                    <th>Current Plan</th>
                                    <th>Vehicle Category</th>
                                    <th>Transmission</th>
                                    <th>Seats</th>
                                    <th>Rental Rate</th>
                                    <th>Add-on Qty/Rate</th>
                                    <th>Extra Driver/Rate</th>
                                    <th>Vehicle Details</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </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="myModalDescription" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Description</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <textarea class="form-control" id="mtxtDescription" rows="4" placeholder="Enter description"></textarea>
                </div>
                <div class="text-end">
                    <button type="button" class="btn btn-success" onclick="updDescription()">Update</button>
                </div>
            </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 / 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="mtxtExtraBed" class="col-md-3 col-form-label text-end">Add-on Qty:</label>
                        <div class="col-md-3">
                            <input id="mtxtExtraBed" name="ExtraBed" class="form-control" type="number" min="0" max="2" 
                                   onchange="mextraBed()" onkeypress="return isNumber(event)" onkeyup="btozero(this);" 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>

    <?php
        $user = isset($_SESSION['user']) ? $_SESSION['user'] : '';
    ?>
    var user = '<?php echo $user; ?>';
    let DESC_OBJ = null;

    function buildBookingRemark() {
        const rentalPeriod = getRentalPeriod();

        return "CARRTL_BOOK|" + JSON.stringify({
            pickup_location: $("#pickupLocation").val().trim(),
            return_location: $("#returnLocation").val().trim(),
            rental_purpose: $("#rentalPurpose").val().trim(),
            rental_mode: $("#rentalMode").val(),
            pickup_datetime: rentalPeriod.startText,
            return_datetime: rentalPeriod.availabilityEndText || rentalPeriod.endText,
            rental_hours: rentalPeriod.hours,
            note: $("#remark").val().trim()
        });
    }

    let checkInOutPicker = null;
    let pickupDatePicker = null;

    function addDays(date, days) {
        const copy = new Date(date);
        copy.setDate(copy.getDate() + days);
        return copy;
    }

    function getRentalPeriod() {
        const isHourly = $("#rentalMode").val() === "hourly";

        if (isHourly) {
            const pickupDate = $("#pickupDate").val();
            const pickupTime = $("#pickupTime").val();
            const returnTime = $("#returnTime").val();
            const startText = pickupDate && pickupTime ? pickupDate + " " + pickupTime : "";
            const endText = pickupDate && returnTime ? pickupDate + " " + returnTime : "";
            const startDate = startText ? new Date(pickupDate + "T" + pickupTime) : null;
            const endDate = endText ? new Date(pickupDate + "T" + returnTime) : null;
            let hours = 0;

            if (startDate && endDate && !isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
                hours = Math.max(0, Math.ceil((endDate - startDate) / (1000 * 3600)));
            }

            return { startText, endText, startDate, endDate, hours };
        }

        const rangeValue = $("#checkInOutDate").val();
        const parts = rangeValue ? rangeValue.split(" to ") : [];
        const startText = parts[0] || "";
        const endText = parts[1] || startText;
        const startDate = startText ? new Date(startText) : null;
        const endDate = endText ? new Date(endText) : null;
        const availabilityEndDate = endDate && !isNaN(endDate.getTime()) ? addDays(endDate, 1) : null;
        const availabilityEndText = availabilityEndDate ? formatDateToYMD(availabilityEndDate) : "";
        let hours = 0;

        if (startDate && endDate && !isNaN(startDate.getTime()) && !isNaN(endDate.getTime())) {
            const rentalDays = Math.floor((endDate - startDate) / (1000 * 3600 * 24)) + 1;
            hours = Math.max(24, rentalDays * 24);
        }

        return { startText, endText, startDate, endDate, availabilityEndDate, availabilityEndText, hours };
    }

    function resetSelectedVehicle() {
        $('#stayDetailsTable .stay-grid').empty(); 
        $("#roomId").val("");          
        $("#roomNumber").val("");       
        $("#roomInfo").val("");
        $("#roomType").val("");    
        $("#bedType").val("");    
        $("#roomRate").val("");    
        $("#extraBed").val("");    
        $("#extraPerson").val("");  
        $('#totalAmount').val('');
        $('#discountAmount').val('0');
        $('#netAmount').val('');
    }

    function initCheckInOutPicker() {
        if (checkInOutPicker) {
            checkInOutPicker.destroy();
        }
        if (pickupDatePicker) {
            pickupDatePicker.destroy();
        }

        const isHourly = $("#rentalMode").val() === "hourly";

        $("#dailyPeriodWrap").toggleClass("d-none", isHourly);
        $("#hourlyDateWrap").toggleClass("d-none", !isHourly);
        $("#pickupTimeWrap").toggleClass("d-none", !isHourly);
        $("#returnTimeWrap").toggleClass("d-none", !isHourly);

        if (isHourly) {
            pickupDatePicker = flatpickr("#pickupDate", {
                dateFormat: "Y-m-d",
                defaultDate: $("#pickupDate").val() || today,
                onChange: function() {
                    resetSelectedVehicle();
                    maybeOpenVehicleList();
                }
            });

            $("#pickupTime, #returnTime").off("change.hourly").on("change.hourly", function() {
                resetSelectedVehicle();
                maybeOpenVehicleList();
            });
        } else {
            checkInOutPicker = flatpickr("#checkInOutDate", {
                mode: "range",
                dateFormat: "Y-m-d",
                showMonths: 2,
                onChange: function(selectedDates) {
                    resetSelectedVehicle();

                    if (selectedDates.length >= 1) {
                        getRoomList();
                    }
                }
            });
        }
    }

    function maybeOpenVehicleList() {
        const rentalPeriod = getRentalPeriod();

        const isHourly = $("#rentalMode").val() === "hourly";
        if (rentalPeriod.startDate && rentalPeriod.endDate && (isHourly ? rentalPeriod.endDate > rentalPeriod.startDate : rentalPeriod.endDate >= rentalPeriod.startDate)) {
            getRoomList();
        }
    }

    function buildCustomerDocument() {
        return "CARRTL_DOC|" + JSON.stringify({
            document_type: $("#documentTypeE").val(),
            document_no: $("#ppNRCE").val().trim(),
            license_expiry: $("#licenseExpiryE").val()
        });
    }

// const today = new Date().toISOString().slice(0, 16).replace('T', ' '); // Generates "2025-01-19 14:30"
    const today = new Date();

    $(document).ready(function() {
        getReservationNo();
        flatpickr("#dateTime", {
            dateFormat: "Y-m-d H:i", // Include date and time in the display format
            defaultDate: today,      // Set the default to the current date and time
            maxDate: today,          // Prevent future date selection
            enableTime: true,        // Enable time picker
            time_24hr: true          // Use 24-hour format
        });

        initCheckInOutPicker();

        $("#rentalMode").on("change", function() {
            $("#checkInOutDate").val("");
            $("#pickupDate").val("");
            $("#pickupTime").val("09:00");
            $("#returnTime").val("12:00");
            resetSelectedVehicle();
            initCheckInOutPicker();
        });

        getAgentList();
    });

	function getReservationNo(){

		$("#reservationNo").val("");
		$.ajax({
			url: APP_URL + "api/reservation/get_generate_reservation_no.php",
			type: "POST",
			data: JSON.stringify({ date: "" }),
		}).done(function(data) {
            $("#reservationNo").val(data.reservation_no);
		});
	}
	
    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 a driver</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 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": "License / ID" },
            { "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 getRoomList() {
    const rentalPeriod = getRentalPeriod();
    const startDate = rentalPeriod.startDate;
    const endDate = rentalPeriod.endDate;
    const isHourly = $("#rentalMode").val() === "hourly";

    // Validate the dates
    if (!startDate || !endDate || isNaN(startDate.getTime()) || isNaN(endDate.getTime()) || (isHourly ? endDate <= startDate : endDate < startDate)) {
        console.error("Invalid start or end date.");
        return; // Exit the function if the dates are invalid
    }

    $('#roomModel').on('shown.bs.modal', function () {
        $('#myTableRoom_filter input').focus();
    });
    $('#roomModel').modal('show');

    table = $('#myTableRoom').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/room/get_aval_room_datatable.php",
            "data": {
                "startDate": isHourly ? rentalPeriod.startText : formatDateToYMD(startDate),
                "endDate": isHourly ? rentalPeriod.endText : rentalPeriod.availabilityEndText
            },
            "dataSrc": "records"
        },
        "columns": [
            { "title": "ID", "visible": false }, 
            { "title": "Vehicle Number" },
            { "title": "Current Plan" },
            { "title": "Vehicle Category" },
            { "title": "Transmission", "visible": false },
            { "title": "Seats", "visible": false },
            { "title": "Rental Rate", "visible": false },
            { "title": "Add-on Rate", "visible": false },
            { "title": "Extra Driver Fee", "visible": false },
            { "title": "Vehicle Details" },
        ]
    });

    $('#myTableRoom').on('click', 'tbody td', function(e) {
        var rowData = table.row($(this).parents('tr')).data(); 
        $("#roomId").val(rowData[0]);          
        $("#roomNumber").val(rowData[1]);       
        $("#roomType").val(rowData[3]);    
        $("#bedType").val(rowData[4]);    
        $("#roomRate").val(rowData[6]);    
        $("#extraBed").val(rowData[7]);    
        $("#extraPerson").val(rowData[8]);  

        $("#roomModel").modal('hide');
        addStayDetailRow();
    });
}

    $(document).on('click', '.removeRow', function() {
        $(this).closest('tr').remove();
        updateTotalAmount(); 
    });

    $('#btnGenerateStayDetails').click(function() {
        addStayDetailRow(); 
    });

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

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

        console.log(reservationData); 

        $.ajax({
            type: "POST",
            url: APP_URL + "api/reservation/create_update.php",
            contentType: "application/json", 
            data: JSON.stringify(reservationData),
            success: function(response) {
                if (response.message === "created") {
                    askPickupAfterCreate(response.reservation_no || reservationData.reservation_no, reservationData.room_no);
                } else if (response.message === "updated") {
                    resetReservationFormExceptDateAgent();
                    // $("#reservationForm")[0].reset();
                    $("#stayDetailsTable tbody").empty();
                    showAlert("Booking updated successfully!", "success");
                } else if (response.message === "duplicate") {
                    showAlert("Duplicate booking found!", "warning");
                } else if (response.message === "vehicle_unavailable") {
                    showAlert("Selected vehicle is not free for this rental period.", "warning");
                } else {
                    showAlert("Error on server side!", "error");
                }
            },
            error: function() {
                showAlert("Error on server side!", "error");
            },
            complete: function() {
                $('#reservationModal').modal('hide'); 
            }
        });

});

function askPickupAfterCreate(reservationNo, roomNo) {
    Swal.fire({
        icon: 'success',
        title: 'Created',
        text: 'Booking ' + (reservationNo || '') + ' has been successfully created. Do you want to do pickup now?',
        showCancelButton: true,
        confirmButtonText: 'Yes, Pickup',
        cancelButtonText: 'No'
    }).then(function(result) {
        if (result.isConfirmed) {
            runPickupAfterCreate(reservationNo, roomNo);
            return;
        }

        resetReservationFormExceptDateAgent();
        $("#stayDetailsTable tbody").empty();
    });
}

function runPickupAfterCreate(reservationNo, roomNo) {
    $.ajax({
        type: "POST",
        url: APP_URL + "api/reservation/update_check_in.php",
        contentType: "application/json",
        data: JSON.stringify({ reservation_no: reservationNo, room_no: roomNo }),
        success: function(data) {
            if (data.message === "updated") {
                resetReservationFormExceptDateAgent();
                $("#stayDetailsTable tbody").empty();
                Swal.fire({
                        icon: 'success',
                    title: 'Pickup Done',
                    text: 'Booking ' + (reservationNo || '') + ' has been picked up.',
                    timer: 2000,
                    timerProgressBar: true,
                    willClose: () => {
                        window.location.href = 'pickup_list.php';
                    }
                });
            } else {
                showAlert("Booking created, but pickup failed!", "warning");
            }
        },
        error: function() {
            showAlert("Booking created, but pickup failed!", "warning");
        }
    });
}

function resetReservationFormExceptDateAgent() {
    // Save values to preserve
    const dateTimeValue = $('#dateTime').val();
    const agentId = $('#agentName').val(); // or selected data-id if needed

    // Reset the form
    $('#reservationForm')[0].reset();

    // Restore preserved values
    $('#dateTime').val(dateTimeValue);
    
    if (agentId) {
        $('#agentName').val(agentId).trigger('change');
    }

    // Optionally, clear stay details and total
    $('#stayDetailsTable tbody').empty();
    $('#totalAmount').val('');
    $('#discountAmount').val('0');
    $('#netAmount').val('');
    initCheckInOutPicker();
    getReservationNo();
}


function getStayDetails() {
        const stayDetails = [];
        $('#stayDetailsTable .stay-grid tr').each(function() {
            const row = $(this);
            const rate = parseFloat(row.find(".roomRate").text().replace(/,/g, '')) || 0;
            const billingUnits = parseFloat(row.find(".billingUnits").text()) || 1;
            const stayDetail = {
                date: row.find('td').eq(0).attr('data-date') || row.find('td').eq(0).text(),                
                description: row.find(".description").text(),
                rate_mode: $('#rentalMode').val(),
                billing_units: billingUnits,
                unit_rate: rate,
                room_rate: rate * billingUnits,           
                extra_bed : row.find(".extraBedRate").text().split(' x ')[0],
                extra_bed_rate : parseFloat(row.find(".extraBedRate").text().split(' x ')[1].replace(/,/g, '')),
                extra_person : row.find(".extraPersonRate").text().split(' x ')[0],
                extra_person_rate : parseFloat(row.find(".extraPersonRate").text().split(' x ')[1].replace(/,/g, '')),            
            };
            stayDetails.push(stayDetail);
        });
        return stayDetails;
    }

function addStayDetailRow() {
    const roomNo = $('#roomNumber').val();
    const roomType = $('#roomType').val();
    const bedType = $('#bedType').val();
    const isHourly = $("#rentalMode").val() === "hourly";

    if (!roomNo) {
        showAlert("Please select a vehicle.", "warning");
        return;
    }

    const rentalPeriod = getRentalPeriod();
    const startDate = rentalPeriod.startDate;
    const endDate = rentalPeriod.endDate;

    if (!startDate || !endDate || isNaN(startDate.getTime()) || isNaN(endDate.getTime()) || (isHourly ? endDate <= startDate : endDate < startDate)) {
        showAlert(isHourly ? "Please select a return time after pickup time." : "Please select a valid pickup and return period.", "warning");
        return;
    }

    const billingUnits = isHourly ? rentalPeriod.hours : (Math.floor((endDate - startDate) / (1000 * 3600 * 24)) + 1);
    const rowCount = isHourly ? 1 : billingUnits;

    const extraBedCount = parseFloat($('#extraBedInput').val().replace(/,/g, '')) || 0;
    const extraPersonCount = parseFloat($('#extraPersonInput').val().replace(/,/g, '')) || 0;
    const extraBedRate = parseFloat($('#extraBed').val().replace(/,/g, '')) || 0;
    const extraPersonRate = parseFloat($('#extraPerson').val().replace(/,/g, '')) || 0;
    const roomRate = parseFloat($("#roomRate").val().replace(/,/g, '')) || 0;
    const description = $('#rentalDescription').val().trim();

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

    for (let i = 0; i < rowCount; i++) {
        const currentDate = new Date(startDate);
        currentDate.setDate(currentDate.getDate() + i);
        const rowUnits = isHourly ? billingUnits : 1;
        const periodLabel = isHourly
            ? formatDateToYMD(startDate) + " " + $("#pickupTime").val() + "-" + $("#returnTime").val() + " (" + billingUnits + " hrs)"
            : formatDateToYMD(currentDate);

        const total = (roomRate * rowUnits) + (extraBedCount * extraBedRate) + (extraPersonCount * extraPersonRate);

        $('#stayDetailsTable .stay-grid').append(`
            <tr>
                <td data-date="${formatDateToYMD(currentDate)}">${periodLabel}</td>
                <td class="description" onclick='getDescription(this)' style="background-color: #fff3cd;cursor: pointer;"></td>
                <td class="roomRate" onclick='getRoomRate(this)' style="background-color: #fff3cd;cursor: pointer;">${roomRate.toLocaleString()}</td>
                <td class="extraBedRate" onclick='getExtraBedRate(this)' style="background-color: #fff3cd;cursor: pointer;">${extraBedCount} x ${extraBedRate.toLocaleString()}</td>
                <td class="extraPersonRate" onclick='getExtraPaxRate(this)' style="background-color: #fff3cd;cursor: pointer;">${extraPersonCount} x ${extraPersonRate.toLocaleString()}</td>
                <td class="total">${total.toLocaleString()}</td>
                <td class="billingUnits" style="display: none;">${rowUnits}</td>
                <td style="display: none;">${roomType}</td>
                <td style="display: none;">${bedType}</td>
            </tr>
        `);

        $('#stayDetailsTable .stay-grid tr:last .description').text(description);
    }

    updateAllTotals();
}

function updateAllTotals() {
    let grandTotal = 0; 

    $('#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;
        const billingUnits = parseFloat($(this).find(".billingUnits").text()) || 1;

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

        grandTotal += total; 
    });

    $('#totalAmount').val(grandTotal.toLocaleString()); 
    updateNetAmount();
}

function parseCurrency(value) {
    return parseFloat(String(value || '').replace(/,/g, '')) || 0;
}

function updateNetAmount() {
    const total = parseCurrency($('#totalAmount').val());
    const discount = getDiscountAmount();
    const netAmount = Math.max(0, total - discount);
    $('#netAmount').val(netAmount.toLocaleString());
}

function getDiscountAmount() {
    const total = parseCurrency($('#totalAmount').val());
    return Math.min(parseCurrency($('#discountAmount').val()), total);
}

$('#discountAmount').on('input', updateNetAmount);

$('#discountAmount').on('blur', function() {
    const discount = getDiscountAmount();
    $(this).val(discount ? discount.toLocaleString() : '0');
    updateNetAmount();
});

function getRoomRate(obj){
    // checkPassword(function() {
        $("#myModalRoomRate").modal('show');
        $("#mtxtRoomRate").val($(obj).text().replace(/,/g, ''));
    // });
    OBJ = obj;
}

function getDescription(obj){
    DESC_OBJ = obj;
    $("#mtxtDescription").val($(obj).text().trim());
    $("#myModalDescription").modal('show');
}

function updDescription(){
    $("#myModalDescription").modal('hide');
    $(DESC_OBJ).text($("#mtxtDescription").val().trim());
}

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, ''));
        const billingUnits = parseFloat($(OBJ).closest('tr').find(".billingUnits").text()) || 1;
		amount = (room_rate * billingUnits) + (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]);
            $("#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, ''));
        const billingUnits = parseFloat($(OBJ).closest('tr').find(".billingUnits").text()) || 1;
		amount = (room_rate * billingUnits) + (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]);
            $("#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, ''));
        const billingUnits = parseFloat($(OBJ).closest('tr').find(".billingUnits").text()) || 1;
		amount = (room_rate * billingUnits) + (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
        }
    }


function addGuest() {

    let isValid = true;

    $("#guestNameE").removeClass("is-invalid");

    if ($("#guestNameE").val() === null || $("#guestNameE").val().trim() === "") {
        $("#guestNameE").addClass("is-invalid");
        isValid = false; 
    }

    if (isValid) {

        var formData = new FormData();
        formData.append("id", $("#guestId").val());
        formData.append("guest_name", $("#guestNameE").val());
        formData.append("contact_number", $("#contactNumberE").val());
        formData.append("email", $("#emailE").val());
        formData.append("country", $("#country").val());
        formData.append("ppnrc", buildCustomerDocument());
        formData.append("address", $("#addressE").val());

        // Check if a photo is selected and append it to the form data
        var photo = $("#photoUpload")[0].files[0];
        if (photo) {
            formData.append("photo", photo);
        }

        $.ajax({
            type: "POST",
            url: APP_URL + "api/guest/create_update.php",
            data: formData,
            processData: false,  // Prevent jQuery from automatically converting data to a query string
            contentType: false,  // Prevent jQuery from setting the content type
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    $("#guestId").val(data.guest_id);
                    $("#guestName").val($("#guestNameE").val());
                    $("#guestNameE").val("");
                    $("#contactNumberE").val("");
                    $("#emailE").val("");
                    $("#country").val("");
                    $("#documentTypeE").val("Driving License");
                    $("#ppNRCE").val("");
                    $("#licenseExpiryE").val("");
                    $("#addressE").val("");
                    $("#photoUpload").val(""); 
                    $('#guestModel').modal('hide');
                } else if (data.message === "duplicate") {
                    showAlert("Customer already exists!", "warning");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            }
        });
    }
}

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');
        }
    });
}


function formatDateToYMD(date) {
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2); 
    const day = ('0' + date.getDate()).slice(-2); 
    return `${year}-${month}-${day}`;
}





</script>

