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

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

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

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

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchStatus').value = '';
    document.getElementById('searchAnnee').value = '';
    currentPage = 1;
    loadSemestres();
}

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

function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                document.getElementById('statTotal').textContent = result.data.total || 0;
                document.getElementById('statAnnees').textContent = result.data.total_annees || 0;
            }
        });

    fetch(`${API_BASE_URL}?action=actifs`)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                document.getElementById('statActifs').textContent = result.data.length || 0;
            }
        });
}

// =========================================
// CHARGEMENT DES SEMESTRES
// =========================================

function loadSemestres() {
    showLoading(true);
    
    const params = new URLSearchParams({
        libelle: document.getElementById('searchLibelle')?.value || '',
        code: document.getElementById('searchCode')?.value || '',
        annee_universitaire: document.getElementById('searchAnnee')?.value || '',
        page: currentPage,
        per_page: perPage
    });

    const status = document.getElementById('searchStatus')?.value;
    if (status) {
        params.append('status', status);
    }

    fetch(`${API_BASE_URL}?action=search&${params}`)
        .then(r => r.json())
        .then(result => {
            showLoading(false);
            if (result.success) {
                renderTable(result.data.data);
                renderPagination(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(() => {
            showLoading(false);
            showToast('Erreur de connexion', 'error');
        });
}

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

function renderTable(semestres) {
    const tbody = document.getElementById('tableBody');
    
    if (!semestres || semestres.length === 0) {
        tbody.innerHTML = `<tr><td colspan="8" style="text-align:center;padding:40px;">📭 Aucun semestre trouvé</td></tr>`;
        return;
    }

    tbody.innerHTML = semestres.map(s => {
        const statusBadge = s.status === 'actif' 
            ? '<span class="badge badge-success">Actif</span>'
            : '<span class="badge badge-danger">Inactif</span>';
        
        const periode = s.date_debut && s.date_fin 
            ? `${formatDate(s.date_debut)} → ${formatDate(s.date_fin)}`
            : 'Non défini';

        return `
            <tr>
                <td>${s.id}</td>
                <td><strong>${escapeHtml(s.libelle)}</strong></td>
                <td><span class="badge badge-info">${escapeHtml(s.code)}</span></td>
                <td><span class="badge badge-primary">${escapeHtml(s.annee_universitaire || '-')}</span></td>
                <td><small>${periode}</small></td>
                <td><span class="badge badge-warning">${s.nombre_modules || 0}</span></td>
                <td>${statusBadge}</td>
                <td>
                    <button class="btn btn-info btn-sm" onclick="viewDetail(${s.id})"><i class="fas fa-eye"></i></button>
                    <button class="btn btn-warning btn-sm" onclick="openEditModal(${s.id})"><i class="fas fa-edit"></i></button>
                    <button class="btn btn-danger btn-sm" onclick="deleteSemestre(${s.id})"><i class="fas fa-trash"></i></button>
                </td>
            </tr>
        `;
    }).join('');
}

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

function renderPagination(data) {
    totalPages = data.totalPages;
    const start = (data.page - 1) * perPage + 1;
    const end = Math.min(data.page * perPage, data.total);
    
    document.getElementById('paginationInfo').textContent = 
        `Affichage de ${start} à ${end} sur ${data.total} semestres`;
    
    let html = '';
    for (let i = 1; i <= data.totalPages; i++) {
        html += `<button onclick="goToPage(${i})" ${i === data.page ? 'class="active"' : ''}>${i}</button>`;
    }
    document.getElementById('pageNumbers').innerHTML = html;
    
    document.getElementById('prevBtn').disabled = data.page <= 1;
    document.getElementById('nextBtn').disabled = data.page >= data.totalPages;
}

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

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

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Semestre';
    document.getElementById('semestreForm').reset();
    document.getElementById('semestreId').value = '';
    document.getElementById('status').value = 'actif';
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Semestre';
    document.getElementById('semestreId').value = id;
    
    if (document.getElementById('detailModal').classList.contains('active')) {
        closeDetailModal();
    }

    document.querySelector('.modal-overlay').classList.add('active');
    
    ['libelle', 'code', 'annee_universitaire', 'date_debut', 'date_fin', 'description'].forEach(f => {
        document.getElementById(f).disabled = true;
    });

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(r => r.json())
        .then(result => {
            ['libelle', 'code', 'annee_universitaire', 'date_debut', 'date_fin', 'description'].forEach(f => {
                document.getElementById(f).disabled = false;
            });

            if (result.success) {
                const s = result.data;
                document.getElementById('libelle').value = s.libelle || '';
                document.getElementById('code').value = s.code || '';
                document.getElementById('annee_universitaire').value = s.annee_universitaire || '';
                document.getElementById('status').value = s.status || 'actif';
                document.getElementById('date_debut').value = s.date_debut || '';
                document.getElementById('date_fin').value = s.date_fin || '';
                document.getElementById('description').value = s.description || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(() => {
            ['libelle', 'code', 'annee_universitaire', 'date_debut', 'date_fin', 'description'].forEach(f => {
                document.getElementById(f).disabled = false;
            });
            showToast('Erreur de connexion', 'error');
            closeModal();
        });
}

function saveSemestre() {
    const data = {
        libelle: document.getElementById('libelle').value.trim(),
        code: document.getElementById('code').value.trim(),
        annee_universitaire: document.getElementById('annee_universitaire').value,
        status: document.getElementById('status').value,
        date_debut: document.getElementById('date_debut').value || null,
        date_fin: document.getElementById('date_fin').value || null,
        description: document.getElementById('description').value.trim()
    };

    if (!data.libelle) {
        showToast('Libellé obligatoire', 'warning');
        return;
    }
    if (!data.code) {
        showToast('Code obligatoire', 'warning');
        return;
    }
    if (!data.annee_universitaire) {
        showToast('Année universitaire obligatoire', 'warning');
        return;
    }

    const id = document.getElementById('semestreId').value;
    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : API_BASE_URL;

    const saveBtn = document.querySelector('.modal-footer .btn-primary');
    const orig = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';
    saveBtn.disabled = true;

    fetch(url, {
        method: id ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(result => {
        saveBtn.innerHTML = orig;
        saveBtn.disabled = false;
        if (result.success) {
            showToast(result.message, 'success');
            closeModal();
            loadSemestres();
            loadStats();
        } else {
            showToast('Erreur: ' + result.message, 'error');
        }
    })
    .catch(() => {
        saveBtn.innerHTML = orig;
        saveBtn.disabled = false;
        showToast('Erreur de connexion', 'error');
    });
}

// =========================================
// DETAIL
// =========================================

function viewDetail(id) {
    currentDetailId = id;
    const modal = document.getElementById('detailModal');
    modal.classList.add('active');
    document.body.style.overflow = 'hidden';
    
    document.getElementById('detailContent').innerHTML = 
        '<div class="loading active"><div class="spinner"></div><p style="margin-top:10px;">Chargement...</p></div>';
    document.getElementById('editFromDetailBtn').style.display = 'none';

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

function renderDetail(semestre) {
    const statusBadge = semestre.status === 'actif' 
        ? '<span class="badge badge-success">Actif</span>'
        : '<span class="badge badge-danger">Inactif</span>';
    
    const periode = semestre.date_debut && semestre.date_fin 
        ? `${formatDate(semestre.date_debut)} → ${formatDate(semestre.date_fin)}`
        : 'Non défini';

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar"><i class="fas fa-calendar-alt"></i></div>
                <div class="detail-title">
                    <h2>${escapeHtml(semestre.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">${escapeHtml(semestre.code)}</span>
                        <span class="badge badge-primary">${escapeHtml(semestre.annee_universitaire || '-')}</span>
                        ${statusBadge}
                    </div>
                </div>
            </div>
            <div class="detail-grid">
                <div class="detail-item"><span class="label">ID</span><span class="value">${semestre.id}</span></div>
                <div class="detail-item"><span class="label">Code</span><span class="value"><span class="badge badge-info">${escapeHtml(semestre.code)}</span></span></div>
                <div class="detail-item"><span class="label">Année Universitaire</span><span class="value"><span class="badge badge-primary">${escapeHtml(semestre.annee_universitaire || '-')}</span></span></div>
                <div class="detail-item"><span class="label">Statut</span><span class="value">${statusBadge}</span></div>
                <div class="detail-item"><span class="label">Date Début</span><span class="value">${formatDate(semestre.date_debut)}</span></div>
                <div class="detail-item"><span class="label">Date Fin</span><span class="value">${formatDate(semestre.date_fin)}</span></div>
                <div class="detail-item full-width"><span class="label">Libellé</span><span class="value">${escapeHtml(semestre.libelle)}</span></div>
                <div class="detail-item full-width"><span class="label">Description</span><span class="value">${escapeHtml(semestre.description || 'Aucune description')}</span></div>
            </div>
            <div class="detail-stats">
                <div class="detail-stat-item">
                    <span class="stat-number">${semestre.nombre_modules || 0}</span>
                    <span class="stat-label">Modules</span>
                </div>
                <div class="detail-stat-item">
                    <span class="stat-number">${(semestre.total_cours || 0) + (semestre.total_tp || 0) + (semestre.total_td || 0)}h</span>
                    <span class="stat-label">Total Heures</span>
                </div>
                <div class="detail-stat-item">
                    <span class="stat-number">${semestre.total_cours || 0}h</span>
                    <span class="stat-label">Heures Cours</span>
                </div>
            </div>
        </div>`;
    
    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';
}

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

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

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

function deleteSemestre(id) {
    if (!confirm('⚠️ Supprimer ce semestre ?\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');
                loadSemestres();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(() => {
            showToast('Erreur de connexion', 'error');
        });
}

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

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

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

function closeModal() {
    document.querySelector('.modal-overlay').classList.remove('active');
}

function formatDate(date) {
    if (!date) return '-';
    const d = new Date(date);
    return d.toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
    });
}

function showLoading(show) {
    const loading = document.querySelector('.loading');
    if (loading) loading.classList.toggle('active', show);
}

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    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 closeModal();
        }
    });
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (document.getElementById('detailModal').classList.contains('active')) closeDetailModal();
        else if (document.querySelector('.modal-overlay.active')) closeModal();
    }
});