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

<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">Monthly Status</h2>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>
<div class="page-body">
        
    <div class="container-xl">
        <div class="card" style="height: 570px;">
            <div class="card-body">
                <div class="calendar-container text-center">
                    <div class="d-flex justify-content-between" style="margin-top: 10px;">
                        
                        <div style="display: flex; gap: 20px; justify-content: left;">
                            <div style="display: flex; align-items: center;">
                                <div style="width: 20px; height: 20px; background-color: #28a745; margin-right: 5px;border-radius: 3px;"></div>
                                <span>Active Rental</span>
                            </div>
                            <div style="display: flex; align-items: center;">
                                <div style="width: 20px; height: 20px; background-color: #007bff; margin-right: 5px;border-radius: 3px;"></div>
                                <span>Booked</span>
                            </div>
                            <div style="display: flex; align-items: center;">
                                <div style="width: 20px; height: 20px; background-color: #6f42c1; margin-right: 5px;border-radius: 3px;"></div>
                                <span>Confirmed Booking</span>
                            </div>
                            <div style="display: flex; align-items: center;">
                                <div style="width: 20px; height: 20px; background-color: #1f4e79; margin-right: 5px;border-radius: 3px;"></div>
                                <span>Available</span>
                            </div>
                            <div style="display: flex; align-items: center;">
                                <div style="width: 20px; height: 20px; background-color: #dc3545; margin-right: 5px;border-radius: 3px;"></div>
                                <span>Out of Service</span>
                            </div>
                            <div style="display: flex; align-items: center;">
                                <div style="width: 20px; height: 20px; background-color: #ffc107; margin-right: 5px;border-radius: 3px;"></div>
                                <span>Free</span>
                            </div>
                        </div>
                        <div class="calendar-controls" style="position: relative; display: flex; justify-content: center; align-items: center; margin-bottom: 20px;">
                            <span id="prevMonth" style="font-size: 24px; cursor: pointer; font-weight: bold; position: fix; left: 30px;"><i class="fa-solid fa-caret-left"></i></span>
                            <span id="currentMonth" class="mx-3" style="font-size: 24px; text-align: center;width:220px;font-weight: 700;"></span>
                            <span id="nextMonth" style="font-size: 24px; cursor: pointer; font-weight: bold; position: fix; right: 30px;"><i class="fa-solid fa-caret-right"></i></span>
                        </div>
                    </div>
                    <div id="calendar" class="mt-5"></div>
                </div>
            </div>
        </div>
        <!-- Modal -->
        <div class="modal fade" id="roomDetailModal" tabindex="-1" aria-labelledby="roomDetailModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <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>
    let currentMonth = new Date().getMonth() + 1; // JavaScript months are 0-based
    let currentYear = new Date().getFullYear();

    $(document).ready(function() {
        loadCalendarData(currentMonth, currentYear);

        $('#prevMonth').click(function() {
            if (currentMonth === 1) {
                currentMonth = 12;
                currentYear--;
            } else {
                currentMonth--;
            }
            loadCalendarData(currentMonth, currentYear);
        });

        $('#nextMonth').click(function() {
            if (currentMonth === 12) {
                currentMonth = 1;
                currentYear++;
            } else {
                currentMonth++;
            }
            loadCalendarData(currentMonth, currentYear);
        });
    });

    function loadCalendarData(month, year) {
        const startDate = `${year}-${('0' + month).slice(-2)}-01`;
        const endDate = `${year}-${('0' + month).slice(-2)}-${new Date(year, month, 0).getDate()}`;

        $('#currentMonth').text(new Date(year, month - 1).toLocaleString('default', { month: 'long', year: 'numeric' }));

        $.ajax({
            type: "POST",
            url: APP_URL + "api/room_status/get_room_count_by_date.php",
            data: JSON.stringify({ s: startDate, e: endDate }),
            contentType: "application/json",
            success: function(data) {
                populateRoomStatusCount(data.records, data.total_rooms, month, year);
            },
            error: function(error) {
                console.error("Error fetching room data: ", error);
            }
        });
    }

    function populateRoomStatusCount(records, total_rooms, month, year) {
    const calendarHTML = createCalendar(month, year, records, total_rooms);
    $('#calendar').html(calendarHTML);
}

function createCalendar(month, year, records, total_rooms) {
    const daysInMonth = new Date(year, month, 0).getDate();
    const firstDayOfMonth = new Date(year, month - 1, 1).getDay();
    const today = new Date().toISOString().slice(0, 10); // Get today's date in YYYY-MM-DD format

    const statusColors = {
        "Occupied": "#28a745",
        "Reserved": "#007bff",
        "Clean": "#1f4e79",
        "Vacant": "#ffc107",
        "Confirm": "#6f42c1",
        "Service": "#dc3545"
    };

    let calendarHTML = `
        <div style="display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; width: 100%; height: 50%;">
            <div style="text-align: center; font-weight: bold; color: red;">Sun</div>
            <div style="text-align: center; font-weight: bold;">Mon</div>
            <div style="text-align: center; font-weight: bold;">Tue</div>
            <div style="text-align: center; font-weight: bold;">Wed</div>
            <div style="text-align: center; font-weight: bold;">Thu</div>
            <div style="text-align: center; font-weight: bold;">Fri</div>
            <div style="text-align: center; font-weight: bold; color: red;">Sat</div>
    `;

    for (let i = 0; i < firstDayOfMonth; i++) {
        calendarHTML += `<div></div>`;
    }

    for (let day = 1; day <= daysInMonth; day++) {
        const date = `${year}-${('0' + month).slice(-2)}-${('0' + day).slice(-2)}`;
        const recordsForDay = records.filter(record => record.date === date);
        const dayOfWeek = new Date(year, month - 1, day).getDay();

        const todayStyle = date === today ? 'background-color: #efffe9;border-color: black;color: green;' : '';

        let counts = {
            checkin: 0,
            confirm: 0,
            reserve: 0,
            clean: 0,
            service: 0
        };

        recordsForDay.forEach(record => {
            if (record.reservation_status.toLowerCase() in counts) {
                counts[record.reservation_status.toLowerCase()] += parseInt(record.no_of_room);
            }
        });

        const occupiedCount = counts.checkin;
        const vacantCount = total_rooms - (counts.reserve + counts.confirm + counts.checkin + counts.service + counts.clean);

        let dayDiv = `<div style="position: relative; text-align: center; border: 0.1px solid #ddd; height: 68px; padding: 5px; color: ${dayOfWeek === 0 || dayOfWeek === 6 ? 'red' : ''}; ${todayStyle}" class="calendar-day" data-date="${date}">`;
        dayDiv += `<div style="font-size: 23px; font-weight: bold; margin-bottom: 5px;">${day}</div>`;
        dayDiv += `<div style="position: absolute; bottom: 5px; left: 10px; display: flex; flex-wrap: wrap;">`;

        const statuses = [
            { label: 'Active Rental', count: occupiedCount, color: statusColors.Occupied },
            { label: 'Booked', count: counts.reserve, color: statusColors.Reserved },
            { label: 'Confirmed Booking', count: counts.confirm, color: statusColors.Confirm },
            { label: 'Available', count: counts.clean, color: statusColors.Clean },
            { label: 'Service', count: counts.service, color: statusColors.Service },
            { label: 'Free', count: vacantCount, color: statusColors.Vacant }
        ];

        statuses.forEach(({ label, count, color }) => {
            if (count > 0) {
                dayDiv += `<div style="width: 23px; height: 23px; background-color: ${color}; color: white; display: flex; justify-content: center; align-items: center; border-radius: 3px; margin-right: 3px; margin-bottom: 3px;">${count}</div>`;
            }
        });

        dayDiv += '</div></div>';
        calendarHTML += dayDiv;
    }

    calendarHTML += '</div>';
    return calendarHTML;
}




    function showRoomDetails(date, records) {
        const roomsForDate = records.filter(record => record.date === date);
        let detailsHTML = `<h3>Vehicle Details for ${date}</h3>`;
        
        if (roomsForDate.length > 0) {
            roomsForDate.forEach(record => {
                detailsHTML += `
                    <div>
                        <strong>Status:</strong> ${record.reservation_status} <br>
                        <strong>Active Vehicles:</strong> ${record.no_of_room} <br>
                    </div>
                `;
            });
        } else {
            detailsHTML += `<p>No data available for this date.</p>`;
        }

        $('#roomDetailsContent').html(detailsHTML);
        $('#roomDetailModal').modal('show');
    }
</script>


