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

<div id="detailModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 900px;">
        <div class="modal-header">
            <h2><i class="fas fa-clipboard-list" style="color:#27ae60;"></i> Détails de la séance</h2>
            <button type="button" class="modal-close" onclick="closeDetailModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="detailContent">
                <div class="loading active">
                    <div class="spinner"></div>
                    <p style="margin-top:10px;">Chargement des détails...</p>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeDetailModal()">
                <i class="fas fa-times"></i> Fermer
            </button>
            <button type="button" class="btn btn-warning" id="editFromDetailBtn" onclick="editFromDetail()" style="display:none;">
                <i class="fas fa-edit"></i> Modifier
            </button>
            <button type="button" class="btn btn-success" onclick="printDetail()">
                <i class="fas fa-print"></i> Imprimer
            </button>
        </div>
    </div>
</div>

<script>
    let currentDetailId = null;

    function viewPresence(id) {
        currentDetailId = id;
        const modal = document.getElementById('detailModal');
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';

        document.getElementById('detailContent').innerHTML =
            '<div class="loading active"><div class="spinner"></div><p style="margin-top:10px;">Chargement...</p></div>';
        document.getElementById('editFromDetailBtn').style.display = 'none';

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

    function renderDetail(presence) {
        const students = presence.students || [];
        const total = students.length;
        const presents = students.filter(s => s.present == 1).length;
        const absents = total - presents;
        const taux = total > 0 ? Math.round((presents / total) * 100) : 0;
        const tauxColor = taux >= 80 ? '#27ae60' : (taux >= 50 ? '#f39c12' : '#e74c3c');

        let html = `
            <div style="padding:15px;">
                <!-- En-tête -->
                <div style="display:flex;align-items:center;gap:20px;padding:15px 20px;background:#f8f9fa;border-radius:12px;margin-bottom:20px;flex-wrap:wrap;">
                    <div style="width:70px;height:70px;border-radius:50%;background:#27ae60;display:flex;align-items:center;justify-content:center;font-size:30px;color:white;flex-shrink:0;">
                        <i class="fas fa-clipboard-list"></i>
                    </div>
                    <div style="flex:1;">
                        <h2 style="margin:0 0 8px 0;font-size:22px;color:#2c3e50;">${escapeHtml(presence.libelle || 'Séance')}</h2>
                        <div style="display:flex;gap:10px;flex-wrap:wrap;">
                            <span class="badge badge-primary">📅 ${formatDate(presence.date_seance)}</span>
                            <span class="badge badge-info">🕐 ${presence.heure_debut || '08:00'} (${presence.nb_heures || 2}h)</span>
                            <span class="badge badge-secondary">📆 ${escapeHtml(presence.jour_semaine || '-')}</span>
                            <span class="badge badge-info">📚 ${escapeHtml(presence.module_libelle || '')}</span>
                            <span class="badge badge-success">👨‍🏫 ${escapeHtml(presence.employee_fullname || '')}</span>
                            <span class="badge badge-secondary">📖 ${escapeHtml(presence.filiere_libelle || '')}</span>
                        </div>
                    </div>
                </div>

                <!-- Stats -->
                <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;margin-bottom:20px;">
                    <div style="text-align:center;padding:12px;background:#f8f9fa;border-radius:8px;border:1px solid #e9ecef;">
                        <div style="font-size:24px;font-weight:700;color:#2c3e50;">${total}</div>
                        <div style="font-size:12px;color:#7f8c8d;">👥 Total</div>
                    </div>
                    <div style="text-align:center;padding:12px;background:#d4edda;border-radius:8px;border:1px solid #c3e6cb;">
                        <div style="font-size:24px;font-weight:700;color:#155724;">${presents}</div>
                        <div style="font-size:12px;color:#155724;">✅ Présents</div>
                    </div>
                    <div style="text-align:center;padding:12px;background:#f8d7da;border-radius:8px;border:1px solid #f5c6cb;">
                        <div style="font-size:24px;font-weight:700;color:#721c24;">${absents}</div>
                        <div style="font-size:12px;color:#721c24;">❌ Absents</div>
                    </div>
                    <div style="text-align:center;padding:12px;background:#f8f9fa;border-radius:8px;border:1px solid #e9ecef;">
                        <div style="font-size:24px;font-weight:700;color:${tauxColor};">${taux}%</div>
                        <div style="font-size:12px;color:#7f8c8d;">📊 Taux</div>
                    </div>
                </div>

                <!-- Tableau des étudiants -->
                <h4 style="margin:20px 0 10px 0;color:#2c3e50;">
                    <i class="fas fa-users" style="color:#27ae60;"></i>
                    Liste des étudiants
                    <span style="font-size:13px;font-weight:400;color:#7f8c8d;margin-left:10px;">(${total} étudiant${total > 1 ? 's' : ''})</span>
                </h4>
                <div style="overflow-x:auto;">
                    <table style="width:100%;border-collapse:collapse;font-size:14px;">
                        <thead>
                            <tr style="background:#2c3e50;color:white;">
                                <th style="padding:10px 12px;text-align:left;">#</th>
                                <th style="padding:10px 12px;text-align:left;">Nom</th>
                                <th style="padding:10px 12px;text-align:left;">Prénom</th>
                                <th style="padding:10px 12px;text-align:center;">Statut</th>
                                <th style="padding:10px 12px;text-align:left;">Observation</th>
                            </tr>
                        </thead>
                        <tbody>
        `;

        if (students.length > 0) {
            students.forEach((s, i) => {
                const isPresent = s.present == 1;
                html += `
                    <tr style="border-bottom:1px solid #ecf0f1;">
                        <td style="padding:8px 12px;font-weight:600;color:#7f8c8d;">${i + 1}</td>
                        <td style="padding:8px 12px;font-weight:600;color:#2c3e50;">${escapeHtml(s.nom || '')}</td>
                        <td style="padding:8px 12px;color:#34495e;">${escapeHtml(s.prenom || '')}</td>
                        <td style="padding:8px 12px;text-align:center;">
                            <span style="display:inline-block;padding:3px 14px;border-radius:20px;font-size:13px;font-weight:600;
                                ${isPresent ? 'background:#d4edda;color:#155724;' : 'background:#f8d7da;color:#721c24;'}">
                                ${isPresent ? '✅ Présent' : '❌ Absent'}
                            </span>
                        </td>
                        <td style="padding:8px 12px;color:#7f8c8d;">${escapeHtml(s.description || '-')}</td>
                    </tr>
                `;
            });
        } else {
            html += `<tr><td colspan="5" style="text-align:center;padding:20px;color:#7f8c8d;">Aucun étudiant</td></tr>`;
        }

        html += `
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        document.getElementById('detailContent').innerHTML = html;
    }

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

    function editFromDetail() {
        if (currentDetailId) {
            closeDetailModal();
            setTimeout(() => {
                if (typeof openPresenceModal === 'function') {
                    openPresenceModal({ id: currentDetailId });
                }
            }, 300);
        }
    }

    function printDetail() {
        window.print();
    }

    function formatDate(date) {
        if (!date) return '-';
        const d = new Date(date + '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('detailModal').classList.contains('active')) {
            closeDetailModal();
        }
    });

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

<style>
    .badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }
    .badge-primary { background: #dbeafe; color: #1e40af; }
    .badge-info { background: #e0f2fe; color: #0369a1; }
    .badge-success { background: #d1fae5; color: #065f46; }
    .badge-secondary { background: #f1f5f9; color: #475569; }
    .alert {
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 15px;
    }
    .alert-error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .loading {
        display: none;
        text-align: center;
        padding: 40px;
    }
    .loading.active {
        display: block;
    }
    .spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #27ae60;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    .modal-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 9999;
        justify-content: center;
        align-items: center;
    }
    .modal-overlay.active {
        display: flex;
    }
    .modal-content {
        background: white;
        border-radius: 12px;
        max-height: 90vh;
        display: flex;
        flex-direction: column;
        width: 100%;
        max-width: 900px;
        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 25px;
        border-bottom: 2px solid #eee;
        flex-shrink: 0;
    }
    .modal-header h2 {
        margin: 0;
        font-size: 20px;
        color: #2c3e50;
    }
    .modal-close {
        background: none;
        border: none;
        font-size: 28px;
        cursor: pointer;
        color: #7f8c8d;
        padding: 0 8px;
        line-height: 1;
    }
    .modal-close:hover {
        color: #e74c3c;
    }
    .modal-body {
        padding: 20px 25px;
        overflow-y: auto;
        flex: 1;
    }
    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        padding: 12px 25px;
        border-top: 2px solid #eee;
        flex-shrink: 0;
        flex-wrap: wrap;
    }
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 20px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
        text-decoration: none;
    }
    .btn-secondary {
        background: #ecf0f1;
        color: #2c3e50;
    }
    .btn-secondary:hover {
        background: #d5dbdb;
    }
    .btn-warning {
        background: #f39c12;
        color: white;
    }
    .btn-warning:hover {
        background: #d68910;
    }
    .btn-success {
        background: #27ae60;
        color: white;
    }
    .btn-success:hover {
        background: #1e8449;
    }
    @media (max-width: 768px) {
        .modal-content {
            max-width: 100%;
            margin: 10px;
            max-height: 95vh;
        }
        .modal-body {
            padding: 15px;
        }
        .modal-header {
            padding: 12px 15px;
        }
        .modal-footer {
            padding: 10px 15px;
            justify-content: center;
        }
        .btn {
            font-size: 12px;
            padding: 6px 14px;
        }
        table {
            font-size: 12px;
        }
        table td, table th {
            padding: 5px 8px !important;
        }
    }
    @media print {
        .modal-overlay { position: static; background: white !important; }
        .modal-content { box-shadow: none; border: 1px solid #ddd; max-height: none; }
        .modal-footer { display: none; }
        .modal-close { display: none; }
        .btn { display: none; }
        .badge { print-color-adjust: exact; }
        .status-legend { print-color-adjust: exact; }
        body { background: white; }
        .modal-header { background: #f8f9fa !important; }
    }
</style>