// app/view/admin/pedagogie/affectation_module/list/main.js

const API_BASE_URL = '/est-concours/model/api/affectation_module.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let currentDetailId = null;

// =========================================
// INITIALISATION
// =========================================

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

// =========================================
// RECHERCHE
// =========================================

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

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

// =========================================
// STATISTIQUES
// =========================================

function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                const stats = result.data;
                document.getElementById('statTotal').textContent = stats.total || 0;
                document.getElementById('statProfesseurs').textContent = stats.total_professeurs || 0;
                document.getElementById('statModules').textContent = stats.total_modules || 0;
            }
        })
        .catch(() => {
            console.error('Erreur lors du chargement des statistiques');
        });
}

// =========================================
// CHARGEMENT DES AFFECTATIONS
// =========================================

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

    // Afficher le chargement
    tbody.innerHTML = `
        <tr>
            <td colspan="7" style="text-align:center;padding:40px;">
                <div class="spinner"></div>
                <p style="margin-top:10px;color:#7f8c8d;">Chargement des affectations...</p>
            </td>
        </tr>
    `;

    // Construire les paramètres de recherche
    const params = new URLSearchParams();
    const searchModule = document.getElementById('searchModule')?.value || '';
    const searchProfesseur = document.getElementById('searchProfesseur')?.value || '';
    const searchAnnee = document.getElementById('searchAnnee')?.value || '';

    if (searchModule) params.append('module_libelle', searchModule);
    if (searchProfesseur) params.append('employee_nom', searchProfesseur);
    if (searchAnnee) params.append('annee_universitaire', searchAnnee);
    params.append('page', currentPage);
    params.append('per_page', perPage);

    const url = `${API_BASE_URL}?action=search&${params.toString()}`;

    fetch(url)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                const data = result.data.data || [];
                renderTable(data);
                renderPagination(result.data);
            } else {
                showToast('Erreur: ' + (result.message || 'Chargement impossible'), 'error');
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" style="text-align:center;padding:40px;color:#e74c3c;">
                            ❌ ${result.message || 'Erreur de chargement'}
                        </td>
                    </tr>
                `;
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" style="text-align:center;padding:40px;color:#e74c3c;">
                        ❌ Erreur de connexion au serveur
                    </td>
                </tr>
            `;
            showToast('Erreur de connexion', 'error');
        });
}

// =========================================
// AFFICHAGE DU TABLEAU
// =========================================

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

    if (!affectations || affectations.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align:center;padding:60px 20px;">
                    <div style="font-size:48px;margin-bottom:15px;">📭</div>
                    <h3 style="color:#7f8c8d;margin-bottom:10px;">Aucune affectation trouvée</h3>
                    <p style="color:#95a5a6;margin-bottom:20px;">Commencez par créer votre première affectation</p>
                    <button class="btn btn-success" onclick="openCreateModal()">
                        <i class="fas fa-plus"></i> Nouvelle Affectation
                    </button>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = affectations.map(a => {
        // Récupérer les données avec les bons noms de champs
        const moduleName = a.module_libelle || '-';
        const moduleCode = a.module_code || '';
        const filiereName = a.filiere_libelle || '-';
        const semestreName = a.semestre_libelle || '-';
        const professeur = a.employee_fullname || '-';

        return `
            <tr>
                <td><strong>${a.id}</strong></td>
                <td>
                    <strong>${escapeHtml(moduleName)}</strong>
                    ${moduleCode ? `<br><small class="text-muted">${escapeHtml(moduleCode)}</small>` : ''}
                </td>
                <td>${escapeHtml(filiereName)}</td>
                <td>${escapeHtml(semestreName)}</td>
                <td>${escapeHtml(professeur)}</td>
                <td><span class="badge badge-primary">${escapeHtml(a.annee_universitaire)}</span></td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-info btn-sm" onclick="viewDetail(${a.id})" title="Voir les détails">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-warning btn-sm" onclick="openEditModal(${a.id})" title="Modifier">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="deleteAffectation(${a.id})" title="Supprimer">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

// =========================================
// PAGINATION
// =========================================

function renderPagination(data) {
    if (!data) return;

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

    const infoElement = document.getElementById('paginationInfo');
    const pageNumbers = document.getElementById('pageNumbers');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');

    if (infoElement) {
        infoElement.textContent = total > 0
            ? `Affichage de ${start} à ${end} sur ${total} affectations`
            : 'Aucune affectation';
    }

    if (pageNumbers) {
        let html = '';
        const maxVisible = 7;
        let startPage = Math.max(1, current - Math.floor(maxVisible / 2));
        let endPage = Math.min(totalPages, startPage + maxVisible - 1);

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

        if (startPage > 1) {
            html += `<button onclick="goToPage(1)">1</button>`;
            if (startPage > 2) html += `<button disabled>...</button>`;
        }

        for (let i = startPage; i <= endPage; i++) {
            html += `<button onclick="goToPage(${i})" ${i === current ? 'class="active"' : ''}>${i}</button>`;
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) html += `<button disabled>...</button>`;
            html += `<button onclick="goToPage(${totalPages})">${totalPages}</button>`;
        }

        pageNumbers.innerHTML = html;
    }

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

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

function goToPage(page) {
    if (page !== currentPage) {
        currentPage = page;
        loadAffectations();
    }
}

// =========================================
// MODAL - CREATE / EDIT
// =========================================

function openCreateModal() {
    openAffectationModal(null);
}

function openEditModal(id) {
    // Fermer le modal de détail s'il est ouvert
    const detailModal = document.getElementById('detailModal');
    if (detailModal && detailModal.classList.contains('active')) {
        closeDetailModal();
    }

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                openAffectationModal(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(() => {
            showToast('Erreur de connexion', 'error');
        });
}

// =========================================
// VISUALISATION
// =========================================

function viewDetail(id) {
    currentDetailId = id;
    const modal = document.getElementById('detailModal');
    if (!modal) {
        showToast('Modal de détail non trouvé', 'error');
        return;
    }

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

    const content = document.getElementById('detailContent');
    if (content) {
        content.innerHTML = `
            <div style="text-align:center;padding:40px;">
                <div class="spinner"></div>
                <p style="margin-top:10px;color:#7f8c8d;">Chargement des détails...</p>
            </div>
        `;
    }

    const editBtn = document.getElementById('editFromDetailBtn');
    if (editBtn) editBtn.style.display = 'none';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
                if (editBtn) editBtn.style.display = 'inline-flex';
            } else {
                if (content) {
                    content.innerHTML = `
                        <div class="alert alert-error">
                            ❌ ${result.message || 'Erreur de chargement'}
                        </div>
                    `;
                }
            }
        })
        .catch(() => {
            if (content) {
                content.innerHTML = `
                    <div class="alert alert-error">
                        ❌ Erreur de connexion
                    </div>
                `;
            }
        });
}

function renderDetail(affectation) {
    const content = document.getElementById('detailContent');
    if (!content) return;

    const moduleName = affectation.module_libelle || '-';
    const moduleCode = affectation.module_code || '';
    const filiereName = affectation.filiere_libelle || '-';
    const semestreName = affectation.semestre_libelle || '-';
    const professeur = affectation.employee_fullname || '-';
    const employeeEmail = affectation.employee_email || '-';

    content.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(moduleName)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">${escapeHtml(moduleCode)}</span>
                        <span class="badge badge-primary">${escapeHtml(affectation.annee_universitaire)}</span>
                    </div>
                </div>
            </div>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label">ID</span>
                    <span class="value">${affectation.id}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Module</span>
                    <span class="value"><strong>${escapeHtml(moduleName)}</strong> (${escapeHtml(moduleCode)})</span>
                </div>
                <div class="detail-item">
                    <span class="label">Filière</span>
                    <span class="value">${escapeHtml(filiereName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Semestre</span>
                    <span class="value">${escapeHtml(semestreName)}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Professeur</span>
                    <span class="value"><strong>${escapeHtml(professeur)}</strong></span>
                </div>
                <div class="detail-item">
                    <span class="label">Email Professeur</span>
                    <span class="value">${escapeHtml(employeeEmail)}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label">Année Universitaire</span>
                    <span class="value"><span class="badge badge-primary">${escapeHtml(affectation.annee_universitaire)}</span></span>
                </div>
            </div>
        </div>
    `;

    // Mettre à jour le bouton modifier
    const editBtn = document.getElementById('editFromDetailBtn');
    if (editBtn) {
        editBtn.setAttribute('onclick', `editFromDetail()`);
    }
}

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

function editFromDetail() {
    if (currentDetailId) {
        closeDetailModal();
        setTimeout(() => openEditModal(currentDetailId), 300);
    }
}

// =========================================
// SUPPRESSION
// =========================================

function deleteAffectation(id) {
    if (!confirm('⚠️ Êtes-vous sûr de vouloir supprimer cette affectation ?\n\nCette action est irréversible.')) {
        return;
    }

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                showToast('✅ ' + result.message, 'success');
                loadAffectations();
                loadStats();
            } else {
                showToast('❌ Erreur: ' + result.message, 'error');
            }
        })
        .catch(() => {
            showToast('❌ Erreur de connexion', 'error');
        });
}

// =========================================
// EXPORT
// =========================================

function exportAffectations() {
    window.location.href = `${API_BASE_URL}?action=export`;
}

// =========================================
// UTILITAIRES
// =========================================

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) {
        console.log(`[${type}] ${message}`);
        return;
    }

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;

    const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };

    toast.innerHTML = `
        <span>${icons[type] || 'ℹ️'} ${message}</span>
        <button onclick="this.parentElement.remove()">&times;</button>
    `;

    container.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            setTimeout(() => {
                if (toast.parentElement) toast.remove();
            }, 300);
        }
    }, 4000);
}

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

// =========================================
// FERMETURE DES MODALS
// =========================================

// Fermer les modals en cliquant sur l'overlay
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.modal-overlay').forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                if (this.id === 'detailModal') {
                    closeDetailModal();
                } else if (this.id === 'affectationModal') {
                    if (typeof closeAffectationModal === 'function') {
                        closeAffectationModal();
                    }
                }
            }
        });
    });

    // Fermer avec la touche Escape
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const detailModal = document.getElementById('detailModal');
            const affectationModal = document.getElementById('affectationModal');

            if (detailModal && detailModal.classList.contains('active')) {
                closeDetailModal();
            } else if (affectationModal && affectationModal.classList.contains('active')) {
                if (typeof closeAffectationModal === 'function') {
                    closeAffectationModal();
                }
            }
        }
    });
});

// =========================================
// FONCTIONS GLOBALES POUR LES MODALS
// =========================================

// Ces fonctions sont appelées depuis les boutons onclick
// Elles doivent être disponibles globalement

window.openCreateModal = openCreateModal;
window.openEditModal = openEditModal;
window.viewDetail = viewDetail;
window.closeDetailModal = closeDetailModal;
window.editFromDetail = editFromDetail;
window.deleteAffectation = deleteAffectation;
window.exportAffectations = exportAffectations;
window.resetSearch = resetSearch;
window.changePage = changePage;
window.goToPage = goToPage;