<!-- app/view/admin/pedagogie/presence/create-edit/modal.php -->

<div class="modal-overlay" id="presenceModal">
    <div class="modal modal-lg">
        <div class="modal-header" style="background:#f8f9fa;border-bottom:2px solid #2c3e50;">
            <h2 id="presenceModalTitle">
                <i class="fas fa-clipboard-list" style="color:#27ae60;"></i>
                Feuille de présence - Boulienne
            </h2>
            <button class="modal-close" onclick="closePresenceModal()">&times;</button>
        </div>

        <div class="modal-body">
            <form id="presenceForm">
                <input type="hidden" id="presenceId" value="">

                <!-- En-tête -->
                <div style="background:#f8f9fa;padding:15px;border-radius:8px;margin-bottom:20px;border:1px solid #dee2e6;">
                    <div class="form-row">
                        <div class="form-group" style="flex:2;">
                            <label><i class="fas fa-book"></i> Cours <span class="required">*</span></label>
                            <select id="affectation_id" class="form-control" required onchange="loadStudentsForAffectation(this.value)">
                                <option value="">Sélectionner un cours</option>
                            </select>
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label><i class="fas fa-calendar"></i> Date <span class="required">*</span></label>
                            <input type="date" id="date_seance" class="form-control" required>
                        </div>
                    </div>
                    <div class="form-row" style="margin-top:10px;">
                        <div class="form-group" style="flex:1;">
                            <label><i class="fas fa-clock"></i> Heure de début <span class="required">*</span></label>
                            <input type="time" id="heure_debut" class="form-control" required value="08:00">
                        </div>
                        <div class="form-group" style="flex:0.5;">
                            <label><i class="fas fa-hourglass-half"></i> Nb d'heures <span class="required">*</span></label>
                            <select id="nb_heures" class="form-control" required>
                                <option value="1">1h</option>
                                <option value="2" selected>2h</option>
                                <option value="3">3h</option>
                                <option value="4">4h</option>
                                <option value="5">5h</option>
                                <option value="6">6h</option>
                            </select>
                        </div>
                        <div class="form-group" style="flex:1.5;">
                            <label><i class="fas fa-tag"></i> Libellé</label>
                            <input type="text" id="libelle_seance" class="form-control" placeholder="Libellé de la séance">
                        </div>
                    </div>
                    <div style="margin-top:10px;padding:10px;background:#eaf4ea;border-radius:5px;font-size:14px;color:#2c3e50;display:flex;flex-wrap:wrap;gap:15px;">
                        <span><i class="fas fa-user-tie"></i> <strong>Professeur :</strong> <span id="professeurInfo">-</span></span>
                        <span><i class="fas fa-graduation-cap"></i> <strong>Filière :</strong> <span id="filiereInfo">-</span></span>
                        <span><i class="fas fa-layer-group"></i> <strong>Semestre :</strong> <span id="semestreInfo">-</span></span>
                        <span><i class="fas fa-calendar-alt"></i> <strong>Année :</strong> <span id="anneeInfo">-</span></span>
                        <span><i class="fas fa-calendar-day"></i> <strong>Jour :</strong> <span id="jourInfo">-</span></span>
                    </div>
                    <div id="conflictWarning" style="display:none;margin-top:10px;padding:10px;background:#f8d7da;border-radius:5px;border-left:4px solid #e74c3c;color:#721c24;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <span id="conflictMessage">Une séance existe déjà pour ce cours à cette date et heure.</span>
                    </div>
                </div>

                <!-- Liste des étudiants -->
                <div style="border:1px solid #dee2e6;border-radius:8px;padding:15px;background:white;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;flex-wrap:wrap;">
                        <h3 style="margin:0;color:#2c3e50;font-size:18px;">
                            <i class="fas fa-users"></i> Liste des étudiants
                            <span style="font-size:14px;font-weight:400;color:#7f8c8d;margin-left:10px;" id="totalStudents">(0)</span>
                        </h3>
                        <div style="display:flex;gap:10px;flex-wrap:wrap;">
                            <button type="button" class="btn btn-sm btn-success" onclick="markAllPresent()">
                                <i class="fas fa-check"></i> Tout Présent (P)
                            </button>
                            <button type="button" class="btn btn-sm btn-danger" onclick="markAllAbsent()">
                                <i class="fas fa-times"></i> Tout Absent (A)
                            </button>
                        </div>
                    </div>

                    <div id="studentList" style="overflow-x:auto;">
                        <div style="text-align:center;padding:40px;color:#7f8c8d;">
                            <i class="fas fa-hand-pointer" style="font-size:40px;display:block;margin-bottom:10px;"></i>
                            Sélectionnez un cours pour charger les étudiants
                        </div>
                    </div>
                </div>

                <!-- Légende -->
                <div style="display:flex;gap:20px;margin-top:15px;padding:10px;background:#f8f9fa;border-radius:5px;font-size:13px;flex-wrap:wrap;">
                    <span><span style="display:inline-block;width:20px;height:20px;background:#27ae60;border-radius:4px;vertical-align:middle;text-align:center;color:white;font-weight:bold;line-height:20px;">P</span> = Présent</span>
                    <span><span style="display:inline-block;width:20px;height:20px;background:#e74c3c;border-radius:4px;vertical-align:middle;text-align:center;color:white;font-weight:bold;line-height:20px;">A</span> = Absent</span>
                    <span><i class="fas fa-pencil-alt" style="color:#f39c12;"></i> Cliquez sur P/A pour modifier</span>
                    <span><i class="fas fa-comment" style="color:#3498db;"></i> Description = Observations</span>
                </div>
            </form>
        </div>

        <div class="modal-footer" style="border-top:2px solid #eee;padding:15px;">
            <button class="btn btn-secondary" onclick="closePresenceModal()">
                <i class="fas fa-times"></i> Annuler
            </button>
            <button class="btn btn-primary" onclick="savePresence()">
                <i class="fas fa-save"></i> Enregistrer
            </button>
        </div>
    </div>
</div>

<style>
    .bulletin-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }
    .bulletin-table th {
        background: #2c3e50;
        color: white;
        padding: 10px 12px;
        text-align: left;
        font-weight: 600;
        font-size: 13px;
        text-transform: uppercase;
        position: sticky;
        top: 0;
        z-index: 10;
    }
    .bulletin-table td {
        padding: 8px 12px;
        border-bottom: 1px solid #ecf0f1;
        vertical-align: middle;
    }
    .bulletin-table tr:hover {
        background: #f8f9fa;
    }
    .bulletin-table .num {
        width: 40px;
        text-align: center;
        font-weight: 600;
        color: #7f8c8d;
    }
    .bulletin-table .nom {
        font-weight: 600;
        color: #2c3e50;
    }
    .bulletin-table .prenom {
        color: #34495e;
    }
    .btn-status {
        width: 44px;
        height: 38px;
        border: 2px solid #ddd;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 700;
        font-size: 15px;
        transition: all 0.2s;
        background: white;
        font-family: 'Arial', sans-serif;
    }
    .btn-status:hover {
        transform: scale(1.08);
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }
    .btn-status.active-present {
        background: #27ae60;
        color: white;
        border-color: #27ae60;
        box-shadow: 0 0 0 3px rgba(39,174,96,0.3);
    }
    .btn-status.active-absent {
        background: #e74c3c;
        color: white;
        border-color: #e74c3c;
        box-shadow: 0 0 0 3px rgba(231,76,60,0.3);
    }
    .btn-status:not(.active-present):not(.active-absent):hover {
        border-color: #3498db;
    }
    .status-legend {
        display: inline-block;
        padding: 3px 14px;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 600;
    }
    .status-legend.present {
        background: #d4edda;
        color: #155724;
    }
    .status-legend.absent {
        background: #f8d7da;
        color: #721c24;
    }
    .desc-input {
        width: 100%;
        padding: 5px 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 13px;
        transition: border-color 0.2s;
        background: #fafafa;
    }
    .desc-input:focus {
        border-color: #3498db;
        outline: none;
        background: white;
    }
    .desc-input::placeholder {
        color: #bbb;
        font-style: italic;
        font-size: 12px;
    }
    .modal-lg {
        max-width: 1100px !important;
        width: 95% !important;
    }
    #studentList {
        max-height: 500px;
        overflow-y: auto;
    }
    #studentList::-webkit-scrollbar {
        width: 6px;
    }
    #studentList::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }
    #studentList::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
    }
    #studentList::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
    .form-row {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
    }
    .form-group {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }
    .form-group label {
        font-size: 13px;
        font-weight: 600;
        color: #2c3e50;
    }
    .form-control {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        background: white;
        min-width: 120px;
    }
    .form-control:focus {
        border-color: #3498db;
        outline: none;
        box-shadow: 0 0 0 3px rgba(52,152,219,0.2);
    }
    .required {
        color: #e74c3c;
    }
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 18px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
        text-decoration: none;
    }
    .btn-primary {
        background: #3498db;
        color: white;
    }
    .btn-primary:hover {
        background: #2980b9;
    }
    .btn-success {
        background: #27ae60;
        color: white;
    }
    .btn-success:hover {
        background: #1e8449;
    }
    .btn-danger {
        background: #e74c3c;
        color: white;
    }
    .btn-danger:hover {
        background: #c0392b;
    }
    .btn-secondary {
        background: #ecf0f1;
        color: #2c3e50;
    }
    .btn-secondary:hover {
        background: #d5dbdb;
    }
    .btn-sm {
        padding: 5px 12px;
        font-size: 12px;
    }
    @media (max-width: 768px) {
        .bulletin-table th,
        .bulletin-table td {
            padding: 6px 8px;
            font-size: 12px;
        }
        .btn-status {
            width: 34px;
            height: 32px;
            font-size: 12px;
        }
        .desc-input {
            font-size: 11px;
            padding: 3px 5px;
            min-width: 60px;
        }
        .modal-lg {
            max-width: 100% !important;
            width: 100% !important;
            margin: 10px;
        }
        .form-row {
            flex-direction: column;
            gap: 10px;
        }
    }
    @media print {
        .modal-overlay { position: static; }
        .modal { box-shadow: none; border: 1px solid #ddd; }
        .btn-status { border: 1px solid #999; }
        .btn-status.active-present { background: #27ae60 !important; }
        .btn-status.active-absent { background: #e74c3c !important; }
        .no-print { display: none !important; }
        .modal-footer { display: none; }
    }
</style>

<script>
    let studentsData = [];
    let currentAffectationData = null;
    let isEditMode = false;
    let checkConflictTimeout = null;

    function openPresenceModal(data = null) {
        const modal = document.getElementById('presenceModal');
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';

        if (data && data.id) {
            isEditMode = true;
            document.getElementById('presenceId').value = data.id;
            document.getElementById('presenceModalTitle').innerHTML =
                '<i class="fas fa-edit" style="color:#f39c12;"></i> Modifier la feuille de présence';
            loadPresenceData(data.id);
        } else {
            isEditMode = false;
            document.getElementById('presenceId').value = '';
            document.getElementById('presenceModalTitle').innerHTML =
                '<i class="fas fa-clipboard-list" style="color:#27ae60;"></i> Feuille de présence - Nouvelle séance';

            const now = new Date();
            document.getElementById('date_seance').value = now.toISOString().split('T')[0];
            document.getElementById('heure_debut').value = '08:00';
            document.getElementById('nb_heures').value = '2';
            document.getElementById('libelle_seance').value = '';
            document.getElementById('affectation_id').value = '';
            document.getElementById('professeurInfo').textContent = '-';
            document.getElementById('filiereInfo').textContent = '-';
            document.getElementById('semestreInfo').textContent = '-';
            document.getElementById('anneeInfo').textContent = '-';
            document.getElementById('jourInfo').textContent = '-';
            document.getElementById('conflictWarning').style.display = 'none';
            document.getElementById('studentList').innerHTML = `
                <div style="text-align:center;padding:40px;color:#7f8c8d;">
                    <i class="fas fa-hand-pointer" style="font-size:40px;display:block;margin-bottom:10px;"></i>
                    Sélectionnez un cours pour charger les étudiants
                </div>
            `;
            document.getElementById('totalStudents').textContent = '(0)';
            loadAffectationsForSelect();
        }
    }

    function closePresenceModal() {
        const modal = document.getElementById('presenceModal');
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }

    function loadAffectationsForSelect() {
        fetch('/est-concours/model/api/presence.php?action=get_modules_with_affectations')
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    const select = document.getElementById('affectation_id');
                    select.innerHTML = '<option value="">Sélectionner un cours</option>';
                    (result.data.data || []).forEach(a => {
                        select.innerHTML += `
                            <option value="${a.id}"
                                    data-professeur="${a.employee_fullname || ''}"
                                    data-filiere="${a.filiere_libelle || ''}"
                                    data-semestre="${a.semestre_libelle || ''}"
                                    data-annee="${a.annee_universitaire || ''}">
                                ${a.module_libelle} - ${a.employee_fullname} (${a.annee_universitaire})
                            </option>
                        `;
                    });
                }
            })
            .catch(() => alert('Erreur de chargement des cours'));
    }

    function loadPresenceData(id) {
        fetch('/est-concours/model/api/presence.php?action=get&id=' + id)
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    const data = result.data;
                    document.getElementById('affectation_id').value = data.affectation_id || data.inscription_module_id;
                    document.getElementById('date_seance').value = data.date_seance;
                    document.getElementById('heure_debut').value = data.heure_debut || '08:00';
                    document.getElementById('nb_heures').value = data.nb_heures || 2;
                    document.getElementById('libelle_seance').value = data.libelle || '';
                    document.getElementById('jourInfo').textContent = data.jour_semaine || getJourSemaine(data.date_seance);

                    const select = document.getElementById('affectation_id');
                    const opt = select.querySelector(`option[value="${data.affectation_id || data.inscription_module_id}"]`);
                    if (opt) {
                        document.getElementById('professeurInfo').textContent = opt.dataset.professeur || data.employee_fullname || '-';
                        document.getElementById('filiereInfo').textContent = opt.dataset.filiere || data.filiere_libelle || '-';
                        document.getElementById('semestreInfo').textContent = opt.dataset.semestre || data.semestre_libelle || '-';
                        document.getElementById('anneeInfo').textContent = opt.dataset.annee || data.annee_universitaire || '-';
                    }

                    studentsData = data.students || [];
                    renderStudentList(studentsData);
                    checkConflict();
                } else {
                    alert('Erreur: ' + result.message);
                }
            })
            .catch(() => alert('Erreur de connexion'));
    }

    function getJourSemaine(dateStr) {
        if (!dateStr) return '-';
        const d = new Date(dateStr + 'T00:00:00');
        const jours = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
        return jours[d.getDay()];
    }

    function loadStudentsForAffectation(affectationId) {
        if (!affectationId) {
            document.getElementById('studentList').innerHTML = `
                <div style="text-align:center;padding:40px;color:#7f8c8d;">
                    <i class="fas fa-hand-pointer" style="font-size:40px;display:block;margin-bottom:10px;"></i>
                    Sélectionnez un cours pour charger les étudiants
                </div>
            `;
            document.getElementById('totalStudents').textContent = '(0)';
            document.getElementById('conflictWarning').style.display = 'none';
            return;
        }

        const select = document.getElementById('affectation_id');
        const selectedOption = select.options[select.selectedIndex];
        document.getElementById('professeurInfo').textContent = selectedOption.dataset.professeur || '-';
        document.getElementById('filiereInfo').textContent = selectedOption.dataset.filiere || '-';
        document.getElementById('semestreInfo').textContent = selectedOption.dataset.semestre || '-';
        document.getElementById('anneeInfo').textContent = selectedOption.dataset.annee || '-';

        fetch('/est-concours/model/api/presence.php?action=get_students&inscription_module_id=' + affectationId)
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    studentsData = (result.data || []).map(s => ({
                        ...s,
                        present: 0,
                        description: null
                    }));
                    renderStudentList(studentsData);
                    checkConflict();
                } else {
                    alert('Erreur: ' + result.message);
                }
            })
            .catch(() => alert('Erreur de connexion'));
    }

    function renderStudentList(students) {
        const container = document.getElementById('studentList');
        document.getElementById('totalStudents').textContent = `(${students.length})`;

        if (!students || students.length === 0) {
            container.innerHTML = `
                <div style="text-align:center;padding:40px;color:#7f8c8d;">
                    <i class="fas fa-users" style="font-size:40px;display:block;margin-bottom:10px;"></i>
                    Aucun étudiant trouvé pour cette filière
                </div>
            `;
            return;
        }

        let html = `
            <table class="bulletin-table">
                <thead>
                    <tr>
                        <th style="width:40px;">#</th>
                        <th style="min-width:120px;">NOM</th>
                        <th style="min-width:100px;">PRÉNOM</th>
                        <th style="width:60px;text-align:center;">P</th>
                        <th style="width:60px;text-align:center;">A</th>
                        <th style="min-width:120px;">STATUT</th>
                        <th style="min-width:160px;">OBSERVATION</th>
                    </tr>
                </thead>
                <tbody>
        `;

        students.forEach((s, index) => {
            const isPresent = s.present === 1;
            const statusClass = isPresent ? 'present' : 'absent';
            const statusText = isPresent ? '✅ Présent' : '❌ Absent';
            const activeP = isPresent ? 'active-present' : '';
            const activeA = !isPresent ? 'active-absent' : '';
            const descValue = s.description || '';

            html += `
                <tr>
                    <td class="num">${index + 1}</td>
                    <td class="nom">${escapeHtml(s.nom)}</td>
                    <td class="prenom">${escapeHtml(s.prenom)}</td>
                    <td style="text-align:center;">
                        <button type="button"
                                class="btn-status ${activeP}"
                                onclick="setStatus(${s.id}, 1)"
                                data-student="${s.id}"
                                title="Présent">
                            P
                        </button>
                    </td>
                    <td style="text-align:center;">
                        <button type="button"
                                class="btn-status ${activeA}"
                                onclick="setStatus(${s.id}, 0)"
                                data-student="${s.id}"
                                title="Absent">
                            A
                        </button>
                    </td>
                    <td style="text-align:center;">
                        <span class="status-legend ${statusClass}">${statusText}</span>
                    </td>
                    <td>
                        <input type="text" class="desc-input"
                               value="${escapeHtml(descValue)}"
                               placeholder="Observation (retard, justifié...)"
                               onchange="updateDescription(${s.id}, this.value)"
                               data-student="${s.id}">
                    </td>
                </tr>
            `;
        });

        html += `</tbody></table>`;
        container.innerHTML = html;
    }

    function setStatus(studentId, status) {
        const student = studentsData.find(s => s.id === studentId);
        if (student) {
            student.present = status;
        }
        renderStudentList(studentsData);
    }

    function updateDescription(studentId, value) {
        const student = studentsData.find(s => s.id === studentId);
        if (student) {
            student.description = value || null;
        }
    }

    function markAllPresent() {
        studentsData.forEach(s => s.present = 1);
        renderStudentList(studentsData);
    }

    function markAllAbsent() {
        studentsData.forEach(s => s.present = 0);
        renderStudentList(studentsData);
    }

    // ============================================
    // VÉRIFICATION DES CONFLITS
    // ============================================
    function checkConflict() {
        const affectationId = document.getElementById('affectation_id').value;
        const date = document.getElementById('date_seance').value;
        const heure = document.getElementById('heure_debut').value;
        const presenceId = document.getElementById('presenceId').value;

        if (date) {
            document.getElementById('jourInfo').textContent = getJourSemaine(date);
        }

        if (!affectationId || !date || !heure) {
            document.getElementById('conflictWarning').style.display = 'none';
            return;
        }

        if (checkConflictTimeout) {
            clearTimeout(checkConflictTimeout);
        }

        checkConflictTimeout = setTimeout(() => {
            const url = '/est-concours/model/api/presence.php?action=check_conflict&inscription_module_id=' + affectationId + '&date=' + date + '&heure=' + heure + (presenceId ? '&exclude_id=' + presenceId : '');

            fetch(url)
                .then(r => r.json())
                .then(result => {
                    const warning = document.getElementById('conflictWarning');
                    if (result.success && result.hasConflict) {
                        warning.style.display = 'block';
                        document.getElementById('conflictMessage').textContent =
                            '⚠️ Une séance existe déjà pour ce cours le ' + formatDate(date) + ' à ' + heure + ' (' + (result.existingLibelle || 'Séance existante') + ')';
                    } else {
                        warning.style.display = 'none';
                    }
                })
                .catch(() => {});
        }, 500);
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('affectation_id').addEventListener('change', checkConflict);
        document.getElementById('date_seance').addEventListener('change', checkConflict);
        document.getElementById('date_seance').addEventListener('input', checkConflict);
        document.getElementById('heure_debut').addEventListener('change', checkConflict);
        document.getElementById('heure_debut').addEventListener('input', checkConflict);
    });

    // ============================================
    // SAUVEGARDE
    // ============================================
    function savePresence() {
        const affectationId = document.getElementById('affectation_id').value;
        const date = document.getElementById('date_seance').value;
        const heure = document.getElementById('heure_debut').value;
        const nbHeures = document.getElementById('nb_heures').value;
        const libelle = document.getElementById('libelle_seance').value;
        const presenceId = document.getElementById('presenceId').value;

        if (!affectationId || !date || !heure) {
            alert('Veuillez sélectionner un cours, une date et une heure');
            return;
        }

        if (studentsData.length === 0) {
            alert('Aucun étudiant à enregistrer');
            return;
        }

        const checkUrl = '/est-concours/model/api/presence.php?action=check_conflict&inscription_module_id=' + affectationId + '&date=' + date + '&heure=' + heure + (presenceId ? '&exclude_id=' + presenceId : '');

        fetch(checkUrl)
            .then(r => r.json())
            .then(checkResult => {
                if (checkResult.success && checkResult.hasConflict) {
                    if (!confirm('⚠️ Une séance existe déjà pour ce cours le ' + formatDate(date) + ' à ' + heure + '.\n\nVoulez-vous quand même enregistrer ?')) {
                        return;
                    }
                }

                const presences = studentsData.map(s => ({
                    student_id: s.id,
                    present: s.present !== undefined ? s.present : 0,
                    description: s.description || null
                }));

                const data = {
                    inscription_module_id: parseInt(affectationId),
                    date: date,
                    heure_debut: heure,
                    nb_heures: parseInt(nbHeures),
                    libelle: libelle || 'Séance du ' + formatDate(date) + ' à ' + heure,
                    presences: presences
                };

                const url = presenceId ?
                    '/est-concours/model/api/presence.php?action=update&id=' + presenceId :
                    '/est-concours/model/api/presence.php';

                const method = presenceId ? 'PUT' : 'POST';

                return fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
            })
            .then(response => {
                if (!response) return;
                return response.json();
            })
            .then(result => {
                if (result && result.success) {
                    alert('✅ Feuille de présence enregistrée avec succès');
                    closePresenceModal();
                    location.reload();
                } else if (result) {
                    alert('❌ Erreur: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Erreur:', error);
                alert('❌ Erreur de connexion');
            });
    }

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

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

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && document.getElementById('presenceModal').classList.contains('active')) {
            closePresenceModal();
        }
    });

    document.getElementById('presenceModal').addEventListener('click', function(e) {
        if (e.target === this) closePresenceModal();
    });
</script>