<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<style>
    .table-responsive {
        margin: 20px 0;
    }

    .btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: bold;
    }

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

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

    th, td {
        padding: 12px;
        text-align: center;
        vertical-align: middle;
        border: 1px solid #e0e0e0;
        word-wrap: break-word;
        max-width: 100px;
        overflow: hidden;
    }

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

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

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

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

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

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

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


    .name-cell {
        white-space: nowrap; /* Prevent text from breaking into multiple lines */
        overflow: hidden; /* Hide overflow */
        text-overflow: ellipsis; /* Add ellipsis when text overflows */
        width: 60px; /* Fixed width for each cell */
        display: block;
        text-align: center;
    }

    td {
        width: 60px; /* Fixed width for each table cell */
        max-width: 60px;
        text-align: center;
    }

    th {
        text-align: center;
        width: 60px; /* Fixed width for each table header */
    }



</style>
<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col">
                <h2 class="page-title ">Weekly Vehicle Status</h2>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>
<div class="page-body">
    <div class="container-xl">
        <div class="card shadow-lg">
            <div class="card-body">
                <!-- Navigation Buttons for Week and Month -->
                <div class="d-flex justify-content-between mb-4">
                    <!-- <button id="prevWeek" class="btn btn-outline-primary shadow-sm">Prev Week</button> -->
                    <button id="prevMonth" class="btn btn-outline-primary shadow-sm">Prev Month</button>
                    <h4 id="monthLabel" class="text-secondary fw-bold"></h4>
                    <button id="nextMonth" class="btn btn-outline-primary shadow-sm">Next Month</button>
                    <!-- <button id="nextWeek" class="btn btn-outline-primary shadow-sm">Next Week</button> -->
                </div>

                <!-- Vehicle status table will be generated here -->
                <div id="roomStatusTable" class="table-responsive rounded-3">
                    <!-- Vehicle status table will be dynamically created here -->
                </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">Vehicle 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>

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



<script>
    $(document).ready(function() {
        let currentDate = new Date();
        let startDate = currentDate;

        function getNextMonth(start) {
            const dates = [];
            const newStartDate = new Date(start);
            newStartDate.setDate(1); // Set to the first of the current month

            // Loop through 30 (or 31) days for a full month
            while (newStartDate.getMonth() === start.getMonth()) {
                const date = new Date(newStartDate);
                dates.push(date.toISOString().split('T')[0]);
                newStartDate.setDate(newStartDate.getDate() + 1);
            }
            return dates;
        }

        function updateMonthLabel(start) {
            const options = { month: 'long', year: 'numeric' };
            const monthLabel = start.toLocaleDateString('en-US', options);  // Correct the format to "December 2024"
            $('#monthLabel').text(monthLabel);  // Display the month and year
        }

        function createRoomStatusTable() {
            const dates = getNextMonth(startDate);
            const table = `
                <table id="myTable" class="table table-bordered card-table table-vcenter text-nowrap datatable">
                    <thead>
                        <tr>
                            <th>Vehicle No.</th>
                            ${dates.map(date => `<th>${date.split('-')[2]} (${getDayName(new Date(date))})</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody id="roomStatusBody"></tbody>
                </table>
            `;
            $('#roomStatusTable').html(table);
            fetchRoomStatus(dates);
            updateMonthLabel(startDate);
        }

        function getDayName(date) {
            const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
            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 = {};

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

            data.records.forEach(record => {
                const { room_no, date, name, status } = record;

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

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

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

            for (let room_no in roomStatus) {
                let row = `<tr><td><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
                        ) {
                            span++;
                        }

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

                        row += `
                            <td colspan="${span}" class="${statusClass}" style="color:white; cursor:pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 0 5px;" 
                                title="${name}" 
                                onclick="showFullName('${name}')"
                                data-name="${name}">
                                ${name}
                            </td>`;
                        i += span;
                    } else {
                        row += `<td></td>`;
                        i++;
                    }
                }

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

            adjustNamesForWidth();
        }

        function adjustNamesForWidth() {
            $('#roomStatusBody td').each(function () {
                const cell = $(this);
                const name = cell.data('name');
                if (name) {
                    const cellWidth = cell.width(); // Get the width of the cell
                    const textWidth = getTextWidth(name, cell.css('font')); // Get the width of the name

                    if (textWidth > cellWidth) {
                        // Truncate the name if it doesn't fit
                        let truncatedName = name;
                        while (getTextWidth(truncatedName + '...', cell.css('font')) > cellWidth && truncatedName.length > 0) {
                            truncatedName = truncatedName.slice(0, -1);
                        }
                        cell.html(truncatedName + '...'); // Add ellipsis
                    } else {
                        cell.html(name); // Use full name if it fits
                    }
                }
            });
        }

        function getTextWidth(text, font) {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            context.font = font || '16px Arial';
            return context.measureText(text).width;
        }

        function nextMonth() {
            startDate.setMonth(startDate.getMonth() + 1);
            createRoomStatusTable();
        }

        function prevMonth() {
            startDate.setMonth(startDate.getMonth() - 1);
            createRoomStatusTable();
        }

        function nextWeek() {
            startDate.setDate(startDate.getDate() + 7);
            createRoomStatusTable();
        }

        function prevWeek() {
            startDate.setDate(startDate.getDate() - 7);
            createRoomStatusTable();
        }

        $('#nextMonth').click(nextMonth);
        $('#prevMonth').click(prevMonth);
        $('#nextWeek').click(nextWeek);
        $('#prevWeek').click(prevWeek);

        createRoomStatusTable();
    });

    function showFullName(name) {
        // Show the full name in the modal
        $('#roomDetailsContent').html(`<p class="text-center">${name}</p>`);
        // Open the modal
        $('#roomDetailModal').modal('show');
    }
</script>
