// js/inscriptions.js
const API_BASE_URL = '/est-concours/model/api/inscription.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let concoursList = [];
let candidatsList = [];

// Load inscriptions on page load
document.addEventListener('DOMContentLoaded', function () {
    loadInscriptions();
    loadConcours();
    loadCandidats();
    setupSearchForm();
    setupMoyenneCalculation();
});

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    currentPage = 1;
    loadInscriptions();
}

function loadConcours() {
    fetch(`${API_BASE_URL}?action=concours`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                concoursList = result.data;
                populateConcoursDropdowns();
            }
        })
        .catch(error => console.error('Error loading concours:', error));
}

function loadCandidats() {
    fetch(`${API_BASE_URL}?action=candidats`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                candidatsList = result.data;
                populateCandidatDropdowns();
            }
        })
        .catch(error => console.error('Error loading candidats:', error));
}

function populateConcoursDropdowns() {
    const selects = ['searchConcours', 'concours_id'];
    selects.forEach(id => {
        const select = document.getElementById(id);
        if (select) {
            const firstOption = select.options[0];
            select.innerHTML = '';
            select.appendChild(firstOption);

            concoursList.forEach(item => {
                const option = document.createElement('option');
                option.value = item.id;
                option.textContent = item.label+'('+item.code+')'
                select.appendChild(option);
            });
        }
    });
}

function populateCandidatDropdowns() {
    const select = document.getElementById('candidat_id');
    if (select) {
        const firstOption = select.options[0];
        select.innerHTML = '';
        select.appendChild(firstOption);

        candidatsList.forEach(candidat => {
            const option = document.createElement('option');
            option.value = candidat.id;
            option.textContent = candidat.nom + ' ' + candidat.prenom + ' (' + candidat.email + ')';
            select.appendChild(option);
        });
    }
}

function loadInscriptions() {
    showLoading(true);

    const searchData = {
        action: 'search',
        concours_id: document.getElementById('searchConcours').value || '',
        candidat_search: document.getElementById('searchCandidat').value.trim() || '',
        etat_inscription: document.getElementById('searchEtat').value || '',
        resultat_inscription: document.getElementById('searchResultat').value || '',

        page: currentPage,
        per_page: perPage
    };

    // Remove empty values to keep URL clean
    Object.keys(searchData).forEach(key => {
        if (searchData[key] === '' || searchData[key] === null || searchData[key] === undefined) {
            delete searchData[key];
        }
    });

    const params = new URLSearchParams(searchData);

    fetch(`${API_BASE_URL}?${params.toString()}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            showLoading(false);
            if (result.success) {
                // Check if result.data has pagination structure
                if (result.data && result.data.data) {
                    renderTable(result.data.data);
                    renderPagination(result.data);
                } else if (Array.isArray(result.data)) {
                    // If data is a flat array, adapt pagination
                    renderTable(result.data);
                    // Simple pagination without total count
                    document.getElementById('paginationInfo').textContent =
                        `Affichage de 1 à ${result.data.length} sur ${result.data.length} inscriptions`;
                    document.getElementById('pageNumbers').innerHTML = '';
                    document.getElementById('prevBtn').disabled = true;
                    document.getElementById('nextBtn').disabled = true;
                } else {
                    renderTable([]);
                }
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
                renderTable([]);
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur: ' + error.message, 'error');
            console.error('Error:', error);
            renderTable([]);
        });
}
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 stats = result.data;
                document.getElementById('statTotal').textContent = stats.total || 0;
                document.getElementById('statValide').textContent = stats.valide || 0;
                document.getElementById('statEnAttente').textContent = stats.en_attente || 0;
                document.getElementById('statAdmis').textContent = stats.admis || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}
function renderTable(inscriptions) {
    const tbody = document.getElementById('tableBody');

    if (!inscriptions || inscriptions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" style="text-align: center; padding: 40px; color: #666;">
                    <p style="font-size: 18px;">📭 Aucune inscription trouvée</p>
                    <p style="font-size: 14px; margin-top: 5px;">Essayez de modifier vos critères de recherche</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = inscriptions.map(item => {
        const concours = item.concours || {};
        const candidat = item.candidat || {};
        const hasDocuments = item.cv || item.diplome || item.releves_notes || item.cin_recto || item.cin_verso || item.photo || item.demande_maniscrite;

        return `
            <tr>
               
                <td>${escapeHtml(concours.code || '-')}</td>
                <td>${escapeHtml(candidat.nom || '')} ${escapeHtml(candidat.prenom || '')}</td>
                <td>${escapeHtml(candidat.email || '-')}</td> <!-- تم الإضافة -->
                <td>${escapeHtml(candidat.cin || '-')}</td>   <!-- تم الإضافة -->
                <td>${item.moyenne_general_calcule || '-'}</td>
                <td><span class="badge ${getEtatBadge(item.etat_inscription)}">${escapeHtml(item.etat_inscription || '-')}</span></td>
                <td><span class="badge ${getResultatBadge(item.resultat_inscription)}">${escapeHtml(item.resultat_inscription || '-')}</span></td>
                <td>
                    <button class="btn btn-info btn-sm" onclick="viewDetail(${item.id})" title="Voir">👁️ </button>
                    <button class="btn btn-warning btn-sm" onclick="openEditModal(${item.id})" title="Modifier">✏️ </button>
                    <button class="btn btn-danger btn-sm" onclick="deleteInscription(${item.id})" title="Supprimer">🗑️ </button>
                    ${hasDocuments ? `
                        <button class="btn btn-success btn-sm" onclick="downloadDocument(${item.id})" title="Télécharger les concours (Documents)">📥 </button>
                    ` : ''}
                </td>
            </tr>
        `;
    }).join('');
}
function getEtatBadge(etat) {
    const map = {
        'VALIDE': 'badge-success',
        'EN_ATTENTE': 'badge-warning',
        'REJETE': 'badge-danger'
    };
    return map[etat] || 'badge-secondary';
}

function getResultatBadge(resultat) {
    const map = {
        'ADMIS_ORALE': 'badge-success',
        'ADMIS_ECRIT': 'badge-success',

        'EN_COURS': 'badge-warning',
        'NON_ADMIS': 'badge-danger',
        'ELLIBGIBLE_ECRIT': 'badge-info'
    };
    return map[resultat] || 'badge-secondary';
}

function renderPagination(data) {
    if (!data || !data.total) {
        document.getElementById('paginationInfo').textContent = 'Aucune donnée';
        document.getElementById('pageNumbers').innerHTML = '';
        document.getElementById('prevBtn').disabled = true;
        document.getElementById('nextBtn').disabled = true;
        return;
    }

    const {total, page, totalPages: pages} = data;
    totalPages = pages || 1;

    const start = (page - 1) * perPage + 1;
    const end = Math.min(page * perPage, total);
    document.getElementById('paginationInfo').textContent =
        `Affichage de ${start} à ${end} sur ${total} inscriptions`;

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

    document.getElementById('prevBtn').disabled = page <= 1;
    document.getElementById('nextBtn').disabled = page >= pages;
}
function changePage(direction) {
    if (direction === 'prev' && currentPage > 1) {
        currentPage--;
    } else if (direction === 'next' && currentPage < totalPages) {
        currentPage++;
    }
    loadInscriptions();
}

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

function setupMoyenneCalculation() {
    const semestreFields = ['note_s1', 'note_s2', 'note_s3', 'note_s4', 'note_s5', 'note_s6'];
    semestreFields.forEach(field => {
        document.getElementById(field).addEventListener('input', calculateMoyenne);
    });
}

function calculateMoyenne() {
    const notes = [];
    const semestreFields = ['note_s1', 'note_s2', 'note_s3', 'note_s4', 'note_s5', 'note_s6'];
    semestreFields.forEach(field => {
        const value = parseFloat(document.getElementById(field).value);
        if (!isNaN(value) && value > 0) {
            notes.push(value);
        }
    });

    if (notes.length > 0) {
        const moyenne = notes.reduce((a, b) => a + b, 0) / notes.length;
        document.getElementById('moyenne_calculee').textContent = moyenne.toFixed(2) + ' / 20';
    } else {
        document.getElementById('moyenne_calculee').textContent = '-';
    }
}

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouvelle Inscription';
    document.getElementById('inscriptionForm').reset();
    document.getElementById('inscriptionId').value = '';
    document.getElementById('moyenne_calculee').textContent = '-';
    switchTab('info');
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Inscription';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const data = result.data;
                // Fill general info
                document.getElementById('inscriptionId').value = data.id;
                document.getElementById('code').value = data.code;
                document.getElementById('label').value = data.label;
                document.getElementById('concours_id').value = data.concours_id;
                document.getElementById('candidat_id').value = data.candidat_id;
                document.getElementById('civilite').value = data.civilite || '';
                document.getElementById('etat_inscription').value = data.etat_inscription || 'EN_ATTENTE';
                document.getElementById('resultat_inscription').value = data.resultat_inscription || 'EN_COURS';
                document.getElementById('active').value = data.active;
                document.getElementById('description').value = data.description || '';

                // Fill bac info
                document.getElementById('annee_bac').value = data.annee_bac || '';
                document.getElementById('specialite_bac').value = data.specialite_bac || '';
                document.getElementById('mention_bac').value = data.mention_bac || '';
                document.getElementById('moyenne_general_bac').value = data.moyenne_general_bac || '';
                document.getElementById('type_etablissement_bac').value = data.type_etablissement_bac || '';
                document.getElementById('province').value = data.province || '';

                // Fill diplome info
                document.getElementById('type_diplome_obtenu').value = data.type_diplome_obtenu || '';
                document.getElementById('specialite_diplome').value = data.specialite_diplome || '';
                document.getElementById('anne_obtention_diplome').value = data.anne_obtention_diplome || '';
                document.getElementById('etablissement_origine').value = data.etablissement_origine || '';
                document.getElementById('module_valide').value = data.module_valide || 0;
                document.getElementById('duree_diplome').value = data.duree_diplome || '';
                document.getElementById('note_s1').value = data.note_s1 || '';
                document.getElementById('note_s2').value = data.note_s2 || '';
                document.getElementById('note_s3').value = data.note_s3 || '';
                document.getElementById('note_s4').value = data.note_s4 || '';
                document.getElementById('note_s5').value = data.note_s4 || '';
                document.getElementById('note_s6').value = data.note_s4 || '';

                // Fill documents info
                document.getElementById('moyenne_ecrit').value = data.moyenne_ecrit || '';
                document.getElementById('moyenne_orale').value = data.moyenne_orale || '';

                // Calculate moyenne
                calculateMoyenne();

                document.querySelector('.modal-overlay').classList.add('active');
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur: Edit' + error, 'error');
            console.error('Error:', error);
        });
}

function viewDetail(id) {
    document.getElementById('detailModal').classList.add('active');
    document.getElementById('detailContent').innerHTML = `
        <div class="loading active">
            <div class="spinner"></div>
            <p style="margin-top: 10px;">Chargement des détails...</p>
        </div>
    `;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success && result.data) {
                renderDetail(result.data); // هنا يتم إرسال البيانات لدالة العرض
            } else {
                document.getElementById('detailContent').innerHTML = `
                    <p style="color: var(--danger-color);">Erreur: ${result.message || 'Données introuvables'}</p>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <p style="color: var(--danger-color);">Erreur de connexion au serveur.</p>
            `;
            console.error('Error fetching detail:', error);
        });
}

// 2. دالة عرض النوافذ المقسمة (محدثة مع حماية البيانات وإضافة type="button")
function renderDetail(data) {
    if (!data) return; // حماية من الأخطاء إذا كانت البيانات فارغة

    const concours = data.concours || {};
    const candidat = data.candidat || {};

    document.getElementById('detailContent').innerHTML = `
        <div class="tabs-nav" style="display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 20px; border-bottom: 2px solid #eee; padding-bottom: 10px;">
            <button type="button" class="btn btn-sm tab-detail-btn active" onclick="switchDetailTab('info')" data-detail-tab="info">📋 Général</button>
            <button type="button" class="btn btn-sm btn-secondary tab-detail-btn" onclick="switchDetailTab('bac')" data-detail-tab="bac">🎓 Baccalauréat</button>
            <button type="button" class="btn btn-sm btn-secondary tab-detail-btn" onclick="switchDetailTab('diplome')" data-detail-tab="diplome">📜 Diplôme</button>
            <button type="button" class="btn btn-sm btn-secondary tab-detail-btn" onclick="switchDetailTab('notes')" data-detail-tab="notes">📊 Notes</button>
            <button type="button" class="btn btn-sm btn-secondary tab-detail-btn" onclick="switchDetailTab('docs')" data-detail-tab="docs">📎 Documents</button>
        </div>
        
        <div id="detail-tab-info" class="tab-detail-content" style="display: block;">
            <div class="detail-section">
                <div class="detail-grid">
                    <div class="detail-item"><span class="label">Code</span><span class="value">${escapeHtml(data.code)}</span></div>
                    <div class="detail-item"><span class="label">Libellé</span><span class="value">${escapeHtml(data.Libellé)}</span></div>
                    <div class="detail-item"><span class="label">Concours</span><span class="value">${escapeHtml(concours.code || '-')}</span></div>
                    <div class="detail-item"><span class="label">Étudiant</span><span class="value">${escapeHtml(data.nom || '-')} ${escapeHtml(data.prenom || '')}</span></div>
                    <div class="detail-item"><span class="label">Civilité</span><span class="value">${escapeHtml(data.civilite || '-')}</span></div>
                    <div class="detail-item"><span class="label">État Inscription</span><span class="value"><span class="badge ${getEtatBadge(data.etat_inscription)}">${escapeHtml(data.etat_inscription)}</span></span></div>
                    <div class="detail-item"><span class="label">Résultat</span><span class="value"><span class="badge ${getResultatBadge(data.resultat_inscription)}">${escapeHtml(data.resultat_inscription)}</span></span></div>
                    <div class="detail-item"><span class="label">Statut</span><span class="value"><span class="badge ${data.active ? 'badge-active' : 'badge-inactive'}">${data.active ? 'Actif' : 'Inactif'}</span></span></div>
                </div>
            </div>
        </div>
        
        <div id="detail-tab-bac" class="tab-detail-content" style="display: none;">
            <div class="detail-section">
                <div class="detail-grid">
                    <div class="detail-item"><span class="label">Année</span><span class="value">${data.annee_bac || '-'}</span></div>
                    <div class="detail-item"><span class="label">Spécialité</span><span class="value">${escapeHtml(data.specialite_bac || '-')}</span></div>
                    <div class="detail-item"><span class="label">Mention</span><span class="value">${escapeHtml(data.mention_bac || '-')}</span></div>
                    <div class="detail-item"><span class="label">Moyenne Générale</span><span class="value">${data.moyenne_general_bac || '-'}</span></div>
                    <div class="detail-item"><span class="label">Type Établissement</span><span class="value">${escapeHtml(data.type_etablissement_bac || '-')}</span></div>
                    <div class="detail-item"><span class="label">Province</span><span class="value">${escapeHtml(data.province || '-')}</span></div>
                </div>
            </div>
        </div>
        
        <div id="detail-tab-diplome" class="tab-detail-content" style="display: none;">
            <div class="detail-section">
                <div class="detail-grid">
                    <div class="detail-item"><span class="label">Type</span><span class="value">${escapeHtml(data.type_diplome_obtenu || '-')}</span></div>
                    <div class="detail-item"><span class="label">Spécialité</span><span class="value">${escapeHtml(data.specialite_diplome || '-')}</span></div>
                    <div class="detail-item"><span class="label">Année Obtention</span><span class="value">${data.anne_obtention_diplome || '-'}</span></div>
                    <div class="detail-item"><span class="label">Établissement</span><span class="value">${escapeHtml(data.etablissement_origine || '-')}</span></div>
                    <div class="detail-item"><span class="label">Durée</span><span class="value">${data.duree_diplome || '-'} ans</span></div>
                    <div class="detail-item"><span class="label">Modules Validés</span><span class="value">${data.module_valide ? '✅ Oui' : '❌ Non'}</span></div>
                </div>
            </div>
        </div>
        
        <div id="detail-tab-notes" class="tab-detail-content" style="display: none;">
            <div class="detail-section">
                <div class="detail-grid">
                    <div class="detail-item"><span class="label">Semestre 1</span><span class="value">${data.note_s1 || '-'}</span></div>
                    <div class="detail-item"><span class="label">Semestre 2</span><span class="value">${data.note_s2 || '-'}</span></div>
                    <div class="detail-item"><span class="label">Semestre 3</span><span class="value">${data.note_s3 || '-'}</span></div>
                    <div class="detail-item"><span class="label">Semestre 4</span><span class="value">${data.note_s4 || '-'}</span></div>
                    <div class="detail-item"><span class="label">Semestre 5</span><span class="value">${data.note_s5 || '-'}</span></div>
                    <div class="detail-item"><span class="label">Semestre 6</span><span class="value">${data.note_s6 || '-'}</span></div>
                    <div class="detail-item"><span class="label">Moyenne Générale</span><span class="value" style="font-weight: bold; color: var(--primary-color);">${data.moyenne_general_calcule || '-'}</span></div>
                    <div class="detail-item"><span class="label">Moyenne Écrit</span><span class="value">${data.moyenne_ecrit || '-'}</span></div>
                    <div class="detail-item"><span class="label">Moyenne Orale</span><span class="value">${data.moyenne_orale || '-'}</span></div>
                </div>
            </div>
        </div>
        
        <div id="detail-tab-docs" class="tab-detail-content" style="display: none;">
            <div class="detail-section">
                <div class="detail-grid">
                    <div class="detail-item"><span class="label">Baccalauréat</span><span class="value">${data.bac_recto ? '✅ Présent' : '-'}</span></div>
                    <div class="detail-item"><span class="label">Attestation Réussite</span><span class="value">${data.attestation_reusite ? '✅ Présent' : '-'}</span></div>
                    <div class="detail-item"><span class="label">Relevé de Notes</span><span class="value">${data.releve_note ? '✅ Présent' : '-'}</span></div>
                    <div class="detail-item"><span class="label">Demande Manuscrite</span><span class="value">${data.demande_maniscrite ? '✅ Présent' : '-'}</span></div>
                    <div class="detail-item"><span class="label">CV</span><span class="value">${data.cv ? '✅ Présent' : '-'}</span></div>
                    <div class="detail-item"><span class="label">CIN</span><span class="value">${data.cin_recto ? '✅ Présent' : '-'}</span></div>
                </div>
            </div>
        </div>
    `;
}

function switchDetailTab(tabId) {
    document.querySelectorAll('.tab-detail-btn').forEach(btn => {
        btn.classList.remove('active');
        btn.classList.add('btn-secondary');
    });

    const activeBtn = document.querySelector(`.tab-detail-btn[data-detail-tab="${tabId}"]`);
    if (activeBtn) {
        activeBtn.classList.remove('btn-secondary');
        activeBtn.classList.add('active');
    }
    document.querySelectorAll('.tab-detail-content').forEach(content => {
        content.style.display = 'none';
    });

    const targetContent = document.getElementById(`detail-tab-${tabId}`);
    if (targetContent) {
        targetContent.style.display = 'block';
    }
}

function importCsv() {
    // Create a modal for CSV import
    const modal = document.createElement('div');
    modal.className = 'modal-overlay active';
    modal.id = 'importCsvModal';
    modal.innerHTML = `
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3>📥 Importer des inscriptions depuis un CSV</h3>
                <button class="modal-close" onclick="closeCsvModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="csvImportForm" enctype="multipart/form-data">
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label for="importConcours">Concours *</label>
                        <select id="importConcours" required>
                            <option value="">Sélectionner un concours</option>
                            ${concoursList.map(c => `<option value="${c.id}">${c.code} - ${c.label}</option>`).join('')}
                        </select>
                    </div>
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label for="csvFile">Fichier CSV *</label>
                        <input type="file" id="csvFile" accept=".csv" required>
                        <small style="display: block; margin-top: 5px; color: #666;">
                            Format attendu: Colonnes correspondant aux champs de l'inscription.
                            <br>Le CIN et l'email sont obligatoires.
                        </small>
                    </div>
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label>Statut par défaut</label>
                        <select id="importEtat">
                            <option value="EN_ATTENTE">En Attente</option>
                            <option value="VALIDE">Validée</option>
                            <option value="REJETE">Rejetée</option>
                        </select>
                    </div>

                    <div class="form-actions" style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                        <button type="button" class="btn btn-info" onclick="downloadTemplate()">
                            <i class="fas fa-download"></i> Télécharger le template csv
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="closeCsvModal()">Annuler</button>
                        <button type="submit" class="btn btn-primary" id="importCsvBtn">
                            <i class="fas fa-upload"></i> Importer
                        </button>
                    </div>

                    <div id="importProgress" style="display: none; margin-top: 15px;">...</div>
                    <div id="importResult" style="display: none; margin-top: 15px;"></div>
                </form>
            </div>
        </div>
    `;
    document.body.appendChild(modal);

    // Handle form submission
    document.getElementById('csvImportForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const concoursId = document.getElementById('importConcours').value;
        const fileInput = document.getElementById('csvFile');
        const etat = document.getElementById('importEtat').value;

        if (!concoursId) {
            showToast('Veuillez sélectionner un concours', 'warning');
            return;
        }

        if (!fileInput.files || fileInput.files.length === 0) {
            showToast('Veuillez sélectionner un fichier CSV', 'warning');
            return;
        }

        const file = fileInput.files[0];
        if (!file.name.toLowerCase().endsWith('.csv')) {
            showToast('Le fichier doit être au format CSV', 'warning');
            return;
        }

        // Show progress
        const progressDiv = document.getElementById('importProgress');
        const resultDiv = document.getElementById('importResult');
        const progressFill = progressDiv.querySelector('.progress-fill');
        const statusText = document.getElementById('importStatus');
        const submitBtn = document.getElementById('importCsvBtn');

        progressDiv.style.display = 'block';
        resultDiv.style.display = 'none';
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Importation en cours...';
        progressFill.style.width = '30%';
        statusText.textContent = 'Préparation de l\'importation...';

        // Prepare form data
        const formData = new FormData();
        formData.append('csv_file', file);
        formData.append('concours_id', concoursId);
        formData.append('etat_inscription', etat);

        // Send to API
        fetch(`${API_BASE_URL}?action=import_csv`, {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(result => {
                progressFill.style.width = '100%';
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-upload"></i> Importer';

                if (result.success) {
                    statusText.textContent = '✅ Importation terminée !';
                    resultDiv.style.display = 'block';
                    resultDiv.innerHTML = `
                    <div class="alert alert-success" style="padding: 15px; background: #d4edda; border-radius: 8px; color: #155724;">
                        <p><strong>${result.message}</strong></p>
                        <p>📊 ${result.inserted || 0} inscriptions créées, ${result.updated || 0} mises à jour</p>
                        ${result.errors && result.errors.length > 0 ? `
                            <div style="margin-top: 10px; max-height: 150px; overflow-y: auto; background: #f8f9fa; padding: 10px; border-radius: 4px;">
                                <p style="color: #856404;"><strong>⚠️ Erreurs (${result.errors.length}):</strong></p>
                                <ul style="margin: 5px 0 0 20px; color: #856404;">
                                    ${result.errors.map(err => `<li>${err}</li>`).join('')}
                                </ul>
                            </div>
                        ` : ''}
                    </div>
                `;
                    loadInscriptions();
                    loadStats();
                    setTimeout(closeCsvModal, 3000);
                } else {
                    statusText.textContent = '❌ Erreur';
                    resultDiv.style.display = 'block';
                    resultDiv.innerHTML = `
                    <div class="alert alert-danger" style="padding: 15px; background: #f8d7da; border-radius: 8px; color: #721c24;">
                        <p><strong>Erreur:</strong> ${result.message}</p>
                    </div>
                `;
                }
            })
            .catch(error => {
                progressFill.style.width = '100%';
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-upload"></i> Importer';
                statusText.textContent = '❌ Erreur de connexion';
                resultDiv.style.display = 'block';
                resultDiv.innerHTML = `
                <div class="alert alert-danger" style="padding: 15px; background: #f8d7da; border-radius: 8px; color: #721c24;">
                    <p><strong>Erreur:</strong> Problème de connexion au serveur: ${error.message}</p>
                </div>
            `;
                showToast('Erreur de connexion au serveur', 'error');
            });
    });
}



function closeDetailModal() {
    document.getElementById('detailModal').classList.remove('active');
}

function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`.tab-btn[data-tab="${tab}"]`).classList.add('active');

    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });
    document.getElementById(`tab-${tab}`).classList.add('active');
}

function saveInscription() {
    // Validate required fields
    const code = document.getElementById('code').value;
    const label = document.getElementById('label').value;
    const concours_id = document.getElementById('concours_id').value;
    const candidat_id = document.getElementById('candidat_id').value;
    const civilite = document.getElementById('civilite').value;

    if (!code || !label || !concours_id || !candidat_id || !civilite) {
        showToast('Veuillez remplir tous les champs obligatoires (*)', 'warning');
        switchTab('info');
        return;
    }

    const id = document.getElementById('inscriptionId').value;

    const data = {
        code: code,
        label: label,
        concours_id: parseInt(concours_id),
        candidat_id: parseInt(candidat_id),
        civilite: civilite,
        etat_inscription: document.getElementById('etat_inscription').value,
        resultat_inscription: document.getElementById('resultat_inscription').value,
        active: parseInt(document.getElementById('active').value),
        description: document.getElementById('description').value,
        annee_bac: document.getElementById('annee_bac').value || null,
        specialite_bac: document.getElementById('specialite_bac').value || null,
        mention_bac: document.getElementById('mention_bac').value || null,
        moyenne_general_bac: document.getElementById('moyenne_general_bac').value || null,
        type_etablissement_bac: document.getElementById('type_etablissement_bac').value || null,
        province: document.getElementById('province').value || null,
        type_diplome_obtenu: document.getElementById('type_diplome_obtenu').value || null,
        specialite_diplome: document.getElementById('specialite_diplome').value || null,
        anne_obtention_diplome: document.getElementById('anne_obtention_diplome').value || null,
        etablissement_origine: document.getElementById('etablissement_origine').value || null,
        module_valide: parseInt(document.getElementById('module_valide').value) || 0,
        duree_diplome: document.getElementById('duree_diplome').value || null,
        note_s1: document.getElementById('note_s1').value || null,
        note_s2: document.getElementById('note_s2').value || null,
        note_s3: document.getElementById('note_s3').value || null,
        note_s4: document.getElementById('note_s4').value || null,
        note_s5: document.getElementById('note_s5').value || null,
        note_s6: document.getElementById('note_s6').value || null,
        moyenne_ecrit: document.getElementById('moyenne_ecrit').value || null,
        moyenne_orale: document.getElementById('moyenne_orale').value || null
    };

    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : API_BASE_URL;
    const method = id ? 'PUT' : 'POST';

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadInscriptions();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur: Save' + error, 'error');
            console.error('Error:', error);
        });
}

function deleteInscription(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette inscription ?')) return;

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                loadInscriptions();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur: Delete' + error, 'error');
            console.error('Error:', error);
        });
}

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

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');
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <span class="toast-icon">${getToastIcon(type)}</span>
        <span class="toast-message">${message}</span>
        <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    container.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }
    }, 4000);
}

function getToastIcon(type) {
    const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };
    return icons[type] || 'ℹ️';
}

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

// Close modal on overlay click
document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function (e) {
        if (e.target === this) {
            if (this.id === 'detailModal') {
                closeDetailModal();
            } else {
                closeModal();
            }
        }
    });
});

function closeCsvModal() {
    const modal = document.getElementById('importCsvModal');
    if (modal) {
        modal.remove();
    }
}

/**
 * Download CSV template file
 */
function downloadTemplate() {
    // Afficher une notification de chargement
    showToast('Préparation du téléchargement...', 'info');

    // Utiliser l'API pour télécharger le fichier
    const downloadUrl = `${API_BASE_URL}?action=download_template&download=true`;

    // Créer un lien de téléchargement
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'template_import_inscriptions.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showToast('Téléchargement du template démarré', 'success');
}

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

function downloadDocument(id) {
    showToast('Préparation du téléchargement du dossier...', 'info');

    // Show loading state on the button
    const buttons = document.querySelectorAll(`button[onclick="downloadDocument(${id})"]`);
    buttons.forEach(btn => {
        btn.disabled = true;
        btn.innerHTML = '⏳ Téléchargement...';
    });

    // Create a form to submit the download request
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `${API_BASE_URL}?action=download_doc`;
    form.target = '_blank';

    // Add the inscription ID
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'id';
    input.value = id;
    form.appendChild(input);

    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);

    // Reset button state after a delay
    setTimeout(() => {
        buttons.forEach(btn => {
            btn.disabled = false;
            btn.innerHTML = '📥';
        });
    }, 3000);

    showToast('Téléchargement du dossier démarré...', 'success');
}
function downloadAllDocsByConcours() {
    const concoursId = document.getElementById('searchConcours').value;
    if (!concoursId) {
        showToast('Veuillez sélectionner un concours d\'abord', 'warning');
        return;
    }
    window.location.href = `${API_BASE_URL}?action=download_all_concours_docs&concours_id=${concoursId}`;
}

function downloadAllDocsForCandidat(id) {
    if (!id) {
        showToast('ID non valide', 'error');
        return;
    }

    window.location.href = `/est-concours/model/api/inscription.php?action=download_all&id=${id}`;
}