// Notice Page JavaScript - Table Format with Department Filter

let API_BASE_URL;
let currentDepartment = 'all';
let allNotices = [];
let allDepartments = [];

// Wait for DOM to be fully ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initNoticePage);
} else {
    // DOM is already ready
    initNoticePage();
}

function initNoticePage() {
    // Set API_BASE_URL
    API_BASE_URL = window.API_BASE_URL || (window.location.origin + '/admin/public/api');
    
    // Ensure elements exist before proceeding
    const tbody = document.getElementById('notices-tbody');
    if (!tbody) {
        console.error('Notice page elements not found. Waiting...');
        setTimeout(initNoticePage, 200);
        return;
    }
    
    // Load notices
    loadNotices();
    
    // Department filter button click handler (delegation)
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('department-btn') || e.target.closest('.department-btn')) {
            const btn = e.target.classList.contains('department-btn') ? e.target : e.target.closest('.department-btn');
            const department = btn.getAttribute('data-department');
            if (department) {
                filterByDepartment(department);
            }
        }
    });
}

async function loadNotices(department = 'all') {
    const tbody = document.getElementById('notices-tbody');
    
    if (!tbody) {
        console.error('notices-tbody element not found');
        return;
    }
    
    tbody.innerHTML = `
        <tr>
            <td colspan="4" class="px-6 py-12 text-center">
                <i class="fas fa-spinner fa-spin text-4xl text-blue-600 mb-4"></i>
                <p class="text-gray-600">Loading notices...</p>
            </td>
        </tr>
    `;

    try {
        // Always load all notices first to get departments list
        const response = await fetch(`${API_BASE_URL}/notices`);
        const data = await response.json();

        if (data.success && data.data) {
            allNotices = data.data;
            allDepartments = data.departments || [];
            
            // Update department filter buttons (only once)
            if (department === 'all') {
                updateDepartmentFilter();
            }
            
            // Filter notices by department
            let filteredNotices = allNotices;
            if (department !== 'all') {
                filteredNotices = allNotices.filter(notice => notice.department === department);
            }
            
            // Display notices in table format
            if (filteredNotices.length > 0) {
                displayNoticesTable(filteredNotices);
            } else {
                showNoNotices();
            }
        } else {
            showNoNotices();
        }
    } catch (error) {
        console.error('Error fetching notices:', error);
        if (tbody) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="4" class="px-6 py-12 text-center">
                        <div class="bg-red-50 rounded-lg p-6">
                            <i class="fas fa-exclamation-triangle text-red-600 text-4xl mb-4"></i>
                            <p class="text-red-600 font-semibold">Unable to load notices. Please try again later.</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    }
}

function updateDepartmentFilter() {
    const filterContainer = document.getElementById('department-filter');
    
    if (!filterContainer) {
        console.error('department-filter element not found');
        return;
    }
    
    // Keep "All" button and add department buttons
    let html = `
        <button class="department-btn ${currentDepartment === 'all' ? 'active' : ''} px-4 py-2 rounded-lg ${currentDepartment === 'all' ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'} font-semibold transition" data-department="all">
            All
        </button>
    `;
    
    allDepartments.forEach(dept => {
        if (dept) {
            const isActive = currentDepartment === dept;
            html += `
                <button class="department-btn ${isActive ? 'active' : ''} px-4 py-2 rounded-lg ${isActive ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'} font-semibold transition" data-department="${dept}">
                    ${dept}
                </button>
            `;
        }
    });
    
    filterContainer.innerHTML = html;
}

function filterByDepartment(department) {
    currentDepartment = department;
    
    // Update active button state
    document.querySelectorAll('.department-btn').forEach(btn => {
        btn.classList.remove('active', 'bg-blue-600', 'text-white', 'hover:bg-blue-700');
        btn.classList.add('bg-gray-200', 'text-gray-700', 'hover:bg-gray-300');
    });
    
    const activeBtn = document.querySelector(`[data-department="${department}"]`);
    if (activeBtn) {
        activeBtn.classList.add('active', 'bg-blue-600', 'text-white', 'hover:bg-blue-700');
        activeBtn.classList.remove('bg-gray-200', 'text-gray-700', 'hover:bg-gray-300');
    }
    
    // Filter notices from already loaded data
    let filteredNotices = allNotices;
    if (department !== 'all') {
        filteredNotices = allNotices.filter(notice => notice.department === department);
    }
    
    if (filteredNotices.length > 0) {
        displayNoticesTable(filteredNotices);
    } else {
        showNoNotices();
    }
}

function displayNoticesTable(notices) {
    const tbody = document.getElementById('notices-tbody');
    
    if (!tbody) {
        console.error('notices-tbody element not found');
        return;
    }
    
    if (!notices || notices.length === 0) {
        showNoNotices();
        return;
    }
    
    tbody.innerHTML = notices.map((notice, index) => {
        const slNo = index + 1;
        const date = formatDate(notice.date);
        const fileUrl = notice.file_path 
            ? (window.location.origin + '/admin/public/storage/' + notice.file_path)
            : null;
        
        return `
            <tr class="hover:bg-blue-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-gray-900">
                    ${slNo}
                </td>
                <td class="px-6 py-4 text-sm text-gray-900">
                    <div class="font-medium">${notice.title}</div>
                    ${notice.department ? `<div class="text-xs text-gray-500 mt-1">${notice.department}</div>` : ''}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                    <i class="fas fa-calendar-alt text-blue-600 mr-2"></i>${date}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-center">
                    ${fileUrl ? `
                        <a href="${fileUrl}" download target="_blank" 
                           class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-semibold rounded-lg hover:bg-blue-700 transition shadow-md hover:shadow-lg">
                            <i class="fas fa-download mr-2"></i>Download
                        </a>
                    ` : `
                        <span class="text-gray-400 text-sm">No file</span>
                    `}
                </td>
            </tr>
        `;
    }).join('');
}

function showNoNotices() {
    const tbody = document.getElementById('notices-tbody');
    
    if (!tbody) {
        console.error('notices-tbody element not found');
        return;
    }
    
    tbody.innerHTML = `
        <tr>
            <td colspan="4" class="px-6 py-12 text-center">
                <div class="flex flex-col items-center">
                    <i class="fas fa-clipboard-list text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-800 mb-2">No Notices Available</h3>
                    <p class="text-gray-600">There are no notices to display at the moment. Please check back later.</p>
                </div>
            </td>
        </tr>
    `;
}

function formatDate(dateString) {
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
}
