// app/view/admin/pedagogie/inscription-module/list/main.js

const API_BASE_URL = '/est-concours/model/api/inscription-module.php';
const API_FILIERE_URL = '/est-concours/model/api/filiere.php';
const API_MODULE_URL = '/est-concours/model/api/module.php';
const API_SEMESTRE_URL = '/est-concours/model/api/semestre.php';

let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let currentDetailId = null;

document.addEventListener('DOMContentLoaded', function() {
    loadInscriptions();
    loadStats();
    setupSearchForm();
});

function setupSearchForm() {
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            currentPage = 1;
            loadInscriptions();
        });
    }
}

function resetSearch() {
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
        searchForm.reset();
    }
    const searchFiliere = document.getElementById('searchFiliere');
    const searchAnnee = document.getElementById('searchAnnee');
    if (searchFiliere) searchFiliere.value = '';
    if (searchAnnee) searchAnnee.value = '';
    currentPage = 1;
    loadInscriptions();
}

function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                const statTotal = document.getElementById('statTotal');
                const statModules = document.getElementById('statModules');
                const statEtudiants = document.getElementById('statEtudiants');

                if (statTotal) statTotal.textContent = result.data.total_inscriptions || 0;
                if (statModules) statModules.textContent = result.data.total_modules || 0;
                if (statEtudiants) statEtudiants.textContent = result.data.total_etudiants || 0;
            } else {
                console.error('Erreur stats:', result.message);
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des stats:', error);
            // Ne pas afficher de toast pour éviter le spam
        });
}

function loadInscriptions() {
    showLoading(true);

    const searchSearch = document.getElementById('searchSearch');
    const searchAnnee = document.getElementById('searchAnnee');
    const searchFiliere = document.getElementById('searchFiliere');

    const params = new URLSearchParams({
        search: searchSearch?.value || '',
        annee_universitaire: searchAnnee?.value || '',
        filiere_id: searchFiliere?.value || '',
        page: currentPage,
        per_page: perPage
    });

    fetch(`${API_BASE_URL}?action=search&${params}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            showLoading(false);
            if (result.success) {
                renderTable(result.data.data || []);
                renderPagination(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
                renderTable([]);
            }
        })
        .catch(error => {
            showLoading(false);
            console.error('Erreur de connexion:', error);
            showToast('Erreur de connexion au serveur', 'error');
            renderTable([]);
        });
}

function renderTable(inscriptions) {
    const tbody = document.getElementById('tableBody');
    if (!tbody) return;

    if (!inscriptions || inscriptions.length === 0) {
        tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;padding:40px;">📭 Aucune inscription trouvée</td></tr>`;
        return;
    }

    tbody.innerHTML = inscriptions.map(i => {
        const nb = i.nb_etudiants_inscrits || i.nb_etudiants || 0;
        const date = i.created_at ? new Date(i.created_at).toLocaleDateString('fr-FR') : '-';

        return `
            <tr>
                <td>${i.id}</td>
                <td><strong>${escapeHtml(i.module_libelle || '-')}</strong><br><small>${escapeHtml(i.module_code || '')}</small></td>
                <td><span class="badge badge-primary">${escapeHtml(i.filiere_libelle || '-')}</span></td>
                <td><span class="badge badge-secondary">${escapeHtml(i.annee_universitaire || '-')}</span></td>
                <td><span class="badge badge-info">${nb}</span></td>
                <td><small>${date}</small></td>
                <td>
                    <button class="btn btn-info btn-sm" onclick="viewDetail(${i.id})"><i class="fas fa-eye"></i></button>
                    <button class="btn btn-danger btn-sm" onclick="deleteInscription(${i.id})"><i class="fas fa-trash"></i></button>
                </td>
            </tr>
        `;
    }).join('');
}

function renderPagination(data) {
    const paginationInfo = document.getElementById('paginationInfo');
    const pageNumbers = document.getElementById('pageNumbers');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');

    if (!paginationInfo || !pageNumbers) return;

    totalPages = data.totalPages || 1;
    const start = (data.page - 1) * perPage + 1;
    const end = Math.min(data.page * perPage, data.total || 0);

    paginationInfo.textContent = `Affichage de ${start} à ${end} sur ${data.total || 0} inscriptions`;

    let html = '';
    for (let i = 1; i <= totalPages; i++) {
        html += `<button onclick="goToPage(${i})" ${i === data.page ? 'class="active"' : ''}>${i}</button>`;
    }
    pageNumbers.innerHTML = html;

    if (prevBtn) prevBtn.disabled = data.page <= 1;
    if (nextBtn) nextBtn.disabled = data.page >= totalPages;
}

function changePage(dir) {
    if (dir === 'prev' && currentPage > 1) {
        currentPage--;
    } else if (dir === 'next' && currentPage < totalPages) {
        currentPage++;
    }
    loadInscriptions();
}

function goToPage(page) {
    currentPage = page;
    loadInscriptions();
}

function openCreateModal() {
    if (typeof openInscriptionModal === 'function') {
        openInscriptionModal(null);
    } else {
        showToast('Le modal de création n\'est pas disponible', 'warning');
    }
}

function viewDetail(id) {
    currentDetailId = id;
    const modal = document.getElementById('detailModal');
    if (!modal) {
        showToast('Le modal de détail n\'est pas disponible', 'warning');
        return;
    }

    modal.classList.add('active');
    document.body.style.overflow = 'hidden';

    const detailContent = document.getElementById('detailContent');
    if (detailContent) {
        detailContent.innerHTML = '<div class="loading active"><div class="spinner"></div><p style="margin-top:10px;">Chargement...</p></div>';
    }

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
            } else {
                const detailContent = document.getElementById('detailContent');
                if (detailContent) {
                    detailContent.innerHTML = `<div class="alert alert-error">❌ ${result.message}</div>`;
                }
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            const detailContent = document.getElementById('detailContent');
            if (detailContent) {
                detailContent.innerHTML = '<div class="alert alert-error">❌ Erreur de connexion</div>';
            }
        });
}

function renderDetail(data) {
    const nb = data.nb_etudiants_inscrits || data.nb_etudiants || 0;
    const date = data.created_at ? new Date(data.created_at).toLocaleString('fr-FR') : '-';

    let studentsHtml = '';
    if (data.students && data.students.length > 0) {
        studentsHtml = `
            <table class="detail-students-table">
                <thead>
                    <tr>
                        <th>N°</th>
                        <th>Nom</th>
                        <th>Prénom</th>
                        <th>CIN</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    ${data.students.map((s, index) => `
                        <tr>
                            <td>${index + 1}</td>
                            <td>${escapeHtml(s.nom || '-')}</td>
                            <td>${escapeHtml(s.prenom || '-')}</td>
                            <td><span class="badge badge-secondary">${escapeHtml(s.cin || '-')}</span></td>
                            <td>${escapeHtml(s.email || '-')}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    } else {
        studentsHtml = `<p style="text-align:center;color:#7f8c8d;">Aucun étudiant inscrit</p>`;
    }

    const detailContent = document.getElementById('detailContent');
    if (detailContent) {
        detailContent.innerHTML = `
            <div class="detail-section">
                <div class="detail-header">
                    <div class="detail-avatar"><i class="fas fa-user-graduate"></i></div>
                    <div class="detail-title">
                        <h2>${escapeHtml(data.module_libelle || 'Module')}</h2>
                        <div class="detail-meta">
                            <span class="badge badge-primary">${escapeHtml(data.filiere_libelle || '-')}</span>
                            <span class="badge badge-secondary">${escapeHtml(data.annee_universitaire || '-')}</span>
                        </div>
                    </div>
                </div>

                <div class="detail-grid">
                    <div class="detail-item"><span class="label">ID</span><span class="value">${data.id}</span></div>
                    <div class="detail-item"><span class="label">Module</span><span class="value"><strong>${escapeHtml(data.module_libelle)}</strong><br><small>${escapeHtml(data.module_code)}</small></span></div>
                    <div class="detail-item"><span class="label">Filière</span><span class="value">${escapeHtml(data.filiere_libelle)}</span></div>
                    <div class="detail-item"><span class="label">Semestre</span><span class="value">${escapeHtml(data.semestre_libelle || '-')}</span></div>
                    <div class="detail-item"><span class="label">Année Universitaire</span><span class="value">${escapeHtml(data.annee_universitaire)}</span></div>
                    <div class="detail-item"><span class="label">Professeur</span><span class="value">${escapeHtml(data.employee_prenom || '')} ${escapeHtml(data.employee_nom || '-')}</span></div>
                    <div class="detail-item"><span class="label">Nb Étudiants</span><span class="value"><strong style="color:#27ae60;font-size:20px;">${nb}</strong></span></div>
                    <div class="detail-item"><span class="label">Date de création</span><span class="value">${date}</span></div>
                    <div class="detail-item full-width"><span class="label">Description</span><span class="value">${escapeHtml(data.description || 'Aucune description')}</span></div>
                </div>

                <div style="margin-top:20px;">
                    <h3><i class="fas fa-users"></i> Étudiants inscrits (${nb})</h3>
                    <div class="table-wrapper" style="max-height:400px;overflow-y:auto;">
                        ${studentsHtml}
                    </div>
                </div>
            </div>
        `;
    }
}

function closeDetailModal() {
    const modal = document.getElementById('detailModal');
    if (modal) modal.classList.remove('active');
    document.body.style.overflow = '';
    currentDetailId = null;
}

function closeInscriptionModal() {
    const modal = document.getElementById('inscriptionModal');
    if (modal) modal.classList.remove('active');
    document.body.style.overflow = '';
}

function deleteInscription(id) {
    if (!confirm('⚠️ Supprimer cette inscription ?\n\nCette action supprimera également tous les étudiants inscrits.')) {
        return;
    }

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                loadInscriptions();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            showToast('Erreur de connexion', 'error');
        });
}

function showLoading(show) {
    const loading = document.querySelector('.loading');
    if (loading) {
        if (show) {
            loading.classList.add('active');
        } else {
            loading.classList.remove('active');
        }
    }
}

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) {
        console.log('Toast:', message);
        return;
    }
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<span>${message}</span><button onclick="this.parentElement.remove()">&times;</button>`;
    container.appendChild(toast);
    setTimeout(() => {
        if (toast.parentElement) toast.remove();
    }, 4000);
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Fermeture des modals
document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            if (this.id === 'detailModal') {
                closeDetailModal();
            } else if (this.id === 'inscriptionModal') {
                closeInscriptionModal();
            }
        }
    });
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const detailModal = document.getElementById('detailModal');
        const inscriptionModal = document.getElementById('inscriptionModal');

        if (detailModal?.classList.contains('active')) {
            closeDetailModal();
        } else if (inscriptionModal?.classList.contains('active')) {
            closeInscriptionModal();
        }
    }
});