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


<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 */
    }


</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' => 'arrival', 'title' => 'Arrivals'],
                ['id' => 'departure', 'title' => 'Departures'],
                ['id' => 'onboard', 'title' => 'On Board'],
                // ['id' => 'expense', 'title' => 'Expense'],
                // ['id' => 'income', 'title' => '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="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="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>

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



                <div id="roomStatusTable" class="table-responsive 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>

    <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">
                        <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: 200px;">
                        <table class="table table-vcenter card-table table-sm table-striped" id="myTableCB" 
                            style="font-size: 11px; 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>
    </div>



    <!-- <div class="modal fade" id="guestDetailsModal" tabindex="-1" role="dialog" aria-labelledby="guestDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="guestDetailsModalLabel">Guest Details</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div> -->

    
</div>

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

<script>
    	var today = new Date().toISOString().split('T')[0];
        $(function() {

            ["reservation","arrival", "departure", "onboard", "expense", "income", "room_income", "osc_income"].forEach(id => {
                getData(id, 'today');
                $(`#${id}`).closest(".card-body").find("button:contains('Today')").addClass("btn-active");
            });
            flatpickr("#dateFrom", {
                dateFormat: "Y-m-d",
                defaultDate: today, // Set to first day of the current month
                maxDate: today,               // Restrict selection to today or earlier
            });
            flatpickr("#dateTo", {
                dateFormat: "Y-m-d", 
                defaultDate: today,  
                maxDate: today,      
            });
            getMonthly();
            loadCalender();
        });

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

        // Fetch data dynamically
        $.ajax({
            url: APP_URL + `api/utils/get_${cardId}.php`,
            method: "POST",
            data: JSON.stringify({ type: dateType }),
            success: function(data) {
                let output = `${data[cardId]}`;
                $(`#${cardId}`).text(output);
            },
            error: function() {
                $(`#${cardId}`).text(0.00);
            }
        });
    }

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

	var BAL = 0 ;
	var COL = "" ;
    function getMonthly(){
		var df =$("#dateFrom").val();
		var dt =$("#dateTo").val();
		$("#myTableCB").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";
				$("#myTableCB").find("tbody")
				.append($('<tr>')
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + v.cash_in + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;' >" + v.cash_in + "</td>")
					.append("<td></td>")
                    .append("<td></td>")
					)
			});	
              $.each(data.records_out, function(i, v) {
				var s="Out";

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


			$("#myTableCB").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)?data.cash_in_total:0) + "</td>")
			.append("<td style='text-align:left;'>Total</td>")
			.append("<td style='text-align:right;'>" + ((data.cash_out_total)?data.cash_out_total:0) + "</td>")
  			); 

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

            $("#myTableCB").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)?data.cash_balance: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;'>" + v.amount + "</td>")
                        )
                });
                $("#mdtitle1").text(data.total_amountF);
        });		
    }

    // 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;
        const totalRooms = 16;  // 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>
                            <th colspan="2"></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">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 { room_no, room_type, date, name, status, room_income } = record;

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

                roomStatus[room_no][date] = { room_type, name, status, room_income };

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

            // 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 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>${roomDetails.room_type || 'N/A'}</td> <!-- Room Type Column -->
                    <td title="${tooltip}" style="cursor: pointer;"><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 { name, status } = 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
                        ) {
                            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('${name}', '${status}', '${currentDate}', '${room_no}', 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.toFixed(2)}
                    </td>`;
            });

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


        function generateOccupancyGraph(dailyOccupancy, dates) {
            const totalRooms = 16; // 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 addOccupancyRows(dailyOccupancy, dates, totalRooms) {
            let bookedRow = `<tr id="bookedRow">
                <td colspan="2">Booked</td>`;
            let availableRow = `<tr id="availableRow">
                <td colspan="2">Available</td>`;

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

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

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

            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 = 16; // 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();
        });

        createRoomStatusTable();
    }

    let tooltip = null; // Declare the tooltip variable

    function showGuestDetails(name, status, date, roomNo, 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>Guest Name:</strong> ${name}<br>
                <strong>Room No:</strong> ${roomNo}<br>
                <strong>Status:</strong> ${status}<br>
                <strong>Date:</strong> ${date}
            </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) => {
        const isTooltip = event.target.closest('.tooltip');
        const isTrigger = event.target.closest('td'); // Check if the clicked element is a table cell
        if (!isTooltip && !isTrigger && tooltip) {
            hideTooltip(); // Close the tooltip if the click is outside
        }
    });


</script>

