
<?php include 'auth_check.php'; ?>
<?php include 'header.php'; ?>

<?php
session_start();

$userrole_id = $_SESSION['userrole_id'] ?? '';
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
    .btn-active {
        background-color: #1f4e79; /* Highlight color (teal) */
        color: #ffffff; /* White text */
        border-color: #1f4e79; /* Consistent border */
    }
     /* .table-responsive {
        margin: 20px 0;
    } */

    #roomStatusTable .btn {
        /* padding: 5px 5px; */
        border-radius: 6px;
        font-weight: bold;
    }

    /* .btn-outline-primary {
        border: 2px solid #007bff;
    } */

    /* Table Styling */
    #roomStatusTable table {
        width: 100%;
        border-spacing: 0;
        /* font-family: Arial, sans-serif; */
        font-size: 0.6rem;
        
    }

    /* th, td {
        padding: 12px;
        text-align: center;
        vertical-align: middle;
        border: 2px solidrgb(177, 13, 13);
        word-wrap: break-word;
        max-width: 100px;
        overflow: hidden;
    } */

    /* th {
        background-color: #007bff;
        color: white;
        font-weight: 600;
        position: sticky;
        top: 0;
    } */

    #roomStatusTable tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    /* Cell Status Colors */
    #roomStatusTable .status-checkin {
        background-color: #28a745 !important;
        color: white;
        border-radius: 8px;
    }

    #roomStatusTable .status-reserve {
        background-color: #007bff !important;
        color: white;
        border-radius: 8px;
    }

    #roomStatusTable .status-confirm {
        background-color: #6f42c1 !important;
        color: white;
        border-radius: 8px;
    }

    #roomStatusTable .status-clean {
        background-color: #1f4e79 !important;
        color: white;
        border-radius: 8px;
    }

    #roomStatusTable .status-service {
        background-color: #dc3545 !important;
        color: white;
        border-radius: 8px;
    }

    #roomStatusTable .status-checkout {
        background-color: #ee732f !important; /* Yellow for checkout */
        color: white;
        border-radius: 8px;
    }


    #roomStatusTable .name-cell {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 30px;
        display: block;
        text-align: center;
    }

    #roomStatusTable td {
        width: 30px;
        max-width: 30px;
        text-align: center;
    }

    #roomStatusTable th {
        text-align: center;
        width: 50px;
    }

    #roomStatusTable .occupancy-graph-cell {
        height: 50px;
        background-color: rgba(75, 192, 192, 0.2);
        border: 1px solid #e0e0e0;
    }

    /* Set fixed width for Room Type column */
    #roomStatusTable th:nth-child(1),
    #roomStatusTable td:nth-child(1) {
        font-size: 7px;
        min-width: 100px; /* Adjust width as needed */
        max-width: auto;
        white-space: nowrap; /* Prevent text from wrapping */
        overflow: hidden;
        text-overflow: ellipsis; /* Add ellipsis for overflow text */
    }

    #roomStatusTable td:nth-child(2) {
        width: 50px; /* Adjust width as needed */
        max-width: 50px;
    }

    #roomStatusTable td:nth-child(n+3), 
    #roomStatusTable th:nth-child(n+3) {
        width: 40px; /* Adjust the width as needed */
        max-width: 40px;
        white-space: nowrap; /* Prevent text wrapping */
        overflow: hidden; 
        padding-left: 1px;
        /* text-overflow: ellipsis; */
    }

    #roomStatusTable #bookedRow td, #availableRow td, #dailyOccupancyRow th, #percentageRow th, #dayRow th {
        font-family: "Helvetica Neue", Arial, sans-serif; /* Same font as 'PERCENTAGE' */
        font-weight: bold;          /* Bold font */
        text-transform: uppercase;  /* Convert text to uppercase */
        font-size: 0.5rem;          /* Adjust the font size */
        color: #555;                /* Dark gray color for consistency */
        text-align: center;         /* Center the text */
    }

    #roomStatusTable tr:last-child td {
        font-size: 7px; /* Adjust the size as needed */
        font-weight: bold; /* Optional for styling */
        color: #333; /* Optional: change font color */
    }
    
    /* Tooltip Base Styles */
    .tooltip {
        position: absolute;
        background: #ffffff; /* White background */
        color: #333; /* Text color */
        border-radius: 8px; /* Rounded corners */
        padding: 5px; /* Inner padding */
        font-size: 13px; /* Font size */
        font-weight: 500; /* Slightly bold */
        white-space: nowrap; /* Prevent wrapping */
        z-index: 1000; /* Make sure it's above everything */
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Add shadow for depth */
        opacity: 0; /* Hidden by default */
        transition: opacity 0.3s ease, transform 0.3s ease; /* Smooth fade-in animation */
    }

    /* Tooltip Visible State */
    .tooltip.visible {
        opacity: 1; /* Make it visible */
        transform: translateY(4px); /* Slightly slide it upward */
    }

    /* Tooltip Arrow */
    .tooltip-arrow {
        position: absolute;
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 10px; /* Size of the arrow */
        border-color: transparent transparent #ffffff transparent; /* Arrow pointing up */
        top: 100%; /* Position at the bottom of the tooltip */
        left: 50%; /* Center the arrow horizontally */
        transform: translateX(50%);
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); /* Add shadow for visibility */
    }

    /* Tooltip Content */
    .tooltip-content {
        padding: 5px;
        background: #ffffff; /* White background for the tooltip content */
        border-radius: 8px;
    }


    .highlighted-cell {
        background: linear-gradient(135deg,rgb(169, 169, 169),rgb(169, 169, 169)); /* Smooth gradient background */
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Add a subtle shadow for a 3D effect */
        transition: all 0.3s ease-in-out; /* Smooth and modern animation */
        padding: 5px; /* Add some inner spacing for better look */
        transform: scale(1); /* Slightly enlarge the cell for focus */
    }

    #columnChart {
        height: 374px;
    }
    #columnChartMonthlySales {
        height: 374px;
    }
    
#roomStatusTable th {
    text-align: center;
    background: #fff; /* must have background */
}

/* Month row sticky */
#monthRow th {
    position: sticky;
    top: 50;
    z-index: 10;
}

/* Day row sticky */
#dayRow th {
    position: sticky;
    top: 80px; /* adjust to month row height */
    z-index: 5;
}



</style>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-deck row-cards">

            <!-- Array of card definitions -->
            <?php
            $cards = [
                ['id' => 'reservation', 'title' => 'New Reservations'],
                ['id' => 'onboard', 'title' => 'On Board'],
                ['id' => 'arrival', 'title' => 'Arrivals'],
                ['id' => 'departure', 'title' => 'Departures'],
                // ['id' => 'expense', 'title' => 'Expense'],
                ['id' => 'osc_income', 'title' => 'OSC Income'],
                // ['id' => 'room_income', 'title' => 'Room Income'],
                // ['id' => 'osc_income', 'title' => 'OSC Income']
            ];

            foreach ($cards as $card) {
            ?>
            <div class="col-sm-6 col-lg-2">
                <div class="card" style="border: 1px solid #1f4e79; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
                    <div class="card-body text-center">
                        <div class="subheader" style="color: #1f4e79; font-weight: bold;">
                            <?php echo $card['title']; ?>
                        </div>
                        <!-- <div class="mt-1 mb-1" id="<?php echo $card['id']; ?>" style="color: #1f4e79;"></div> -->
                        <div class="mt-1 mb-1" 
                            id="<?php echo $card['id']; ?>" 
                            style="color: #1f4e79; <?php echo ($card['id'] === 'reservation' || $card['id'] === 'checkin') ? 'cursor: pointer;color: blue;' : ''; ?>">
                        </div>

                        <div class="d-flex justify-content-around">
                            <?php if ($card['id'] !== 'departure' && $card['id'] !== 'onboard') { ?>
                                <button class="btn btn-sm " onclick="getData('<?php echo $card['id']; ?>', 'yesterday', this)">Yesterday</button>
                            <?php } ?>
                            <button class="btn btn-sm " onclick="getData('<?php echo $card['id']; ?>', 'today', this)">Today</button>
                            <?php if ($card['id'] !== 'reservation' && $card['id'] !== 'checkin') { ?>
                                <button class="btn btn-sm " onclick="getData('<?php echo $card['id']; ?>', 'tomorrow', this)">Tomorrow</button>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php
            }
            ?>

        </div>
    </div>

    <div class="container-xl mt-3">
        <div class="row">

            

            <div class="col-lg-6 col-md-12">
                <div class="row">
                    <div class="col-lg-6 col-md-12">
                        <div class="card shadow-sm">
                            <div class="card-body p-0">
                                <canvas id="agentPieChart" width="200" height="200"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-6 col-md-12">
                        <div class="card shadow-sm">
                            <div class="card-body p-0">
                                <canvas id="nightChart" width="200" height="200"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            
            <div class="col-lg-6 col-md-12">

                <div class="row">
                    <div class="col-lg-12">
                        <div class="card shadow-sm">
                            <div class="card-body">
                                <h6>Employees Currently On Duty</h6>
                                <div id="dashboard" style="display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-start;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <div class="col-lg-6 col-md-12">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <canvas id="columnChart" width="400" height="365"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-12">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <canvas id="columnChartMonthlySales" width="400" height="365"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>


    

    <div class="container-xl mt-3">
        <div class="card shadow-sm">
            <div class="card-body">
            <div class="d-flex align-items-center" style="border: 1px solid #ddd; padding: 8px;">
                <!-- Search Bar -->
                <div class="me-2" style="max-width: 250px;">
                    <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="Search here..." style="width: 100%;">
                </div>


                <button id="prevWeek" class="btn btn-outline-primary btn-sm px-2 py-1 me-2">
                    &larr;
                </button>
                
 
                <button id="nextWeek" class="btn btn-outline-primary btn-sm px-2 py-1">
                    &rarr;
                </button>
            </div>



                <div id="roomStatusTable" class="rounded-3"></div>
                <div id="legend" class="rounded-3 mt-3 p-2" style="background-color: #f8f9fa; border: 1px solid #e0e0e0;">
                    <span style="display: inline-flex; align-items: center; margin-left: 10px;">
                        <span style="display: inline-block; width: 20px; height: 20px; background-color: #ee732f ; margin-right: 8px; border-radius: 4px;"></span> Checkout
                    </span>
                    <span style="display: inline-flex; align-items: center; margin-left: 20px;">
                        <span style="display: inline-block; width: 20px; height: 20px; background-color: #28a745; margin-right: 8px; border-radius: 4px;"></span> Checkin
                    </span>
                    <span style="display: inline-flex; align-items: center; margin-left: 20px;">
                        <span style="display: inline-block; width: 20px; height: 20px; background-color: #007bff; margin-right: 8px; border-radius: 4px;"></span> Reservation
                    </span>
                    
                </div>
            </div>
        </div>

        <div class="modal fade" id="roomDetailModal" tabindex="-1" aria-labelledby="roomDetailModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="roomDetailModalLabel">Room Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div id="roomDetailsContent"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php if ($userrole_id != 6): ?>
    <div class="container-xl mt-3" style="font-family: 'Arial', sans-serif;">
        <div class="row row-cards">
            <div class="col-6">
                <div class="card shadow-sm" style="border-radius: 12px; padding: 5px; background-color: #ffffff;">
                    <div class="card-body">
                        <h5>Cash Statement</h5>
                        <div class="row align-items-center">
                            <div class="input-group" style="width: 145px;">
                                From&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateFrom" 
                                    placeholder="From Date" aria-label="From Date" required>
                            </div>
                            <div class="input-group" style="width: 130px;">
                                To&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateTo" 
                                    placeholder="To Date" aria-label="To Date" required>
                            </div>
                        </div>


                        <div class="table-responsive mt-1" style="overflow-y: auto; max-height: 300px;">
                            <table class="table table-vcenter card-table table-sm table-striped" id="myTableMonthly" 
                                style="font-size: 12px; width: 100%; border-collapse: collapse;">
                                <thead style="position: sticky; top: 0; z-index: 10; background-color: #f8f9fa;">
                                    <tr>
                                        <th style="width: 20%;font-weight: 600; background-color: #f8f9fa; color: #495057;">Description</th>
                                        <th style="width: 20%;text-align: right; font-weight: 600; background-color: #f8f9fa; color: #495057;">Cash In</th>
                                        <th style="width: 40%;font-weight: 600; background-color: #f8f9fa; color: #495057;">Description</th>
                                        <th style="width: 20%;text-align: right; font-weight: 600; background-color: #f8f9fa; color: #495057;">Cash Out</th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
            </div>
            <div class="col-6">
                <div class="card shadow-sm" style="border-radius: 12px; padding: 5px; background-color: #ffffff;">
                    <div class="card-body">
                        <h5>Cash Book</h5>
                        <div class="row align-items-center">
                            <div class="input-group" style="width: 145px;">
                                From&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateFromCB" 
                                    placeholder="From Date" aria-label="From Date" required>
                            </div>
                            <div class="input-group" style="width: 130px;">
                                To&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateToCB" 
                                    placeholder="To Date" aria-label="To Date" required>
                            </div>
                            <div class="input-group" style="width: 180px;">
                            Type&nbsp;<select type="text" class="form-select form-select-sm" id="cboTypeCB">
										<option value="all">All</option>
										<option value="main cash">Main Cash</option>
										<option value="petty cash">Petty Cash</option>
									</select>
                            </div>
                        </div>
                        <div class="table-responsive mt-1" style="overflow-y: auto; max-height: 300px;">
                            <table class="table table-vcenter card-table table-sm table-striped" id="myTableCB" 
                                style="font-size: 12px; width: 100%; border-collapse: collapse;">
                                <thead style="position: sticky; top: 0; z-index: 10; background-color: #f8f9fa;">
                                    <tr>
                                        <th style="width: 3%">#</th>
										<th>Date</th>
										<th>Account Type</th>
										<th>Account Head</th>
										<th>Particular</th>
										<th>Income</th>
										<th>Expense</th>
										<th>Balance</th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>



                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php if ($userrole_id != 6): ?>
    <div class="container-xl mt-3" style="font-family: 'Arial', sans-serif;">
        <div class="row row-cards">
            <div class="col-6">
                <div class="card shadow-sm" style="border-radius: 12px; padding: 5px; background-color: #ffffff;">
                    <div class="card-body">
                        <h5>Rental Sales</h5>
                        <div class="row align-items-center">
                            <div class="input-group" style="width: 145px;">
                                From&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateFromRS" 
                                    placeholder="From Date" aria-label="From Date" required>
                            </div>
                            <div class="input-group" style="width: 130px;">
                                To&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateToRS" 
                                    placeholder="To Date" aria-label="To Date" required>
                            </div>
                        </div>


                        <div class="card mt-1">
                            <div class="card-body">
                                <div class="export-buttons-container" style="margin-bottom: 10px;">
                                    <button id="exportCSV" class="btn btn-outline-primary">Export to CSV</button>
                                    <button id="exportExcel" class="btn btn-outline-primary">Export to Excel</button>
                                    <button id="exportPDF" class="btn btn-outline-primary">Export to PDF</button>
                                    <button id="printTable" class="btn btn-outline-primary">Print Table</button>
                                </div>
                                <div class="table-responsive">
                                    <table id="myTableRS" class="table card-table table-vcenter text-nowrap datatable">
                                        <thead>
                                            <tr>
                                                <th>Vehicle No.</th>
                                                <th>Booking No.</th>
                                                <th>Driver Name</th>
                                                <th>Customer Name</th>
                                                <th>Booking Date</th>
                                                <th>Created At</th>
                                                <th>Rental Rate</th>
                                                <th>Add-on</th>
                                                <th>Extra Driver</th>
                                                <th>Total GROSS</th>
                                                <th>VAT (7%)</th>
                                                <th>Balance</th>
                                                <!-- <th>Actions</th> -->
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Dynamic content here -->
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th colspan="9" class="text-end">Total:</th>
                                                <th class="text-end"></th> <!-- sum will be shown here -->
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
            <div class="col-6">
                <div class="card shadow-sm" style="border-radius: 12px; padding: 5px; background-color: #ffffff;">
                    <div class="card-body">
                        <h5>Booking & Rental</h5>
                        <div class="row align-items-center">
                            <div class="input-group" style="width: 145px;">
                                From&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateFromRAS" 
                                    placeholder="From Date" aria-label="From Date" required>
                            </div>
                            <div class="input-group" style="width: 130px;">
                                To&nbsp;<input type="text" class="flatpickr form-control form-control-sm" id="dateToRAS" 
                                    placeholder="To Date" aria-label="To Date" required>
                            </div>
                        </div>


                        <div class="card mt-1">
                            <div class="card-body">
                                <div class="export-buttons-container" style="margin-bottom: 10px;">
                                    <button id="exportCSVRAS" class="btn btn-outline-primary">Export to CSV</button>
                                    <button id="exportExcelRAS" class="btn btn-outline-primary">Export to Excel</button>
                                    <button id="exportPDFRAS" class="btn btn-outline-primary">Export to PDF</button>
                                    <button id="printTableRAS" class="btn btn-outline-primary">Print Table</button>
                                </div>
                                <div class="table-responsive">
                                    <table id="myTableRAS" class="table card-table table-vcenter text-nowrap datatable">
                                        <thead>
                                            <tr>
                                                <th>Booking No.</th>
                                                <th>Driver Name</th>
                                                <th>Customer Name</th>
                                                <th>Vehicle No.</th>
                                                <th>Pickup</th>
                                                <th>Return</th>
                                                <th>Check In</th>
                                                <th>Check Out</th>
                                                <th>Rental Days</th>
                                                <th>Total</th>
                                                <th>Payment</th>
                                                <th>Balance</th>
                                                <th>Remark</th>
                                                <th>Booking Created At</th>
                                                <th>Entry At</th>
                                                <!--<th>Actions</th>-->
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Dynamic content here -->
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th colspan="8" class="text-end">Total:</th>
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                                <th class="text-end"></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>



                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

    <div id="detailModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Booking Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><strong>Date Time:</strong> <span id="dateTimeD"></span></p>
                    <p><strong>Booking No:</strong> <span id="reservationNoD"></span></p>
                    <p><strong>Driver Name:</strong> <span id="agentNameD"></span></p>
                    <p><strong>Customer Name:</strong> <span id="guestNameD"></span></p>
                    <p><strong>Vehicle No.:</strong> <span id="roomNoD"></span></p>
                    <p><strong>Pickup:</strong> <span id="checkInDateD"></span></p>
                    <p><strong>Return:</strong> <span id="checkOutDateD"></span></p>
                    <p><strong>Remark:</strong> <span id="remarkD"></span></p>
                    <!-- <p><strong>Deposit:</strong> <span id="depositD"></span></p> -->
                    <!-- <p><strong>Status:</strong> <span id="statusD"></span></p> -->
                    <table class="table table-striped" id="reservationItemsTable">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Vehicle No</th>
                                <th>Rental Rate</th>
                                <th>Add-on Qty</th>
                                <th>Add-on Rate</th>
                                <th>Extra Driver</th>
                                <th>Extra Driver Fee</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
    
                    <div class="row mt-3 text-end">
                        <div class="col-auto">
                            <div class="text-end  p-2">
                                <strong>Net Total:</strong> <span id="netTotalD"></span>
                            </div>
                        </div>
                        <!-- <div class="col-auto">
                            <div class="text-end p-2 ">
                                <strong>Deposit:</strong> <span id="depositD"></span>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="text-end  p-2">
                                <strong>Balance:</strong> <span id="balanceD"></span>
                            </div>
                        </div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="myModalIncome" tabindex="-1" aria-labelledby="myModalIncomeLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdtitle"></h5>
                    <h5 class="modal-title" id="mdtitle1"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="card card-md">
                        <div class="card-body p-0">
                            <!-- Table with max height and scrollable -->
                            <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                                <table class="table table-striped table-hover" id="myTable1">
                                    <thead class="sticky-top bg-light">
                                        <tr>
                                            <th style="width: 3%;">#</th>
                                            <th style="width: 10%;">Date</th>
                                            <th style="width: 30%;">Description</th>
                                            <th style="width: 30%;">Particular</th>
                                            <th style="width: 10%;">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Rows will be populated here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
</div>

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

<script>
        var today = new Date().toISOString().split('T')[0];
        const today1 = new Date();
        const firstDayOfMonth = new Date(today1.getFullYear(), today1.getMonth(), 1);
        $(function() {

            ["reservation","arrival", "departure", "onboard", "osc_income"].forEach(id => {
                getData(id, 'today');
                $(`#${id}`).closest(".card-body").find("button:contains('Today')").addClass("btn-active");
            });

            renderAttendanceDashboard();

            getAgentPie();
            getNightChart();

            getExInRoom();
            getMonthlyRoomSales();

            flatpickr("#dateFrom", {
                dateFormat: "Y-m-d",
                defaultDate: firstDayOfMonth, 
            
            });
            flatpickr("#dateTo", {
                dateFormat: "Y-m-d", 
                defaultDate: today,  
 
            });

            flatpickr("#dateFromCB", {
                dateFormat: "Y-m-d",
                defaultDate: firstDayOfMonth,
          
            });
            flatpickr("#dateToCB", {
                dateFormat: "Y-m-d", 
                defaultDate: today,  
         
            });

            flatpickr("#dateFromRS", {
                dateFormat: "Y-m-d", 
                defaultDate: firstDayOfMonth,  
  
            });
            flatpickr("#dateToRS", {
                dateFormat: "Y-m-d", 
                defaultDate: today,  
     
            });
        
            flatpickr("#dateFromRAS", {
                dateFormat: "Y-m-d", 
                defaultDate: firstDayOfMonth,  
  
            });
            flatpickr("#dateToRAS", {
                dateFormat: "Y-m-d", 
                defaultDate: today,  
    
            });
        
            getMonthly();
            getCashBook();
            loadCalender();
            getAllReservations();
            getAllReservationsRAS();
        });
        
        $("#dateFromRS, #dateToRS").change(function() {
            getAllReservations();
        });
        
        $("#dateFromRAS, #dateToRAS, #cboStatusRAS, #cboBalanceRAS").change(function() {
            getAllReservationsRAS();
        });

        function getData(cardId, dateType, button = null) {
            if (button) {
                $(button).siblings().removeClass('btn-active');
                $(button).addClass('btn-active');
            }

            $.ajax({
                url: APP_URL + `api/utils/get_${cardId}.php`,
                method: "POST",
                data: JSON.stringify({ type: dateType }),
                success: function (data) {
                    let output = `${data[cardId]}`;
                    if (cardId === 'reservation') {
                        const details = data.all_reservation_details;
                        setTimeout(() => {
                            showReservationModal(details);
                        }, 700);

                        $(`#${cardId}`).text(output);
                    } else {
                        $(`#${cardId}`).text(output);
                    }

                },
                error: function () {
                    $(`#${cardId}`).text(0.00);
                },
            });
        }

        // Function to generate and show the modal
        function showReservationModal(details) {
            if ($('#reservationModal').length) {
                $('#reservationModal').remove();
            }
        
            // Generate table rows for the reservation details
            let tableRows = details.map(detail => `
                <tr>
                    <td>${detail.reservation_no}</td>
                    <td>${detail.agent_name}</td>
                    <td>${detail.guest_name}</td>
                    <td>${detail.checkin_date}</td>
                    <td>${detail.checkout_date}</td>
                    <td>${detail.nights}</td>
                    <td>${detail.room_no}</td>
                    <td>${detail.date_time}</td>
                    <td>${detail.created_at}</td>
                </tr>
            `).join('');

            // Modal HTML content
            const modalHTML = `
                <div class="modal fade" id="reservationModal" tabindex="-1" role="dialog" aria-labelledby="reservationModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-xl" role="document">
                        <div class="modal-content">
                            <div class="modal-body table-responsive">
                                <table class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <th>Reservation No</th>
                                            <th>Agent Name</th>
                                            <th>Guest Name</th>
                                            <th>Check-in Date</th>
                                            <th>Check-out Date</th>
                                            <th>Nights</th>
                                            <th>Room No</th>
                                            <th>Date Time</th>
                                            <th>Entry At</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${tableRows}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            `;



        $('body').append(modalHTML);

        $('#reservationModal').on('hidden.bs.modal', function () {
                // $(this).remove();
            });
        }


        $('#reservation').on('click', function () {
            setTimeout(() => {
                $('#reservationModal').modal('show');
            }, 200);
        });

    function renderAttendanceDashboard() {
        // Fetch attendance data using AJAX
        $.ajax({
            url: APP_URL + "api/utils/get_attendance.php",
            method: "GET",
            dataType: "json", // Ensure response is automatically parsed as JSON
            success: function(data) {
                console.log("Parsed API Data:", data); // Log parsed data

                const dashboard = document.getElementById('dashboard');
                dashboard.innerHTML = ''; // Clear previous content

                data.records.forEach(employee => {
                    // Create a card for each employee
                    const employeeCard = document.createElement('div');
                    employeeCard.style.cssText = `
                        border: 1px solid #1f4e79;
                        border-radius: 5px;
                        padding: 2px;
                        width: 100px;
                        text-align: center;
                        background: white;
                        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                    `;

                    // Add the photo
                    const photo = document.createElement('img');
                    photo.src = employee.dp || "https://via.placeholder.com/200"; // Fallback image if dp is empty
                    photo.alt = employee.name;
                    photo.style.cssText = "width: 80%; height: 80px; border-radius: 10px;";

                    // Add the name
                    const name = document.createElement('h5');
                    name.textContent = employee.name;
                    name.style.cssText = "margin: 2px 0 5px; font-size: 10px; color: #333;";

                    // Add the duty-in time
                    const dutyInTime = document.createElement('p');
                    dutyInTime.textContent = `${employee.din}`;
                    dutyInTime.style.cssText = "margin: 2px 0; font-size: 10px; color: #444;";

                    // Append elements to the card
                    employeeCard.appendChild(photo);
                    employeeCard.appendChild(name);
                    employeeCard.appendChild(dutyInTime);

                    // Append card to the dashboard
                    dashboard.appendChild(employeeCard);
                });
            },
            error: function(xhr, status, error) {
                console.error("Error fetching attendance:", error);
            }
        });
    }

    function getAgentPie() {
        $.ajax({
            url: APP_URL + "api/utils/get_agent_pie.php",
            method: "GET",
            dataType: "json",
            success: function(data) {
                // Validate data
                if (data && data.records && Array.isArray(data.records)) {
                    const labels = data.records.map(item => item.agent_name);
                    const values = data.records.map(item => item.count);

                    // Calculate the total for percentage calculation
                    const total = values.reduce((sum, value) => sum + value, 0);

                    // Access canvas and set dimensions
                    const canvas = document.getElementById('agentPieChart');
                    const ctx = canvas.getContext('2d');

                    // Create pie chart
                    new Chart(ctx, {
                        type: 'pie',
                        data: {
                            labels: labels,
                            datasets: [{
                                data: values,
                                backgroundColor: [
                                    '#FF6384', '#36A2EB', '#FFCE56',
                                    '#4BC0C0', '#9966FF', '#FF9F40',
                                    '#C9CBCF'
                                ], // Colors for each section
                                hoverBackgroundColor: [
                                    '#FF7A92', '#4CA7F1', '#FFD369',
                                    '#64D6D6', '#B099FF', '#FFB45E',
                                    '#E0E2E6'
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'right', // Legend on the right
                                    labels: {
                                        generateLabels: function(chart) {
                                            const data = chart.data;
                                            return data.labels.map((label, index) => {
                                                const value = data.datasets[0].data[index];
                                                // const percentage = ((value / total) * 100).toFixed(2);
                                                return {
                                                    text: `${label}: ${value}`,
                                                    fillStyle: data.datasets[0].backgroundColor[index],
                                                    strokeStyle: data.datasets[0].backgroundColor[index],
                                                    hidden: false
                                                };
                                            });
                                        },
                                        font: {
                                            size: 10 // Match font size
                                        },
                                        boxWidth: 15, // Match box size
                                        padding: 10 // Spacing
                                    }
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(tooltipItem) {
                                            const label = tooltipItem.label || 'Unknown';
                                            const value = tooltipItem.raw || 0;
                                            const percentage = ((value / total) * 100).toFixed(2);
                                            return `${label}: ${value} (${percentage}%)`;
                                        }
                                    }
                                },
                                title: {
                                    display: true,
                                    text: 'Reservation Count By Agent',
                                    font: {
                                        size: 10, // Title font size
                                    },
                                    padding: {
                                        top: 5,
                                        bottom: 10
                                    },
                                    color: '#333' // Title color
                                }
                            },
                            layout: {
                                padding: {
                                    top: 10,
                                    right: 10,
                                    bottom: 10,
                                    left: 10
                                }
                            }
                        }
                    });
                } else {
                    console.error("Invalid data format:", data);
                }
            },
            error: function(xhr, status, error) {
                console.error("Error fetching agent pie data:", error);
            }
        });
    }

    function getNightChart() {
    // Define all months for reference
    const allMonths = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];

    // Make an AJAX request to fetch the night chart data
    $.ajax({
        url: APP_URL + "api/utils/get_night_chart.php",
        method: "GET",
        dataType: "json",
        success: function (data) {
            // Validate data structure
            if (data?.records && Array.isArray(data.records)) {
                // Initialize a map with all months set to 0
                const monthData = allMonths.map((month, index) => ({
                    month,
                    count: 0 // Default count is 0
                }));

                // Map the server data to the monthData structure
                data.records.forEach(record => {
                    const monthIndex = parseInt(record.month.split('-')[1], 10) - 1; // Get zero-based month index
                    if (monthData[monthIndex]) {
                        monthData[monthIndex].count = record.count;
                    }
                });

                // Extract labels (months) and values (counts)
                const labels = monthData.map(item => item.month);
                const values = monthData.map(item => item.count);

                // Calculate the total count for percentage calculation
                const total = values.reduce((sum, value) => sum + value, 0);

                // Access the canvas and set up the chart context
                const canvas = document.getElementById('nightChart');
                const ctx = canvas.getContext('2d');

                // Destroy any previous chart instance to prevent overlapping
                if (window.nightChartInstance) {
                    window.nightChartInstance.destroy();
                }

                // Create the donut chart
                window.nightChartInstance = new Chart(ctx, {
                    type: 'doughnut', // Changed from 'pie' to 'doughnut'
                    data: {
                        labels: labels,
                        datasets: [{
                            data: values,
                            backgroundColor: [
                                '#FF5733', '#33FF57', '#3357FF', '#FF33A8', '#FFC733', '#33FFF1',
                                '#8D33FF', '#FF8D33', '#33FF8D', '#FF3333', '#33A8FF', '#A8FF33'
                            ],
                            hoverBackgroundColor: [
                                '#FF694D', '#4DFF69', '#4D69FF', '#FF4DB9', '#FFD24D', '#4DFFF4',
                                '#9F4DFF', '#FF9F4D', '#4DFF9F', '#FF4D4D', '#4DB9FF', '#B9FF4D'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'right',
                                labels: {
                                    generateLabels: function (chart) {
                                        const data = chart.data;
                                        return data.labels.map((label, index) => {
                                            const value = data.datasets[0].data[index];
                                            return {
                                                text: `${label}: ${value}`,
                                                fillStyle: data.datasets[0].backgroundColor[index],
                                                strokeStyle: data.datasets[0].backgroundColor[index],
                                                hidden: false
                                            };
                                        });
                                    },
                                    font: {
                                        size: 10
                                    },
                                    boxWidth: 15,
                                    padding: 15
                                }
                            },
                            tooltip: {
                                callbacks: {
                                    label: function (tooltipItem) {
                                        const value = tooltipItem.raw || 0;
                                        const percentage = ((value / total) * 100).toFixed(2);
                                        return `${tooltipItem.label}: ${value} (${percentage}%)`;
                                    }
                                }
                            },
                            title: {
                                display: true,
                                text: 'Nights Count by Month',
                                font: {
                                    size: 10 // Adjusted title font size
                                },
                                padding: {
                                    top: 5,
                                    bottom: 10
                                },
                                color: '#333'
                            }
                        },
                        layout: {
                            padding: {
                                top: 10,
                                right: 10,
                                bottom: 10,
                                left: 10
                            }
                        }
                    }
                });
            } else {
                console.error("Invalid data format:", data);
            }
        },
        error: function (xhr, status, error) {
            console.error("Error fetching night data:", error);
        }
    });
}



    function getExInRoom() {
    $.ajax({
        url: APP_URL + "api/utils/get_column_chart.php", // Replace with your actual URL
        method: "GET",
        dataType: "json",
        success: function(response) {
            // Parse the data from the API response
            const records = response.records;

            // Format the dates to 'MM-DD' (e.g., '12-1', '12-2')
            const labels = records.map(item => {
                const date = new Date(item.d);
                const month = date.getMonth() + 1;
                const day = date.getDate();
                return `${day}`;
            });

            const expenses = records.map(item => item.expense);
            const incomes = records.map(item => item.income);
            const profit = records.map(item => item.profit);

            // Calculate the totals for expenses, incomes, and profit
            const totalExpenses = expenses.reduce((sum, value) => sum + value, 0);
            const totalIncomes = incomes.reduce((sum, value) => sum + value, 0);
            const totalProfit = profit.reduce((sum, value) => sum + value, 0);

            // Get the current year and month
            const today = new Date();
            const currentYear = today.getFullYear();
            const currentMonth = today.toLocaleString('default', { month: 'long' }); // e.g., "December"

            // Create the column chart
            const ctx = document.getElementById('columnChart').getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: 'Expense',
                            data: expenses,
                            backgroundColor: 'rgba(255, 0, 55, 0.8)', // Bright pink
                            borderColor: 'rgba(255, 99, 132, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'Income',
                            data: incomes,
                            backgroundColor: 'rgba(0, 255, 85, 0.8)', // Bright blue
                            borderColor: 'rgb(0, 255, 17)',
                            borderWidth: 1
                        },
                        {
                            label: 'Profit',
                            data: profit,
                            backgroundColor: 'rgba(0, 68, 255, 0.8)', // Bright green
                            borderColor: 'rgb(0, 47, 255)',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false, // Allows custom height from CSS
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                color: '#000000', // Bright black text for legend
                                font: {
                                    size: 14
                                }
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        },
                        title: {
                            display: true,
                            text: `${currentYear} - ${currentMonth}`,
                            font: {
                                size: 16,
                                weight: 'bold'
                            }
                        },
                        // Custom Plugin for Showing Totals at Bottom
                        subtitle: {
                            display: true,
                            text: `Total Expense: ${totalExpenses.toLocaleString()} | Total Income: ${totalIncomes.toLocaleString()} | Total Profit: ${totalProfit.toLocaleString()}`,
                            color: '#333333', // Slightly bright text
                            font: {
                                size: 14
                            },
                            padding: {
                                top: 10,
                                bottom: 10
                            }
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Date',
                                color: '#333333', // Slightly bright text for x-axis
                                font: {
                                    size: 14
                                }
                            },
                            ticks: {
                                autoSkip: false,
                                color: '#555555' // Slightly bright text for tick labels
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Amount',
                                color: '#333333', // Slightly bright text for y-axis
                                font: {
                                    size: 14
                                }
                            },
                            ticks: {
                                color: '#555555' // Slightly bright text for tick labels
                            }
                        }
                    }
                },
            });
        },
        error: function(xhr, status, error) {
            console.error("Error fetching data:", error);
        }
    });
}

    async function getMonthlyRoomSales() {
    try {
        const response = await $.ajax({
            url: APP_URL + "api/utils/get_column_chart_monthly_sales.php",
            method: "GET",
            dataType: "json"
        });

        const records = response.records || [];

        // Months Jan–Dec
        const monthLabels = [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun",
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
        ];

        // Initialize with zeros
        const OTAData = Array(12).fill(0);
        const WalkInData = Array(12).fill(0);

        records.forEach(item => {
            const idx = item.month - 1; // month = 1–12
            OTAData[idx] = Number(item.OTA) || 0;
            WalkInData[idx] = Number(item.WalkIn) || 0;
        });

        // Totals
        const totalOTA = OTAData.reduce((sum, v) => sum + v, 0);
        const totalWalkIn = WalkInData.reduce((sum, v) => sum + v, 0);
        const totalAll = totalOTA + totalWalkIn;

        // Chart setup
        const ctx = document.getElementById("columnChartMonthlySales").getContext("2d");
        new Chart(ctx, {
            type: "bar",
            data: {
                labels: monthLabels,
                datasets: [
                    {
                        label: "OTA",
                        data: OTAData,
                        backgroundColor: "#36a2eb", // Blue
                        borderColor: "#36a2eb",
                        borderWidth: 1
                    },
                    {
                        label: "Walk-In",
                        data: WalkInData,
                        backgroundColor: "#ff6384", // Red
                        borderColor: "#ff6384",
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: "top",
                        labels: {
                            color: "#000000",
                            font: { size: 14 }
                        }
                    },
                    tooltip: {
                        mode: "index",
                        intersect: false
                    },
                    title: {
                        display: true,
                        text: `Rental Sales by Month (${new Date().getFullYear()})`,
                        font: { size: 16, weight: "bold" }
                    },
                    subtitle: {
                        display: true,
                        text: `Total OTA: ${totalOTA.toLocaleString()} | Total Walk-In: ${totalWalkIn.toLocaleString()} | Grand Total: ${totalAll.toLocaleString()}`,
                        color: "#333333",
                        font: { size: 14 },
                        padding: { top: 10, bottom: 10 }
                    }
                },
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: "Month",
                            color: "#333333",
                            font: { size: 14 }
                        },
                        ticks: { color: "#555555" }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: "Amount",
                            color: "#333333",
                            font: { size: 14 }
                        },
                        ticks: { color: "#555555" }
                    }
                }
            }
        });

    } catch (error) {
        console.error("Error fetching data:", error);
    }
}







    $("#dateFrom, #dateTo").change(function() {
        getMonthly();
    });

	var BAL = 0 ;
	var COL = "" ;
    function getMonthly(){
		var df =$("#dateFrom").val();
		var dt =$("#dateTo").val();
		$("#myTableMonthly").find("tbody").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/sales/search_monthly_report.php",
			data: JSON.stringify({ df: df,dt: dt}),
		}).done(function(data) {	
			$.each(data.records_in, function(i, v) {
				var s="In";
				$("#myTableMonthly").find("tbody")
				.append($('<tr>')
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + Number(v.cash_in).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;' >" + Number(v.cash_in).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
					.append("<td></td>")
                    .append("<td></td>")
					)
			});	
              $.each(data.records_out, function(i, v) {
				var s="Out";

				$("#myTableMonthly").find("tbody")
				.append($('<tr>')
                    .append("<td></td>")
                    .append("<td></td>")
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + Number(v.cash_out).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;'>" + Number(v.cash_out).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
					)
			});	



			$("#myTableMonthly").find("tbody")
			.append($('<tr style="font-weight:bold;">')
            .append("<td colspan='1' style='text-align:left;'>Total</td>")
            .append("<td style='text-align:right;'>" + ((data.cash_in_total)?Number(data.cash_in_total).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
			.append("<td style='text-align:left;'>Total</td>")
			.append("<td style='text-align:right;'>" + ((data.cash_out_total)?Number(data.cash_out_total).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
  			); 

			  var $bc="";
			if(parseInt(data.cash_balance)<0){
				 $bc="color:red;";
				 COL ="color:red;";
			}else{
				$bc="";
				COL ="";
			}
			BAL = data.cash_balance;

            $("#myTableMonthly").find("tbody")
			.append($('<tr style="font-weight:bold;">')
            .append("<td colspan='3' style='text-align:right;'>Balance Amount</td>")
			.append("<td style='text-align:right;"+$bc+"'>" + ((data.cash_balance)?Number(data.cash_balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
  			); 
       });
	}	

    function getDetail(r,st,amt){

        $("#myModalIncome").modal('show');
        $("#mdtitle").text(st);

        $("#myTable1").find("tbody tr").remove();
        var df =$("#dateFrom").val();
        var dt =$("#dateTo").val();
        $.ajax({
            url: APP_URL + "api/sales/get_monthly_detail.php",
            type: "POST",
            data: JSON.stringify({ r:r, df: df, dt: dt, st:st, ym:"" })
        }).done(function(data){
            console.log(data.records)
                $.each(data.records, function(i, v) {
                    $("#myTable1").find("tbody")
                        .append($('<tr>')
                            .append("<td style='width: 10px'>" + (i+1) + "</td>")
                            .append("<td>" + v.date + "</td>")
                            .append("<td>" + v.description + "</td>")
                            .append("<td>" + v.particular + "</td>")
							.append("<td  style='text-align:right;'>" + Number(v.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                        )
                });
				$("#mdtitle1").text(Number(data.total_amountF).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
        });		
    }

    $("#dateFromCB, #dateToCB, #cboTypeCB").change(function() {
		getCashBook();
	});

    function getCashBook() {
        var df = $("#dateFromCB").val();
        var dt = $("#dateToCB").val();
        var type = $("#cboTypeCB").val();
        $.ajax({
            type: "POST",
            url: APP_URL + "api/sales/search_cash_book.php",
            data: JSON.stringify({ df: df, dt: dt, type: type }),
            error: function (data) {
                $("#loading").css("display", "none");
            }
        }).done(function (data) {
            console.log(data);
            $("#myTableCB").find("tbody").find("tr").remove();
            $("#myTableCB").find("tbody")
                .append($('<tr>')
                    .append("<td>1</td>")
                    .append("<td colspan='6'><b stylestyle='white-space: nowrap;'>Opening Balance</b></td>")
                    // .append("<td></td>")
                    // .append("<td></td>")
                    // .append("<td></td>")
                    // .append("<td></td>")
                    // .append("<td></td>")
                    .append("<td style='text-align: right;font-weight:bold;font-size:12px;'><span id='openingbalance'></span></td>")
                );
            $("#openingdate").text(df);
            $("#openingbalance").text(parseFloat(data.balance).toFixed(2));
            var balance = parseFloat(data.balance);

            $.each(data.records, function (i, v) {
                balance -= parseFloat(v.ex_amt);
                balance += parseFloat(v.in_amt);
                $("#myTableCB").find("tbody")
                    .append($('<tr>')
                        .append("<td>" + (i + 2) + "</td>")
                        .append("<td>" + v.date + "</td>")
                        .append("<td>" + v.account_head + "</td>")
                        .append("<td>" + v.head + "</td>")
                        .append("<td>" + v.particular + "</td>")
                        .append("<td style='text-align: right;'>" + ((v.in_amt == 0) ? "" : Number(v.in_amt).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })) + "</td>")
                        .append("<td style='text-align: right;'>" + ((v.ex_amt == 0) ? "" : Number(v.ex_amt).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })) + "</td>")
                        .append("<td style='text-align: right;" + (data.records.length == (i + 1) ? "font-weight:bold;font-size:14px;" : "") + "'>" + Number(balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                    );
            });

            $("#myTableCB").find("tbody")
                .append($('<tr style="font-weight:bold;">')
                    .append("<td colspan='8'>Total Amount From " + df + " To " + dt + " By Account Head</td>")
                );

            $.each(data.records1, function (i, b) {
                $("#myTableCB").find("tbody")
                    .append($('<tr style="font-weight:bold;">')
                        .append("<td colspan='2'>" + b.R + "</td>")
                        .append("<td colspan='1'>" + b.account_head + "</td>")
                        .append("<td style='text-align:right;'>" + Number(b.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                    );
            });

            $("#myTableCB").find("tbody")
                .append($('<tr style="font-weight:bold;">')
                    .append("<td colspan='8'>Total Amount From " + df + " To " + dt + " By Type</td>")
                );

            $.each(data.records2, function (i, b) {
                $("#myTableCB").find("tbody")
                    .append($('<tr style="font-weight:bold;">')
                        .append("<td colspan='2'>" + b.R + "</td>")
                        .append("<td style='text-align:right;'>" + Number(b.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
                    );
            });

            $("#total_records").text("Closing Balance = " + Number(balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
        });
    }
    // Search and Filter Table Rows
    $('#searchInput').on('input', function () {
        const searchValue = $(this).val().toLowerCase();

        // Iterate through all cells in the table body
        $('#roomStatusBody td').each(function () {
            const cellText = $(this).text().toLowerCase();

            // Check if the cell text matches the search value
            if (cellText.includes(searchValue) && searchValue !== '') {
                $(this).css({ filter: 'none', opacity: '1' }); // Clear blur for matching cells
            } else {
                $(this).css({ filter: 'blur(1px)', opacity: '1' }); // Blur non-matching cells
            }
        });

        // Reset all cells if the search input is cleared
        if (searchValue === '') {
            $('#roomStatusBody td').css({ filter: 'none', opacity: '1' });
        }
    });

    function loadCalender() {
        let currentDate = new Date();
        let startDate = currentDate;
        startDate.setDate(currentDate.getDate() - 7);
        const totalRooms = 25;  // Total number of rooms

        function getnextWeek(start) {
            const dates = [];
            const newStartDate = new Date(start);

            // Loop through the next 31 days
            for (let i = 0; i < 31; i++) {
                const date = new Date(newStartDate);
                dates.push(date.toISOString().split('T')[0]);
                newStartDate.setDate(newStartDate.getDate() + 1);
            }
            return dates;
        }


        function createRoomStatusTable() {
            const dates = getnextWeek(startDate);
            const today = new Date().toISOString().split('T')[0];
            const months = {};

            // Group dates by month
            dates.forEach(date => {
                const dateObj = new Date(date);
                const month = dateObj.toLocaleDateString('en-US', { month: 'long' });
                if (!months[month]) {
                    months[month] = [];
                }
                months[month].push(date);
            });

            const table = `
                <table id="myTable" class="table table-bordered card-table table-vcenter text-nowrap datatable">
                    <thead>
                        <!-- Empty Headers for Room Type and Room No -->
                                    <tr id="dailyOccupancyRow">
                            <th colspan="2">Daily Occupancy Graph</th>
                            ${dates.map(() => `<th class="occupancy-cell"></th>`).join('')}
                        </tr>

                        <tr id="percentageRow">
                            <th colspan="2"><strong>Daily Occupancy %</strong></th>
                            ${dates.map(() => `<th class="percentage-cell">0.00%</th>`).join('')}
                        </tr>
                        <!-- Month Headers -->
                        <tr id="monthRow">
                            <th colspan="2">Month</th>
                            ${Object.keys(months)
                                .map(month => `<th colspan="${months[month].length}" style="text-align: center;">${month}</th>`)
                                .join('')}
                        </tr>
                        <!-- Day Row -->
                        <tr id="dayRow">
         
                            <th colspan="2" style="text-align: center;">
Day

                            </th>

                            ${dates.map(date => {
                                const dayName = getDayName(new Date(date));
                                const dayNumber = date.split('-')[2];
                                const isWeekend = dayName === 'Sa' || dayName === 'Su';
                                const isToday = date === today;
                                const colorStyle = isWeekend ? 'color: red;' : '';
                                const backgroundStyle = isToday ? 'background-color: green; color: white;' : '';
                                return `
                                        <th style="${backgroundStyle}">
                                            <div style="display: flex; flex-direction: column; align-items: center;">
                                                <span style="font-weight: bold;">${date.split('-')[2]}</span>
                                                <span style="font-size: 0.6rem; ${colorStyle}">${dayName}</span>
                                            </div>
                                        </th>`;
                            }).join('')}
                        </tr>
                    </thead>
                    <tbody id="roomStatusBody"></tbody>
                </table>
            `;
            $('#roomStatusTable').html(table);
            fetchRoomStatus(dates);

        }

        function getDayName(date) {
            const daysOfWeek = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
            return daysOfWeek[date.getDay()];
        }


        function fetchRoomStatus(dates) {
            $.ajax({
                type: "POST",
                url: APP_URL + "api/room_status/get_room_status_by_date.php",
                contentType: "application/json",
                data: JSON.stringify({ start_date: dates[0], end_date: dates[dates.length - 1] }),
                dataType: 'json',
                success: function (data) {
                    console.log('API Response:', data);
                    populateRoomStatus(data, dates);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.error('Error fetching room status:', textStatus, errorThrown);
                }
            });
        }

        function populateRoomStatus(data, dates) {
            const roomStatus = {};
            const dailyOccupancy = {};  // To track occupancy for each date
            const dailyIncome = {};     // To track total income for each date

            if (!data.records || data.records.length === 0) {
                console.error('No records found in the data');
                return;
            }

            data.records.forEach(record => {
                const { reservation_no, room_no, room_type, date, name, status, room_income, from_to_date, total_days, total_amount, agent_name } = record;

                if (!roomStatus[room_no]) {
                    roomStatus[room_no] = {};
                }

                roomStatus[room_no][date] = { reservation_no, room_type, name, status, room_income, from_to_date, total_days, total_amount, agent_name };

                // Count occupied rooms for each date (include checkout)
                if (status === 'checkin' || status === 'reserve' || status === 'confirm' || status === 'checkout') {
                    if (!dailyOccupancy[date]) {
                        dailyOccupancy[date] = 0;
                    }
                    dailyOccupancy[date]++;
                }

                // Calculate total income for each date
                if (!dailyIncome[date]) {
                    dailyIncome[date] = 0;
                }
                dailyIncome[date] += parseFloat(room_income || 0); // Add income for this room
            });

            $('#roomStatusBody').empty();

            // Sort room numbers by room_type and room_no
            // const sortedRooms = Object.keys(roomStatus).sort((a, b) => {
            //     const roomA = data.records.find(record => record.room_no === a) || {};
            //     const roomB = data.records.find(record => record.room_no === b) || {};

            //     if (roomA.room_type < roomB.room_type) return -1;
            //     if (roomA.room_type > roomB.room_type) return 1;
            //     return parseInt(a) - parseInt(b); // Sort numerically by room_no
            // });
            
            const sortedRooms = Object.keys(roomStatus).sort((a, b) => {
                return parseInt(a) - parseInt(b);
            });

            let lastRoomType = null;
            let roomTypeColors = {};
            let colorIndex = 0;
            const colorPalette = ['#f0f8ff', '#e6ffe6', '#fff0f5', '#fef9e7', '#e0f7fa']; // soft background colors
            // Generate table rows in sorted order
            sortedRooms.forEach(room_no => {
                
                const roomDetails = data.records.find(record => record.room_no === room_no); // Get room details for tooltip
                
                const roomType = roomDetails.room_type || 'N/A';
                // Assign color to each room_type
                if (!roomTypeColors[roomType]) {
                    roomTypeColors[roomType] = colorPalette[colorIndex % colorPalette.length];
                    colorIndex++;
                }
                const rowBackground = roomTypeColors[roomType];
                
                const tooltip = `
                    Room No: ${room_no}
                    Room Type: ${roomDetails.room_type || 'N/A'}
                    Bed Type: ${roomDetails.bed_type || 'N/A'}
                    Max Occupancy: ${roomDetails.max_occupancy || 'N/A'}
                    Room Rate: ${roomDetails.room_rate ? `$${roomDetails.room_rate}` : 'N/A'}
                    Remark: ${roomDetails.remark || 'N/A'}
                `.trim();

                let row = `<tr>
                    <td title="${tooltip}" style="cursor: pointer;background-color: ${rowBackground};">${roomDetails.room_type || 'N/A'}</td> <!-- Room Type Column -->
                    <td title="${tooltip}" style="cursor: pointer;background-color: ${rowBackground};"><strong>${room_no}</strong></td>`;

                let i = 0;
                while (i < dates.length) {
                    const currentDate = dates[i];
                    const guestData = roomStatus[room_no][currentDate];

                    if (guestData) {
                        const { reservation_no, name, status, from_to_date, total_days, total_amount , agent_name} = guestData;

                        let span = 1;
                        while (
                            i + span < dates.length &&
                            roomStatus[room_no][dates[i + span]] &&
                            roomStatus[room_no][dates[i + span]].status === status &&
                            roomStatus[room_no][dates[i + span]].name === name &&
                            roomStatus[room_no][dates[i + span]].reservation_no === reservation_no 
                        ) {
                            span++;
                        }

                        const statusClass = status === 'checkin' ? 'status-checkin'
                            : status === 'reserve' ? 'status-reserve'
                            : status === 'confirm' ? 'status-confirm'
                            : status === 'clean' ? 'status-clean'
                            : status === 'service' ? 'status-service'
                            : status === 'checkout' ? 'status-checkout'
                            : '';

                        row += `
                            <td colspan="${span}" class="${statusClass}" style="color:white; cursor:pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 0 5px;" 
                                title="${name}" 
                                <td 
                                    onclick="showGuestDetails('${reservation_no}', '${name}', '${status}', '${currentDate}', '${room_no}', '${from_to_date}', '${total_days}', '${total_amount}', '${agent_name}', event)"
                                    style="cursor: pointer;"
                                >
                                    ${name}
                                </td>
                                data-name="${name}" data-status="${status}" data-date="${currentDate}" data-room="${room_no}">
                                ${name}
                            </td>`;
                        i += span;
                    } else {
                        row += `<td></td>`;
                        i++;
                    }
                }

                row += '</tr>';
                $('#roomStatusBody').append(row);
            });


            // Add total income row
            addIncomeRow(dailyIncome, dates);
            addOccupancyRows(dailyOccupancy, dates, totalRooms);
            // Update occupancy and percentage
            updateOccupancyPercentage(dailyOccupancy, dates);
            generateOccupancyGraph(dailyOccupancy, dates);
        }


        function addIncomeRow(dailyIncome, dates) {
            let incomeRow = `<tr id="totalIncomeRow">
                <td colspan="2"><strong>Total Income</strong></td>`; 

            dates.forEach(date => {
                const totalIncome = dailyIncome[date] || 0; // Get the total income for the date
                incomeRow += `
                    <td style="font-weight: bold; color:rgb(0, 0, 0);">
                        ${totalIncome.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </td>`;
            });

            incomeRow += `</tr>`;
            $('#roomStatusBody').append(incomeRow); // Append the income row to the table
        }


        // function generateOccupancyGraph(dailyOccupancy, dates) {
        //     const totalRooms = 22; // Adjust this value if needed

        //     // Update the percentage row
        //     $('#myTable thead tr:nth-child(4) th.percentage-cell').each(function (index) {
        //         const date = dates[index];
        //         const occupiedRooms = dailyOccupancy[date] || 0;
        //         const occupancyPercentage = ((occupiedRooms / totalRooms) * 100).toFixed(2); // Calculate percentage

        //         // Populate the percentage row
        //         $(this).text(`${occupancyPercentage}`);
        //     });

        //     // Update the occupancy bar graph
        //     $('#myTable thead tr:nth-child(1) th.occupancy-cell').each(function (index) {
        //         const date = dates[index];
        //         const occupiedRooms = dailyOccupancy[date] || 0;
        //         const occupancyPercentage = ((occupiedRooms / totalRooms) * 100).toFixed(2);

        //         // Set the content of each cell
        //         $(this).html(`
        //             <div style="display: flex; flex-direction: column; height: 100%; width: 100%; background-color: #e9ecef; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px;">
        //                 <div style="height: ${occupancyPercentage}%; background-color: #5DADE2; position: absolute; bottom: 0; left: 0; right: 0; border-top-left-radius: 5px; border-top-right-radius: 5px;"></div>
        //             </div>
        //         `);

        //         // Ensure the cell has a consistent height
        //         $(this).css({
        //             height: "60px",
        //             padding: "0",
        //             position: "relative",
        //             overflow: "hidden",
        //         });
        //     });
        // }
        
function generateOccupancyGraph(dailyOccupancy, dates) {
    const totalRooms = 22;

    // Update the percentage row (optional)
    $('#myTable thead tr:nth-child(4) th.percentage-cell').each(function (index) {
        const date = dates[index];
        const booked = dailyOccupancy[date] || 0;
        const occupancyPercentage = ((booked / totalRooms) * 100).toFixed(2);
        $(this).text(`${occupancyPercentage}`);
    });

    // Update the occupancy bar graph
    $('#myTable thead tr:nth-child(1) th.occupancy-cell').each(function (index) {
        const date = dates[index];
        const booked = dailyOccupancy[date] || 0;
        const available = totalRooms - booked;
        const occupancyPercentage = ((booked / totalRooms) * 100).toFixed(2);

        $(this).html(`
            <div style="position: relative; width: 100%; height: 100%; background-color: #e9ecef; border-top-left-radius: 5px; border-top-right-radius: 5px;">
                
                <!-- Blue booked bar -->
                <div style="
                    height: ${occupancyPercentage}%;
                    background-color: #5DADE2;
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    border-top-left-radius: 5px;
                    border-top-right-radius: 5px;
                "></div>

                <!-- Booked-Available text at top -->
                <span style="
                    position: absolute;
                    top: 2px;
                    left: 50%;
                    transform: translateX(-50%);
                    font-size: 0.75rem;
                    font-weight: bold;
                    color: #000;
                    white-space: nowrap;
                ">
                    ${booked}-${available}
                </span>
            </div>
        `);

        $(this).css({
            height: "60px",
            padding: "0",
            position: "relative",
            overflow: "hidden",
        });
    });
}





        function addOccupancyRows(dailyOccupancy, dates, totalRooms) {
            let bookedRow = `<tr id="bookedRow">
                <th colspan="2">Booked</th>`;
            let availableRow = `<tr id="availableRow">
                <th colspan="2">Available</th>`;

            dates.forEach(date => {
                const booked = dailyOccupancy[date] || 0; // Occupied rooms
                const available = totalRooms - booked;   // Available rooms

                bookedRow += `<th style="text-align: center; font-weight: bold; background-color: rgba(0, 123, 255, 0.1);">
                                ${booked}
                            </th>`;

                availableRow += `<th style="text-align: center; font-weight: bold; background-color: rgba(40, 167, 69, 0.1);">
                                ${available}
                                </th>`;
            });

            bookedRow += `</tr>`;
            availableRow += `</tr>`;

            // Append Booked and Available rows right AFTER the Daily Occupancy row (3rd row)
            // $('#myTable thead tr:nth-child(2)').after(bookedRow + availableRow);
        }

        function updateOccupancyPercentage(dailyOccupancy, dates) {
            const totalRooms = 22; // Adjust based on the total number of rooms

            $('#myTable thead tr:nth-child(2) th.percentage-cell').each(function (index) {
                const date = dates[index];
                const occupiedRooms = dailyOccupancy[date] || 0;
                const today = new Date().toISOString().split('T')[0];
                const isPastDate = new Date(date) < new Date(today);

                // If the date is in the past, include "checkout" in the occupancy count
                const occupancyPercentage = ((occupiedRooms / totalRooms) * 100).toFixed(2);

                // Display the percentage
                $(this).text(`${occupancyPercentage}`);

                // Apply styling for past dates
                if (isPastDate) {
                    $(this).css({
                        color: '#ee732f ', // Gray color for past dates
                        fontStyle: 'italic'
                    });
                }
            });
        }

        $('#nextWeek').click(() => {
            // Increment startDate by 7 days
            const newDate = new Date(startDate);
            newDate.setDate(newDate.getDate() + 7);
            startDate = newDate; // Update startDate with the new date
            createRoomStatusTable();
        });

        $('#prevWeek').click(() => {
            // Decrement startDate by 7 days
            const newDate = new Date(startDate);
            newDate.setDate(newDate.getDate() - 7);
            startDate = newDate; // Update startDate with the new date
            createRoomStatusTable();
        });
        // Delegate click for dynamically generated buttons
        $('#roomStatusTable').on('click', '#nextWeek, #prevWeek', (e) => {
            const scrollX = window.scrollX;
            const scrollY = window.scrollY;
        
            startDate.setDate(
                e.target.id === 'nextWeek' ? startDate.getDate() + 7 : startDate.getDate() - 7
            );
        
            createRoomStatusTable();
        
            // Restore scroll position
            window.scrollTo(scrollX, scrollY);
        });



        createRoomStatusTable();
    }

    let tooltip = null; // Declare the tooltip variable

    function showGuestDetails(reservation_no, name, status, date, roomNo, from_to_date, total_days,total_amount,agent_name,event) {
        const clickedCell = event.target; // Get the clicked cell

        // Stop propagation so the document click listener doesn't immediately close the tooltip
        event.stopPropagation();

        // Remove any existing tooltip
        if (tooltip) {
            tooltip.remove();
            tooltip = null;
        }

        // Create a new tooltip dynamically
        tooltip = document.createElement('div');
        tooltip.className = 'tooltip'; // Add tooltip class for styling
        tooltip.innerHTML = `
            <div class="tooltip-content">
                <strong>Reservation No:</strong> ${reservation_no}<br>
                <strong>Guest Name:</strong> ${name}<br>
                <strong>Room No:</strong> ${roomNo}<br>
                <strong>Status:</strong> ${status}<br>
                <strong>Date:</strong> ${from_to_date}<br>
                <strong>Total Days:</strong> ${total_days}<br>
                <strong>Total Amount:</strong> ${total_amount}<br>
                <strong>Agent:</strong> ${agent_name}
            </div>
            <div class="tooltip-arrow"></div>
        `;

        // Append the tooltip to the body
        document.body.appendChild(tooltip);

        // Position the tooltip near the clicked cell
        const rect = clickedCell.getBoundingClientRect();
        const tooltipWidth = tooltip.offsetWidth;
        const tooltipHeight = tooltip.offsetHeight;

        // Default positioning above the cell
        let left = rect.left + window.scrollX + rect.width / 2 - tooltipWidth / 2; // Center horizontally
        let top = rect.top + window.scrollY - tooltipHeight - 10; // Position above the cell

        // Adjust tooltip position if it's near the edges
        if (left < 0) {
            left = 10; // Prevent overflow on the left
        } else if (left + tooltipWidth > window.innerWidth) {
            left = window.innerWidth - tooltipWidth - 10; // Prevent overflow on the right
        }

        if (top < 0) {
            top = rect.top + window.scrollY + rect.height + 15; // Position below the cell if there's no space above
            tooltip.querySelector('.tooltip-arrow').style.top = '-1px'; // Move arrow to the top of the tooltip
            tooltip.querySelector('.tooltip-arrow').style.transform = 'translateX(-50%) rotate(180deg)'; // Flip the arrow
        } else {
            tooltip.querySelector('.tooltip-arrow').style.top = '102%'; // Reset the arrow position to the bottom
            tooltip.querySelector('.tooltip-arrow').style.transform = 'translateX(-50%) rotate(-180deg)'; // Reset the arrow
        }

        // Align the arrow with the center of the clicked cell
        const arrow = tooltip.querySelector('.tooltip-arrow');
        const arrowLeft = rect.left + rect.width / 2 - left - 5; // Calculate arrow position relative to tooltip
        arrow.style.left = `${arrowLeft}px`;

        // Apply the final tooltip position
        tooltip.style.left = `${left}px`;
        tooltip.style.top = `${top}px`;

        // Make the tooltip visible
        setTimeout(() => {
            if (tooltip) {
                tooltip.classList.add('visible'); // Add visible class for animation
            }
        }, 10);
    }

    // Function to hide the tooltip
    function hideTooltip() {
        if (tooltip) {
            tooltip.classList.remove('visible'); // Fade-out animation
            setTimeout(() => {
                if (tooltip) {
                    tooltip.remove(); // Remove the tooltip from the DOM
                    tooltip = null; // Reset the variable
                }
            }, 300); // Wait for fade-out animation
        }
    }

    // Listen for clicks anywhere in the document
    document.addEventListener('click', (event) => {
        // Check if the clicked element is a tooltip or a trigger element (like a <td>)
        const isTooltip = event.target.closest('.tooltip');
        const isTrigger = event.target.closest('.tooltip-trigger');


        // If the click is not on the tooltip or the trigger, hide the tooltip
        if (!isTooltip && !isTrigger) {
            console.log('Click outside tooltip or trigger, hiding tooltip.');
            if (tooltip) { // Check if tooltip is defined
                hideTooltip(); // Call the function to hide the tooltip
            } else {
                console.log('Tooltip is not defined.');
            }
        } else {
            console.log('Clicked inside tooltip or trigger.');
        }
    });

function getAllReservations() {
        var df = $("#dateFromRS").val();
        var dt = $("#dateToRS").val();
        $('#myTableRS').DataTable().destroy(); // Destroy existing DataTable instance

        let table = $('#myTableRS').DataTable({
            ajax: {
                url: APP_URL + "api/reservation/get_room_sales.php",
                method: "GET",
                dataType: "json",
                data: {
                    df: df,
                    dt: dt
                },
                dataSrc: 'records'
            },
            columns: [
                {
                    data: 0,
                    render: function(data, type, row) {
                        return `<span class="reservation-number">${data}</span>`;
                    }
                },
                { data: 1 }, 
                { data: 2 },
                { data: 3},
                { data: 4 },
                { data: 5}, 
                { data: 6}, 
                { data: 7 },
                {
                    data: 8,
                    className: 'text-nowrap text-end',
                    render: function (data, type, row) {
                        return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    }
                },
                {
                    data: 9,
                    className: 'text-nowrap text-end',
                    render: function (data, type, row) {
                        return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    }
                },
                {
                    data: 10,
                    className: 'text-nowrap text-end',
                    render: function (data, type, row) {
                        return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    }
                },
                            {
                    data: 11,
                    className: 'text-nowrap text-end',
                    render: function (data, type, row) {
                        return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    }
                },
            ],
            "order": [[5, "asc"], [6, "asc"]],
            paging: true,
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            buttons: [
                {
                    extend: 'csv',
                    text: 'Export to CSV',
                    className: 'buttons-csv',
                    filename: 'RentalSalesReport ' + df + ' to ' + dt,
                    exportOptions: {
                        columns: ':visible',
                        modifier: {
                        page: 'all',  // Include all pages
                        search: 'none' // Don't filter by search
                    }
                    }
                },
                {
                    extend: 'excel',
                    text: 'Export to Excel',
                    className: 'buttons-excel',
                    exportOptions: {
                        columns: ':visible',
                        modifier: {
                        page: 'all',  // Include all pages
                        search: 'none' // Don't filter by search
                    }
                    }
                },
                {
                    extend: 'pdf',
                    text: 'Export to PDF',
                    className: 'buttons-pdf',
                    exportOptions: {
                        columns: ':visible',
                        modifier: {
                        page: 'all',  // Include all pages
                        search: 'none' // Don't filter by search
                    }
                    }
                },
                {
                    extend: 'print',
                    text: 'Print Table',
                    className: 'buttons-print',
                    exportOptions: {
                        columns: ':visible',
                        modifier: {
                        page: 'all',  // Include all pages
                        search: 'none' // Don't filter by search
                    }
                    }
                }
            ],
            createdRow: function (row, data, dataIndex) {
                $(row).attr('data-reservation', JSON.stringify(data));
            },
            footerCallback: function (row, data, start, end, display) {
                var api = this.api();

                function getColumnTotal(index) {
                    const total = api
                        .column(index, { page: 'current' })
                        .data()
                        .reduce(function (a, b) {
                            return parseFloat(a) + parseFloat(b);
                        }, 0);
                
                    return total.toLocaleString(undefined, {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }

                $(api.column(9).footer()).html(getColumnTotal(9));
                $(api.column(10).footer()).html(getColumnTotal(10));
                $(api.column(11).footer()).html(getColumnTotal(11));
            }


        });

        
        $('#exportCSV').on('click', function() {
            table.button('.buttons-csv').trigger();
        });

        $('#exportExcel').on('click', function() {
            table.button('.buttons-excel').trigger();
        });

        $('#exportPDF').on('click', function() {
            table.button('.buttons-pdf').trigger();
        });

        $('#printTable').on('click', function() {
            table.button('.buttons-print').trigger();
        });
    }
 
 function getAllReservationsRAS() {
    var df = $("#dateFromRAS").val();
    var dt = $("#dateToRAS").val();
    var status = $("#cboStatusRAS").val();
    var balance = $("#cboBalanceRAS").val();
    $('#myTableRAS').DataTable().destroy(); // Destroy existing DataTable instance

    let table = $('#myTableRAS').DataTable({
        ajax: {
            url: APP_URL + "api/reservation/get_today_reservation_stay.php",
            method: "GET",
            dataType: "json",
            data: {
                df: df,
                dt: dt,
                status: status,
                balance: balance
            },
            dataSrc: 'records'
        },
        columns: [
            {
                data: 0, // Reservation Number
                // render: function(data, type, row) {
                //     return `<span class="reservation-number" style="color: blue;cursor:pointer;">${data}</span>`;
                // }
            },
            { data: 1 }, 
            { data: 2 }, 
            { data: 3 }, 
            { data: 4 },
            { data: 5 }, 
            { data: 6,
                className: "text-center", // center the content
                render: function(data, type, row) {
                    return data == 1 
                        ? '<span style="font-size: 1.5rem; color: green;">✓</span>' 
                        : '';
                }
            }, 
            { data: 7,
                className: "text-center", // center the content
                render: function(data, type, row) {
                    return data == 1 
                        ? '<span style="font-size: 1.5rem; color: green;">✓</span>' 
                        : '';
                }
            },
            { data: 8, className: "text-end" },
            {
                data: 9,
                className: 'text-nowrap text-end',
                render: function (data, type, row) {
                    return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                }
            },
            {
                data: 10,
                className: 'text-nowrap text-end',
                render: function (data, type, row) {
                    return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                }
            },
            {
                data: 11,
                className: 'text-nowrap text-end',
                render: function (data, type, row) {
                    return data == 0 ? 0 : Number(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                }
            },
            { data: 12, className: "text-end" },
            { data: 13, className: "text-end"},
            { data: 14, className: "text-end"}
            // {
            //     data: null, className: "text-end",
            //     render: function (data, type, row) {

            //         return `
            //             <div class="btn-group">
            //                 <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
            //                     Actions
            //                 </button>
            //                 <ul class="dropdown-menu">
            //                     <li>
            //                         <a class="dropdown-item" href="#" onclick="deposit('${row[0]}', '${row[5]}')">Deposit</a>
            //                     </li>
                                
            //                 </ul>
            //             </div>
            //         `;
            //     }
            // }
        ],
        "order": [[5, "asc"], [6, "asc"]],
        paging: true,
        // scrollX: true,
        // scrollY: false,
        // language: {
        //     emptyTable: "No reservations found",
        //     info: "Showing _START_ to _END_ of _TOTAL_ entries",
        //     lengthMenu: "Show _MENU_ entries",
        //     search: "Search:",
        //     zeroRecords: "No matching records found"
        // },
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        buttons: [
            {
                extend: 'csv',
                text: 'Export to CSV',
                className: 'buttons-csv',
                filename: 'ReservationAndStayReport ' + df + ' to ' + dt,
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'excel',
                text: 'Export to Excel',
                className: 'buttons-excel',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'pdf',
                text: 'Export to PDF',
                className: 'buttons-pdf',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'print',
                text: 'Print Table',
                className: 'buttons-print',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            }
        ],
        createdRow: function (row, data, dataIndex) {
            $(row).attr('data-reservation', JSON.stringify(data));
        },
        footerCallback: function (row, data, start, end, display) {
            var api = this.api();

            function getColumnTotal(index) {
                const total = api
                    .column(index, { page: 'current' })
                    .data()
                    .reduce(function (a, b) {
                        return parseFloat(a) + parseFloat(b);
                    }, 0);
            
                return total.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            }


            $(api.column(8).footer()).html(getColumnTotal(8));
            $(api.column(9).footer()).html(getColumnTotal(9));
            $(api.column(10).footer()).html(getColumnTotal(10));
            $(api.column(11).footer()).html(getColumnTotal(11));
            // $(api.column(11).footer()).html(getColumnTotal(11));
        }
    });

    // Handle reservation details modal
    // $('#myTable tbody').on('click', 'td:nth-child(1)', function () {
    //     const row = $(this).closest('tr');
    //     const data = JSON.parse(row.attr('data-reservation'));

    //     $('#reservationNoD').text(data[0]);
    //     $('#folioNoD').text(data[1]);
    //     $('#agentNameD').text(data[2]);
    //     $('#guestNameD').text(data[3]);
    //     $('#adultChildD').text(data[4]);
    //     $('#roomNoD').text(data[5]);
    //     $('#checkInDateD').text(data[6]);
    //     $('#checkOutDateD').text(data[7]);
    //     $('#dateTimeD').text(data[15]);
    //     $('#remarkD').text(data[11]);

    //     const items = data[17];
    //     const itemsTableBody = $('#reservationItemsTable tbody');
    //     itemsTableBody.empty();

    //     let netTotal = 0;
    //     items.forEach(item => {
    //         const rowHtml = `
    //             <tr>
    //                 <td>${item.date}</td>
    //                 <td>${item.room_no}</td>
    //                 <td>${item.room_rate}</td>
    //                 <td>${item.extra_bed}</td>
    //                 <td>${item.extra_bed_rate}</td>
    //                 <td>${item.extra_person}</td>
    //                 <td>${item.extra_person_rate}</td>
    //                 <td>${item.total}</td>
    //             </tr>`;
    //         itemsTableBody.append(rowHtml);
    //         netTotal += parseFloat(item.total);
    //     });
    //     $('#netTotalD').text(netTotal.toFixed(2));
    //     $('#detailModal').modal('show');
    // });

    $('#exportCSVRAS').on('click', function() {
        table.button('.buttons-csv').trigger();
    });

    $('#exportExcelRAS').on('click', function() {
        table.button('.buttons-excel').trigger();
    });

    $('#exportPDFRAS').on('click', function() {
        table.button('.buttons-pdf').trigger();
    });

    $('#printTableRAS').on('click', function() {
        table.button('.buttons-print').trigger();
    });
    
    

}

</script>

