<script>
    document.addEventListener('DOMContentLoaded', function() {
    // Document filter functionality with dropdown
    const documentTypeFilter = document.getElementById('document_type_filter');

    if (documentTypeFilter) {
        documentTypeFilter.addEventListener('change', function() {
            // Update URL with filter parameter
            const url = new URL(window.location);

            if (this.value !== 'all') {
                url.searchParams.set('document_type', this.value);
            } else {
                url.searchParams.delete('document_type');
            }

            window.location = url.toString();
        });
    }

    // Document type color mapping
    const documentTypeColors = {
        'amdal': 'info',
        'pertek': 'success',
        'andal_rkl_rpl': 'warning',
        'addendum': 'primary',
        'dplh': 'success',
        'delh': 'lilac',
        'ukl_upl': 'danger'
    };

    // Get events data from PHP backend
    const jadwalEvents = @json($jadwal ?? []);

    // Format events for fullCalendar
    const calendarEvents = jadwalEvents.map(event => {
        // If it's a holiday or special day with className already set, keep it
        if (event.className) {
            return event;
        }

        // Otherwise, set className based on document type
        return {
            ...event,
            className: documentTypeColors[event.documentType] || 'primary'
        };
    });

    // Render the events list in the sidebar
    renderEventList(jadwalEvents);

    // Initialize the calendar with filtered events
    var calendar = $("#calendar").fullCalendar({
        header: {
            left: "title",
            center: "agendaDay,agendaWeek,month",
            right: "prev,next today",
        },
        editable: true,
        firstDay: 1,
        selectable: true,
        defaultView: "month",
        axisFormat: "h:mm",
        columnFormat: {
            month: "ddd",
            week: "ddd d",
            day: "dddd M/d",
            agendaDay: "dddd d",
        },
        titleFormat: {
            month: "MMMM yyyy",
            week: "MMMM yyyy",
            day: "MMMM yyyy",
        },
        allDaySlot: false,
        selectHelper: true,
        // Use the events from JSON
        events: calendarEvents,
        eventClick: function(event) {
            // When an event is clicked, show details in modal
            $('#exampleModalView').modal('show');
            // Populate modal with event details
            $('#exampleModalView .modal-title').text('Detail Jadwal');
            $('#exampleModalView .modal-body').find('h6').eq(0).text(event.title);
            $('#exampleModalView .modal-body').find('h6').eq(1).text(formatEventDate(event.start));
            $('#exampleModalView .modal-body').find('h6').eq(2).text(event.end ? formatEventDate(event.end) : 'N/A');
            $('#exampleModalView .modal-body').find('h6').eq(3).text(event.description || 'N/A');

            // Set document type indicator color and text
            const docTypeElement = $('#exampleModalView .modal-body').find('h6').eq(4);
            if (event.documentType) {
                const colorClass = `bg-${documentTypeColors[event.documentType]}-600`;
                docTypeElement.html(`<span class="w-8-px h-8-px ${colorClass} rounded-circle"></span> ${getDocumentTypeName(event.documentType)}`);
            } else {
                docTypeElement.text('N/A');
            }
        }
    });

    // Function to render event list in sidebar
function renderEventList(events) {
const eventListContainer = document.querySelector('.mt-32');
if (!eventListContainer) return;

// Clear existing events
eventListContainer.innerHTML = '';

// Add filtered events (skip holidays or events with className="important")
const filteredEvents = events.filter(event => !event.className || event.className !== 'important');

// Pagination setup
const eventsPerPage = 5;
const urlParams = new URLSearchParams(window.location.search);
const currentPage = parseInt(urlParams.get('page')) || 1;
const totalPages = Math.ceil(filteredEvents.length / eventsPerPage);
const startIndex = (currentPage - 1) * eventsPerPage;
const endIndex = startIndex + eventsPerPage;
const paginatedEvents = filteredEvents.slice(startIndex, endIndex);

if (filteredEvents.length > 0) {
// Render events for current page
paginatedEvents.forEach(event => {
const eventItem = document.createElement('div');
eventItem.className = 'event-item d-flex align-items-center justify-content-between gap-4 pb-16 mb-16 border border-start-0 border-end-0 border-top-0';

// Format date to "20 Maret 2025, 14:00 - 15:00" style
const formatAsCustom = (date) => {
const d = new Date(date);
if (isNaN(d)) return '';

// Get day, month name in Indonesian, year
const day = d.getDate();
const monthNames = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
const month = monthNames[d.getMonth()];
const year = d.getFullYear();

// Get hours and minutes with leading zeros
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');

return `${day} ${month} ${year}, ${hours}:${minutes}`;
};

const dateDisplay = event.end ?
`${formatAsCustom(event.start)} - ${new Date(event.end).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'})}` :
formatAsCustom(event.start);

const colorClass = event.documentType ? documentTypeColors[event.documentType] : 'primary';

eventItem.innerHTML = `
<div class="d-flex flex-column">
    <div class="d-flex flex-column gap-10">
        <div class="mt-2">
            <span class="badge bg-${colorClass}-100 text-${colorClass}-600 fw-medium radius-4 text-xs px-8 py-4">
                ${getDocumentTypeName(event.documentType)}
            </span>
        </div>
        <span class="text-secondary-light text-sm">${dateDisplay}</span>
    </div>
    <span class="text-primary-light fw-bold text-md mt-4 text-uppercase">${event.title}</span>
</div>
<div class="dropdown">
    <button type="button" data-bs-toggle="dropdown" aria-expanded="false">
        <iconify-icon icon="entypo:dots-three-vertical" class="icon text-secondary-light"></iconify-icon>
    </button>
    <ul class="dropdown-menu p-12 border bg-base shadow">
        <li>
            <button type="button" class="dropdown-item px-16 py-8 rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900 d-flex align-items-center gap-10"
                data-bs-toggle="modal" data-bs-target="#exampleModalView" data-event-id="${event.id}">
                <iconify-icon icon="hugeicons:view" class="icon text-lg line-height-1"></iconify-icon>
                View
            </button>
        </li>
        <li>
            <button type="button" class="dropdown-item px-16 py-8 rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900 d-flex align-items-center gap-10"
                data-bs-toggle="modal" data-bs-target="#exampleModalEdit" data-event-id="${event.id}">
                <iconify-icon icon="lucide:edit" class="icon text-lg line-height-1"></iconify-icon>
                Edit
            </button>
        </li>
        <li>
            <button type="button" class="delete-item dropdown-item px-16 py-8 rounded text-secondary-light bg-hover-danger-100 text-hover-danger-600 d-flex align-items-center gap-10"
                data-bs-toggle="modal" data-bs-target="#exampleModalDelete" data-event-id="${event.id}">
                <iconify-icon icon="fluent:delete-24-regular" class="icon text-lg line-height-1"></iconify-icon>
                Delete
            </button>
        </li>
    </ul>
</div>
`;

eventListContainer.appendChild(eventItem);
});

// Add pagination controls if needed
if (totalPages > 1) {
const paginationContainer = document.createElement('div');
paginationContainer.className = 'pagination-container mt-16 d-flex justify-content-center align-items-center gap-2';

// Generate pagination HTML
let paginationHTML = '';

// Previous button
paginationHTML += `<button class="btn btn-sm ${currentPage === 1 ? 'btn-outline-secondary disabled' : 'btn-outline-primary'}"
                ${currentPage === 1 ? 'disabled' : `onclick="changePage(${currentPage - 1})"`}>
                <iconify-icon icon="mdi:chevron-left" class="icon"></iconify-icon>
            </button>`;

// Page buttons
const maxVisiblePages = 5;
const halfVisiblePages = Math.floor(maxVisiblePages / 2);

let startPage = Math.max(1, currentPage - halfVisiblePages);
let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

if (endPage - startPage + 1 < maxVisiblePages) {
startPage = Math.max(1, endPage - maxVisiblePages + 1);
}

// First page
if (startPage > 1) {
paginationHTML += `<button class="btn btn-sm ${1 === currentPage ? 'btn-primary' : 'btn-outline-primary'}"
                    onclick="changePage(1)">1</button>`;

if (startPage > 2) {
    paginationHTML += `<span class="pagination-ellipsis">...</span>`;
}
}

// Page numbers
for (let i = startPage; i <= endPage; i++) {
paginationHTML += `<button class="btn btn-sm ${i === currentPage ? 'btn-primary' : 'btn-outline-primary'}"
                    onclick="changePage(${i})">${i}</button>`;
}

// Last page
if (endPage < totalPages) {
if (endPage < totalPages - 1) {
    paginationHTML += `<span class="pagination-ellipsis">...</span>`;
}

paginationHTML += `<button class="btn btn-sm ${totalPages === currentPage ? 'btn-primary' : 'btn-outline-primary'}"
                    onclick="changePage(${totalPages})">${totalPages}</button>`;
}

// Next button
paginationHTML += `<button class="btn btn-sm ${currentPage === totalPages ? 'btn-outline-secondary disabled' : 'btn-outline-primary'}"
                ${currentPage === totalPages ? 'disabled' : `onclick="changePage(${currentPage + 1})"`}>
                <iconify-icon icon="mdi:chevron-right" class="icon"></iconify-icon>
            </button>`;

paginationContainer.innerHTML = paginationHTML;
eventListContainer.appendChild(paginationContainer);
}
} else {
// If no events match filter
const noEventsMsg = document.createElement('div');
noEventsMsg.className = 'text-center text-secondary-light py-16';
noEventsMsg.textContent = 'Tidak ada jadwal untuk ditampilkan';
eventListContainer.appendChild(noEventsMsg);
}
}

// Add this function outside the DOMContentLoaded listener scope
function changePage(page) {
const url = new URL(window.location);
url.searchParams.set('page', page);
window.location = url.toString();
}

// Helper function to format event date
function formatEventDate(dateString) {
    const date = new Date(dateString);
    if (isNaN(date)) return dateString;

    const options = {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
    };

    // If not all-day event, include time
    if (dateString.includes('T')) {
        options.hour = '2-digit';
        options.minute = '2-digit';
    }

    return date.toLocaleDateString('id-ID', options);
}

// Helper function to get display name for document type
function getDocumentTypeName(type) {
    const types = {
        'amdal': 'AMDAL',
        'pertek': 'PERTEK',
        'andal_rkl_rpl': 'ANDAL RKL-RPL',
        'addendum': 'ADDENDUM',
        'dplh': 'DPLH',
        'delh': 'DELH',
        'ukl_upl': 'UKL-UPL'
    };
    return types[type] || type || 'N/A';
}
});

</script>
