// js/inscriptions.js
const API_BASE_URL = '/est-concours/model/api/inscription.php';
let currentPage = 1;
const perPage = 9;
let totalPages = 1;
let editMode = false;
let concoursList = [];
let candidatsList = [];
let diplomeTypes = [];
let selectedIds = new Set();
let currentData = [];

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

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 loadDiplomeTypes() {
    fetch(`${API_BASE_URL}?action=types_diplome`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                diplomeTypes = result.data;
                populateDiplomeDropdowns();
            }
        })
        .catch(error => console.error('Error loading diplome types:', error));
}

function populateConcoursDropdowns() {
    const selects = ['searchConcours', 'concours_id', 'importOraleConcoursId'];
    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 populateDiplomeDropdowns() {
    const select = document.getElementById('searchDiplome');
    if (select) {
        const firstOption = select.options[0];
        select.innerHTML = '';
        select.appendChild(firstOption);

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

function loadInscriptions() {
    showLoading(true);
    selectedIds.clear();
    updateMultiSelectActions();

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

        type_diplome_id: document.getElementById('searchDiplome').value || '',
        page: currentPage,
        per_page: perPage,
        singlePage: true,
        dataMode: 'preparation-orale'
    };

    // 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) {
                if (result.data && result.data.data) {
                    currentData = result.data.data;
                    renderTableGrouped(result.data.data);
                } else if (Array.isArray(result.data)) {
                    currentData = result.data;
                    renderTableGrouped(result.data);
                    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 {
                    currentData = [];
                    renderTableGrouped([]);
                }
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
                renderTableGrouped([]);
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur: ' + error.message, 'error');
            console.error('Error:', error);
            renderTableGrouped([]);
        });
}

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 renderTableGrouped(inscriptions) {
    const tbody = document.getElementById('tableBody');

    if (!inscriptions || inscriptions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <!-- تم تعديل الـ colspan هنا أيضاً لتغطية الجدول بالكامل عند عدم وجود بيانات -->
                <td colspan="10" 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;
    }

    // Group by diplome type
    const groups = {};
    inscriptions.forEach(item => {
        const diplomeLabel = item.type_diplome_libelle || getDiplomeLabel(item.type_diplome_obtenu);
        const groupKey = item.type_diplome_obtenu || 'unknown';

        if (!groups[groupKey]) {
            groups[groupKey] = {
                label: diplomeLabel,
                items: []
            };
        }
        groups[groupKey].items.push(item);
    });

    // Trie les candidats de chaque groupe par moyenne "avant orale" (meilleure moyenne en premier)
    Object.keys(groups).forEach(groupKey => {
        groups[groupKey].items.sort((a, b) => {
            const avantA = parseFloat(a.moyenne_calcule_avant_orale);
            const avantB = parseFloat(b.moyenne_calcule_avant_orale);
            const valA = isNaN(avantA) ? -Infinity : avantA;
            const valB = isNaN(avantB) ? -Infinity : avantB;
            return valB - valA;
        });
    });

    let html = '';
    const sortedGroupKeys = Object.keys(groups).sort((a, b) => {
        const labelA = groups[a].label;
        const labelB = groups[b].label;
        return labelA.localeCompare(labelB);
    });

    sortedGroupKeys.forEach(groupKey => {
        const group = groups[groupKey];
        const count = group.items.length;

        // تعديل colspan بعد حذف عمود ORALE
        html += `
            <tr class="group-header">
                <td colspan="10">
                    <div class="group-title">
                        <span>🎓 ${escapeHtml(group.label)}</span>
                        <span class="badge-group">${count}</span>
                    </div>
                </td>
            </tr>
        `;

        // Items in this group
        group.items.forEach(item => {
            const concours = item.concours || {};
            const candidat = item.candidat || {};
            const isChecked = selectedIds.has(item.id);

            html += `
                <tr data-id="${item.id}">
                    <td class="checkbox-col">
                        <input type="checkbox" class="row-checkbox" data-id="${item.id}" 
                               ${isChecked ? 'checked' : ''} onchange="toggleRowSelection(${item.id})">
                    </td>
                   
                    <td>${escapeHtml(concours.code || '-')}</td>
                    <td>${escapeHtml(candidat.nom || '')} ${escapeHtml(candidat.prenom || '')}</td>
                    
                    <!-- تم إضافة الحقول الجديدة هنا قبل المعدل -->
                    <td>${escapeHtml(item.specialite_bac || '-')}</td>
                    <td>${item.annee_bac || '-'}</td>
                    
                    <td>${item.moyenne_general_calcule || '-'}</td>
                    <td>${item.moyenne_ecrit || '-'}</td>
                    <td>${item.moyenne_calcule_avant_orale || '-'}</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})">👁️</button>
                        <button class="btn btn-warning btn-sm" onclick="openEditModal(${item.id})">✏️</button>
                        <button class="btn btn-danger btn-sm" onclick="deleteInscription(${item.id})">🗑️</button>
                    </td>
                </tr>
            `;
        });
    });

    tbody.innerHTML = html;
    updateMultiSelectActions();
}


// ==================== DOWNLOAD FUNCTIONS ====================

// Trie un tableau d'inscriptions par moyenne "avant orale" décroissante (les valeurs manquantes vont à la fin)
function sortByAvantOrale(data) {
    return [...data].sort((a, b) => {
        const avantA = parseFloat(a.moyenne_calcule_avant_orale);
        const avantB = parseFloat(b.moyenne_calcule_avant_orale);
        const valA = isNaN(avantA) ? -Infinity : avantA;
        const valB = isNaN(avantB) ? -Infinity : avantB;
        return valB - valA;
    });
}

function downloadInscriptions(filterType) {
    // Get current search parameters
    const searchData = {
        action: 'download',
        filter: filterType,
        concours_id: document.getElementById('searchConcours').value || '',
        etat_inscription: document.getElementById('searchEtat').value || '',
        resultat_inscription: document.getElementById('searchResultat').value || '',
        type_diplome_id: document.getElementById('searchDiplome').value || '',
        dataMode: 'preparation-orale'
    };

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

    const params = new URLSearchParams(searchData);
    const url = `${API_BASE_URL}?${params.toString()}`;

    // Show loading state
    const fileName = filterType === 'ALL' ? 'toutes_inscriptions' : 'admis_ecrit';
    showToast('Préparation du téléchargement...', 'info');

    // Fetch and download
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                // Create and download the file
                downloadFile(result.data, fileName);
                showToast(`Téléchargement terminé: ${result.data.length} inscription(s)`, 'success');
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de téléchargement: ' + error.message, 'error');
            console.error('Error:', error);
        });
}

function downloadFile(data, fileName) {
    // Check if data exists
    if (!data || data.length === 0) {
        showToast('Aucune donnée à télécharger', 'warning');
        return;
    }

    // Trie les candidats par moyenne "avant orale" (meilleure moyenne en premier) avant génération du CSV
    data = sortByAvantOrale(data);

    // Convert data to CSV
    const headers = [
        'Email',
        'Civilité',
        'Prénom',
        'Nom',
        'Prénom (Arabe)',
        'Nom (Arabe)',
        'CIN',
        'Téléphone',
        'Situation familiale',
        'Lieu de naissance',
        'Lieu de naissance (Arabe)',
        'Province de naissance',
        'Date de naissance',
        'Adresse',
        'Adresse (Arabe)',
        'Code Postal',
        'Province de résidence',
        'Nationalité',
        'Situation professionnelle',
        'Code MASSAR/CNE',
        'Année du Bac',
        'Spécialité du Baccalauréat',
        'Mention du Bac',
        'Type d\'établissement du Bac',
        'Province du Bac',
        'Moyenne générale du Bac',
        'Type du diplôme obtenu',
        'Spécialité du diplôme',
        'Année d\'obtention du diplôme',
        'Établissement',
        'Note S1',
        'Note S2',
        'Note S3',
        'Note S4',
        'BAC TYPE',
        'DEUX_Spe',
        'DEUX_Dur',
    ];

    const rows = data.map(item => [
        item.candidat?.email || item.candidat_email || item.email || '',                                 // Email
        item.civilite || '',                                                                            // Civilité
        item.candidat?.prenom || item.candidat_prenom || '',                                              // Prénom
        item.candidat?.nom || item.candidat_nom || '',                                                    // Nom
        item.candidat?.prenom_ar || item.prenom_arabe || '',                                                // Prénom (Arabe)
        item.candidat?.nom_ar || item.nom_arabe || '',                                                      // Nom (Arabe)
        item.candidat?.cin || item.candidat_cin || item.cin || '',                                        // CIN
        item.candidat?.telephone || item.candidat_phone || item.telephone || item.phone || '',            // Téléphone
        item.situation_familiale || '',                                                                 // Situation familiale
        item.lieu_naissance || '',                                                                      // Lieu de naissance
        item.lieu_naissance_ar || '',                                                                   // Lieu de naissance (Arabe)
        item.province_naissance || '',                                                                  // Province de naissance
        item.date_naissance || '',                                                                      // Date de naissance
        item.adresse || '',                                                                             // Adresse
        item.adresse_ar || '',                                                                          // Adresse (Arabe)
        item.code_postal || '',                                                                         // Code Postal
        item.province_residence || '',                                                                  // Province de résidence
        item.nationalite || '',                                                                         // Nationalité
        item.situation_professionnelle || '',                                                           // Situation professionnelle
        item.code_massar || item.cne || '',                                                             // Code MASSAR/CNE
        item.annee_bac || '',                                                                           // Année du Bac
        item.specialite_bac || '',                                                                      // Spécialité du Baccalauréat
        item.mention_bac || '',                                                                         // Mention du Bac
        item.type_etablissement_bac || '',                                                              // Type d'établissement du Bac
        item.province_bac || '',                                                                        // Province du Bac
        item.moyenne_general_bac || '',                                                                 // Moyenne générale du Bac
        item.type_diplome?.libelle || item.type_diplome_libelle || getDiplomeLabel(item.type_diplome_obtenu) || '', // Type du diplôme obtenu
        item.specialite_diplome || '',                                                                  // Spécialité du diplôme
        item.anne_obtention_diplome || '',                                                              // Année d'obtention du diplôme
        item.etablissement_origine || '',                                                               // Établissement
        item.note_s1 || '',                                                                             // Note S1
        item.note_s2 || '',                                                                             // Note S2
        item.note_s3 || '',                                                                             // Note S3
        item.note_s4 || '',                                                                             // Note S4
        item.specialite_bac || '',                                                                            // BAC TYPE
        item.duree_diplome || item.deux_dur || '',                                                      // DEUX_Dur
        item.moyenne_general_calcule || item.deux_moy || '',                                            // DEUX_Moy
    ]);

    // Create CSV content
    let csvContent = headers.join(',') + '\n';
    rows.forEach(row => {
        // Escape fields with commas or quotes
        const escapedRow = row.map(field => {
            if (typeof field === 'string' && (field.includes(',') || field.includes('"') || field.includes('\n'))) {
                return `"${field.replace(/"/g, '""')}"`;
            }
            return field;
        });
        csvContent += escapedRow.join(',') + '\n';
    });

    // Create blob with BOM for Excel compatibility
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.download = `${fileName}_${new Date().toISOString().slice(0,10)}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

function getDiplomeLabel(diplomeId) {
    if (!diplomeId) return 'Non défini';
    const found = diplomeTypes.find(d => d.id == diplomeId);
    return found ? found.libelle + ' (' + found.code + ')' : 'ID: ' + diplomeId;
}

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 = {
        'ELIGIBLE_ORALE': 'badge-success',
        'NON_ELIGIBLE_ORALE': 'badge-danger',
        'ELLIBGIBLE_ECRIT': 'badge-info'
    };
    return map[resultat] || 'badge-secondary';
}

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'];
    semestreFields.forEach(field => {
        document.getElementById(field).addEventListener('input', calculateMoyenne);
    });
}

function calculateMoyenne() {
    const notes = [];
    const semestreFields = ['note_s1', 'note_s2', 'note_s3', 'note_s4'];
    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 = '-';
    }
}

// ==================== SELECTION MULTIPLE ====================

function toggleRowSelection(id) {
    if (selectedIds.has(id)) {
        selectedIds.delete(id);
    } else {
        selectedIds.add(id);
    }
    updateMultiSelectActions();
    updateSelectAllState();
}

function toggleSelectAll() {
    const checkboxes = document.querySelectorAll('.row-checkbox');
    const allChecked = document.querySelectorAll('.row-checkbox:checked').length === checkboxes.length;

    if (allChecked) {
        // Deselect all
        selectedIds.clear();
        document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = false);
    } else {
        // Select all visible rows
        document.querySelectorAll('.row-checkbox').forEach(cb => {
            const id = parseInt(cb.dataset.id);
            selectedIds.add(id);
            cb.checked = true;
        });
    }
    updateMultiSelectActions();
}

function updateSelectAllState() {
    const checkboxes = document.querySelectorAll('.row-checkbox');
    const selectAll = document.getElementById('selectAll');
    if (checkboxes.length === 0) {
        selectAll.checked = false;
        selectAll.indeterminate = false;
        return;
    }
    const checkedCount = document.querySelectorAll('.row-checkbox:checked').length;
    if (checkedCount === 0) {
        selectAll.checked = false;
        selectAll.indeterminate = false;
    } else if (checkedCount === checkboxes.length) {
        selectAll.checked = true;
        selectAll.indeterminate = false;
    } else {
        selectAll.checked = false;
        selectAll.indeterminate = true;
    }
}

function updateMultiSelectActions() {
    const actions = document.getElementById('multiSelectActions');
    const count = selectedIds.size;
    document.getElementById('selectedCount').textContent = count;

    if (count > 0) {
        actions.style.display = 'flex';
    } else {
        actions.style.display = 'none';
    }
    // Update checkboxes state
    document.querySelectorAll('.row-checkbox').forEach(cb => {
        const id = parseInt(cb.dataset.id);
        cb.checked = selectedIds.has(id);
    });
    updateSelectAllState();
}

function clearSelection() {
    selectedIds.clear();
    document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = false);
    updateMultiSelectActions();
}

// ==================== BATCH UPDATE ====================

function batchUpdateResultat(newResultat) {
    const ids = Array.from(selectedIds);
    if (ids.length === 0) {
        showToast('Aucune inscription sélectionnée', 'warning');
        return;
    }

    if (!confirm(`Changer le résultat de ${ids.length} inscription(s) en "${newResultat}" ?`)) {
        return;
    }

    const payload = {
        ids: ids,
        resultat_inscription: newResultat
    };

    fetch(`${API_BASE_URL}?action=batchUpdateResultat`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                selectedIds.clear();
                loadInscriptions();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur: ' + error, 'error');
            console.error('Error:', error);
        });
}

// ==================== CRUD OPERATIONS ====================

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;
                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 || '';

                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 || '';

                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('moyenne_ecrit').value = data.moyenne_ecrit || '';
                document.getElementById('moyenne_orale').value = data.moyenne_orale || '';

                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>
    `;
}

// 3. دالة التنقل بين النوافذ الخاصة بالعرض فقط
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 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() {
    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,
        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();
            }
        }
    });
});

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

function downloadAdministrativeOral(filterType) {
    // جلب معايير البحث الحالية من الصفحة
    const searchData = {
        action: 'download',
        filter: filterType,

        concours_id: document.getElementById('searchConcours')?.value || '',
        etat_inscription: document.getElementById('searchEtat')?.value || '',
        resultat_inscription: document.getElementById('searchResultat')?.value || '',

        type_diplome_id: document.getElementById('searchDiplome')?.value || '',
        // ⚠️ تأكد من توافق هذه القيمة مع ما هو موجود في الأزرار الأخرى لصفحة الشفوي
        dataMode: 'preparation-orale'
    };

    // تنظيف الحقول الفارغة
    Object.keys(searchData).forEach(key => {
        if (searchData[key] === '' || searchData[key] === null || searchData[key] === undefined) {
            delete searchData[key];
        }
    });

    const params = new URLSearchParams(searchData);
    const url = `${API_BASE_URL}?${params.toString()}`;

    showToast('Préparation de l\'affichage administratif (Oral)...', 'info');

    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                // استدعاء دالة بناء وتحميل ملف الـ CSV
                downloadAdministrativeFile(result.data, 'affichage_administratif_oral');
                showToast(`Téléchargement terminé: ${result.data.length} inscription(s)`, 'success');
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de téléchargement: ' + error.message, 'error');
            console.error('Error:', error);
        });
}
// 1. الدالة الخاصة بجلب بيانات الشفوي عند الضغط على الزر
function downloadAdministrativeOral(filterType) {
    // جلب معايير البحث الحالية من الصفحة
    const searchData = {
        action: 'download',
        filter: filterType,

        concours_id: document.getElementById('searchConcours')?.value || '',
        etat_inscription: document.getElementById('searchEtat')?.value || '',
        resultat_inscription: document.getElementById('searchResultat')?.value || '',

        type_diplome_id: document.getElementById('searchDiplome')?.value || '',
        // تأكد أن 'preparation-orale' هي القيمة الصحيحة المستعملة في صفحتك لطلب بيانات الشفوي
        dataMode: 'preparation-orale'
    };

    // تنظيف الحقول الفارغة
    Object.keys(searchData).forEach(key => {
        if (searchData[key] === '' || searchData[key] === null || searchData[key] === undefined) {
            delete searchData[key];
        }
    });

    const params = new URLSearchParams(searchData);
    const url = `${API_BASE_URL}?${params.toString()}`;

    showToast('Préparation de l\'affichage administratif (Oral)...', 'info');

    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                // استدعاء الدالة المتواجدة بالأسفل لبناء الملف
                downloadAdministrativeFile(result.data, 'affichage_administratif_oral');
                showToast(`Téléchargement terminé: ${result.data.length} inscription(s)`, 'success');
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de téléchargement: ' + error.message, 'error');
            console.error('Error:', error);
        });
}

// 2. الدالة المسؤولة عن تحويل البيانات إلى CSV وتنزيلها (أضفها هنا لكي تصبح موجودة)
// الدالة المسؤولة عن تحويل البيانات إلى CSV وتنزيلها مع حجب رقم البطاقة الوطنية
function downloadAdministrativeFile(data, fileName) {
    if (!data || data.length === 0) {
        showToast('Aucune donnée à télécharger', 'warning');
        return;
    }

    // دالة فرعية لحجب الـ CIN ديناميكياً (تترك أول حرفين وآخر حرفين وتحول الباقي لـ *)
    function maskCIN(cin) {
        if (!cin) return '';
        const str = String(cin).trim();
        if (str.length <= 4) return str; // في حال كان رقم البطاقة قصيراً جداً لا نقوم بتغييره
        return str.substring(0, 2) + '*'.repeat(str.length - 4) + str.substring(str.length - 2);
    }

    // ترتيب المترشحين حسب معدل "avant orale" (الأفضل أولاً) قبل بناء الـ CSV
    data = sortByAvantOrale(data);

    // الأعمدة المطلوبة
    const headers = ['ID','Nom', 'Prénom', 'CIN'];

    // ترتيب البيانات وتطبيق حجب الـ CIN عند البناء
    const rows = data.map((item, index) => {
        // جلب رقم البطاقة الخام أولاً
        const rawCin = item.candidat?.cin || item.candidat_cin || item.cin || '';

        return [
            index + 1,
            item.candidat?.nom || item.candidat_nom || '',
            item.candidat?.prenom || item.candidat_prenom || '',
            maskCIN(rawCin) // 💡 هنا يتم تحويل الرقم إلى الصيغة المحجوبة (مثل RT****34)
        ];
    });

    // إنشاء محتوى الـ CSV
    let csvContent = headers.join(',') + '\n';
    rows.forEach(row => {
        const escapedRow = row.map(field => {
            const fieldStr = String(field);
            if (fieldStr.includes(',') || fieldStr.includes('"') || fieldStr.includes('\n')) {
                return `"${fieldStr.replace(/"/g, '""')}"`;
            }
            return fieldStr;
        });
        csvContent += escapedRow.join(',') + '\n';
    });

    // تحميل الملف مباشرة للمستخدم بصيغة تدعم الإكسل واللغة العربية
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.download = `${fileName}_${new Date().toISOString().slice(0,10)}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

// ==================== IMPORT NOTES "ÉCRIT + AVANT ORALE" (par CIN) ====================

function openImportAvantOraleModal() {
    // S'assure que la liste des concours est à jour dans le select
    if (concoursList && concoursList.length > 0) {
        populateConcoursDropdowns();
    }
    document.getElementById('importAvantOraleForm').reset();
    document.getElementById('importAvantOraleModal').style.display = 'flex';
}

function closeImportAvantOraleModal() {
    document.getElementById('importAvantOraleModal').style.display = 'none';
}

function setupImportAvantOraleForm() {
    const form = document.getElementById('importAvantOraleForm');
    if (form) {
        form.addEventListener('submit', submitImportAvantOrale);
    }

    // Fermer si on clique en dehors de la boîte du modal
    const overlay = document.getElementById('importAvantOraleModal');
    if (overlay) {
        overlay.addEventListener('click', function (e) {
            if (e.target === overlay) {
                closeImportAvantOraleModal();
            }
        });
    }
}

function submitImportAvantOrale(e) {
    e.preventDefault();

    const concoursId = document.getElementById('importOraleConcoursId').value;
    const fileInput = document.getElementById('importAvantOraleFile');

    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 formData = new FormData();
    formData.append('action', 'import_ecrit_avant_orale');
    formData.append('concours_id', concoursId);
    formData.append('csv_file', fileInput.files[0]);

    showToast('Importation en cours...', 'info');

    fetch(API_BASE_URL, {
        method: 'POST',
        body: formData
    })
        .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');
                closeImportAvantOraleModal();
                loadInscriptions();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur: ' + error.message, 'error');
            console.error('Error:', error);
        });
}

// ==================== EXEMPLE CSV : ÉCRIT + AVANT ORALE ====================

// Génère un exemple de CSV en utilisant les vrais candidats inscrits au concours sélectionné,
// pour éviter que l'admin doive remplacer manuellement des CIN fictifs.
function downloadSampleCsvEcritAvantOrale() {
    const concoursId = document.getElementById('importOraleConcoursId').value;

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

    showToast('Préparation de l\'exemple CSV...', 'info');

    fetch(`${API_BASE_URL}?action=export_sample_avant_orale&concours_id=${encodeURIComponent(concoursId)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                buildSampleCsvEcritAvantOrale(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur: ' + error.message, 'error');
            console.error('Error:', error);
        });
}

function buildSampleCsvEcritAvantOrale(candidats) {
    if (!candidats || candidats.length === 0) {
        showToast('Aucun candidat trouvé pour ce concours', 'warning');
        return;
    }

    let csvContent = "CIN;moyenne_ecrit;moyenne_calcule_avant_orale\r\n";
    candidats.forEach(c => {
        const cin = (c.cin || '').trim();
        if (!cin) return;
        const ecrit = (c.moyenne_ecrit !== null && c.moyenne_ecrit !== undefined) ? c.moyenne_ecrit : '';
        const avantOrale = (c.moyenne_calcule_avant_orale !== null && c.moyenne_calcule_avant_orale !== undefined)
            ? c.moyenne_calcule_avant_orale
            : '';
        csvContent += `${cin};${ecrit};${avantOrale}\r\n`;
    });

    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.download = 'exemple_ecrit_avant_orale.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}