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

const API_DETAIL_URL = '/est-concours/model/api/inscription-module-detail.php';
const API_INSCRIPTION_URL = '/est-concours/model/api/inscription-module.php';

//const currentInscriptionModuleId = window.currentInscriptionModuleId || 0;

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

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

function setupSearchForm() {
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        filterStudents();
    });
}

function resetSearch() {
    document.getElementById('searchForm').reset();
    filterStudents();
}

function filterStudents() {
    const search = document.getElementById('searchStudent').value.toLowerCase().trim();
    const rows = document.querySelectorAll('#tableBody tr');
    let visibleCount = 0;

    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        if (search === '' || text.includes(search)) {
            row.style.display = '';
            visibleCount++;
        } else {
            row.style.display = 'none';
        }
    });

    document.getElementById('paginationInfo').textContent =
        `Affichage de 1 à ${visibleCount} sur ${visibleCount}`;
}

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

function loadStats() {
    fetch(`${API_DETAIL_URL}?action=stats`)
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                document.getElementById('statInscriptions').textContent = result.data.total_inscriptions_detail || 0;
                document.getElementById('statEtudiants').textContent = result.data.total_etudiants || 0;
            }
        });
}

// =========================================
// RETIRER UN ÉTUDIANT
// =========================================

function removeStudent(inscriptionModuleId, studentId) {
    if (!confirm('⚠️ Retirer cet étudiant de l\'inscription ?')) {
        return;
    }

    fetch(`${API_DETAIL_URL}?inscription_module_id=${inscriptionModuleId}&student_id=${studentId}`, {
        method: 'DELETE'
    })
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(() => {
            showToast('Erreur de connexion', 'error');
        });
}

// =========================================
// EXPORTER LES ÉTUDIANTS
// =========================================

function exportStudents(inscriptionModuleId) {
    window.location.href = `${API_DETAIL_URL}?action=export&inscription_module_id=${inscriptionModuleId}`;
}

// =========================================
// TOAST NOTIFICATION
// =========================================

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