<?php
// app/view/admin/pedagogie/inscription-module_detail/create-edit/modal.php

// Les variables $inscriptionModuleIdForModal, $studentsList, $allStudentsList sont définies avant l'inclusion
?>

<div class="modal-overlay" id="inscriptionModuleDetailModal">
    <div class="modal modal-md">
        <div class="modal-header">
            <h2><i class="fas fa-user-plus"></i> Ajouter des Étudiants</h2>
            <button class="modal-close" onclick="closeInscriptionModuleDetailModal()">&times;</button>
        </div>

        <div class="modal-body">
            <form id="inscriptionModuleDetailForm">
                <input type="hidden" id="inscription_module_detail_id" value="<?= isset($inscriptionModuleIdForModal) ? $inscriptionModuleIdForModal : '' ?>">

                <!-- ===================== -->
                <!-- AJOUT MANUEL -->
                <!-- ===================== -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-user"></i>
                        Ajouter un étudiant
                    </h3>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label>Rechercher un étudiant</label>
                            <div style="display:flex;gap:10px;">
                                <input type="text"
                                       id="student_search"
                                       class="form-control"
                                       placeholder="Entrez le CIN de l'étudiant..."
                                       autocomplete="off"
                                       style="flex:1;">
                                <button type="button" class="btn btn-primary" onclick="searchStudent()">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                            <div id="studentSearchResult" style="display:none; margin-top: 10px;"></div>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label>Ou sélectionner dans la liste</label>
                            <div style="display:flex;gap:10px;">
                                <select id="student_id" class="form-control" style="flex:1;">
                                    <option value="">Sélectionner un étudiant</option>
                                    <?php
                                    $allStudents = isset($allStudentsList) ? $allStudentsList : [];
                                    $studentsIds = isset($studentsList) ? array_column($studentsList, 'student_id') : [];
                                    foreach ($allStudents as $student):
                                        $alreadyInscribed = in_array($student['id'], $studentsIds);
                                    ?>
                                        <option value="<?= $student['id'] ?>" <?= $alreadyInscribed ? 'disabled' : '' ?>>
                                            <?= htmlspecialchars($student['cin'] ?? '') ?>
                                            - <?= htmlspecialchars($student['nom'] . ' ' . $student['prenom']) ?>
                                            <?= $alreadyInscribed ? '(déjà inscrit)' : '' ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" class="btn btn-success" onclick="addStudentManually()">
                                    <i class="fas fa-plus"></i> Ajouter
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ===================== -->
                <!-- IMPORT CSV -->
                <!-- ===================== -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-file-import"></i>
                        Importer depuis CSV
                    </h3>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label>Fichier CSV</label>
                            <div class="file-upload-wrapper">
                                <input type="file"
                                       id="detail_csv_file"
                                       class="file-upload-input"
                                       accept=".csv">
                                <label for="detail_csv_file" class="file-upload-label">
                                    <i class="fas fa-cloud-upload-alt"></i>
                                    Choisir un fichier CSV
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label>Nom de la colonne des CIN</label>
                            <input type="text"
                                   id="detail_column_name"
                                   class="form-control"
                                   placeholder="cin"
                                   value="cin">
                            <small class="form-text text-muted">
                                <a href="#" onclick="downloadDetailTemplate()" class="template-link">
                                    <i class="fas fa-download"></i> Télécharger le template CSV
                                </a>
                            </small>
                        </div>
                    </div>

                    <button type="button" class="btn btn-primary" onclick="importCSVStudents()">
                        <i class="fas fa-upload"></i> Importer CSV
                    </button>

                    <div id="csvImportResult" style="margin-top: 10px; display: none;"></div>
                </div>

                <!-- ===================== -->
                <!-- ÉTUDIANTS DÉJÀ INSCRITS -->
                <!-- ===================== -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-users"></i>
                        Étudiants déjà inscrits
                        <span class="badge badge-info" id="studentCountBadge"><?= isset($studentsList) ? count($studentsList) : 0 ?></span>
                    </h3>

                    <div class="student-list-container" style="max-height:200px;overflow-y:auto;border:1px solid #e9ecef;border-radius:8px;padding:10px;">
                        <ul class="student-list" style="list-style:none;padding:0;margin:0;" id="currentStudentList">
                            <?php if (isset($studentsList) && !empty($studentsList)): ?>
                                <?php foreach ($studentsList as $student): ?>
                                    <li data-student_id="<?= $student['student_id'] ?>" style="display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid #f0f2f5;">
                                        <span>
                                            <strong><?= htmlspecialchars($student['nom'] . ' ' . $student['prenom']) ?></strong>
                                            <?php if ($student['cin']): ?>
                                                <span class="badge badge-secondary"><?= htmlspecialchars($student['cin']) ?></span>
                                            <?php endif; ?>
                                        </span>
                                        <button class="btn btn-danger btn-sm" onclick="removeStudentInline(<?= $student['student_id'] ?>)">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </li>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <li class="empty-message" style="text-align:center;padding:20px;color:#7f8c8d;">Aucun étudiant inscrit</li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>

            </form>
        </div>

        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeInscriptionModuleDetailModal()">
                <i class="fas fa-times"></i> Fermer
            </button>
        </div>
    </div>
</div>

<script>
// =========================================
// INSCRIPTION MODULE DETAIL MODAL FUNCTIONS
// =========================================

function openInscriptionModuleDetailModal(inscriptionModuleId) {
    const modal = document.getElementById('inscriptionModuleDetailModal');
    document.getElementById('inscription_module_detail_id').value = inscriptionModuleId;
    modal.classList.add('active');
    document.body.style.overflow = 'hidden';
    document.getElementById('studentSearchResult').style.display = 'none';
    document.getElementById('csvImportResult').style.display = 'none';
}

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

// =========================================
// RECHERCHE D'ÉTUDIANT
// =========================================

function searchStudent() {
    const search = document.getElementById('student_search').value.trim();
    const resultDiv = document.getElementById('studentSearchResult');

    if (!search) {
        showToast('Veuillez entrer un CIN', 'warning');
        return;
    }

    fetch(`/est-concours/model/api/inscription-module-detail.php?action=search_student&code=${encodeURIComponent(search)}`)
        .then(r => r.json())
        .then(result => {
            if (result.success && result.data) {
                const student = result.data;
                const inscriptionModuleId = document.getElementById('inscription_module_detail_id').value;

                // Vérifier si déjà inscrit
                fetch(`/est-concours/model/api/inscription-module-detail.php?action=check_student&inscription_module_id=${inscriptionModuleId}&student_id=${student.id}`)
                    .then(r => r.json())
                    .then(checkResult => {
                        if (checkResult.inscrit) {
                            resultDiv.innerHTML = `
                                <div class="alert alert-warning">
                                    ⚠️ ${escapeHtml(student.nom)} ${escapeHtml(student.prenom)} est déjà inscrit.
                                </div>
                            `;
                        } else {
                            resultDiv.innerHTML = `
                                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:#f8f9fa;border-radius:8px;border:1px solid #27ae60;">
                                    <div>
                                        <strong>${escapeHtml(student.nom)} ${escapeHtml(student.prenom)}</strong>
                                        <span class="badge badge-secondary">${escapeHtml(student.cin)}</span>
                                    </div>
                                    <button class="btn btn-success btn-sm" onclick="addFoundStudent(${student.id})">
                                        <i class="fas fa-plus"></i> Ajouter
                                    </button>
                                </div>
                            `;
                        }
                        resultDiv.style.display = 'block';
                    });
            } else {
                resultDiv.innerHTML = `<div class="alert alert-error">❌ Étudiant non trouvé</div>`;
                resultDiv.style.display = 'block';
            }
        })
        .catch(() => {
            resultDiv.innerHTML = `<div class="alert alert-error">❌ Erreur de recherche</div>`;
            resultDiv.style.display = 'block';
        });
}

function addFoundStudent(studentId) {
    addStudent(studentId);
    document.getElementById('studentSearchResult').style.display = 'none';
    document.getElementById('student_search').value = '';
}

// =========================================
// AJOUT MANUEL
// =========================================

function addStudentManually() {
    const select = document.getElementById('student_id');
    const studentId = select.value;

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

    addStudent(studentId);
    select.value = '';
}

function addStudent(studentId) {
    const inscriptionModuleId = document.getElementById('inscription-module-detait_id').value;

    fetch('/est-concours/model/api/inscription-module-detail.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            inscription_module_id: inscriptionModuleId,
            student_id: studentId
        })
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            showToast(result.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Erreur: ' + result.message, 'error');
        }
    })
    .catch(() => {
        showToast('Erreur de connexion', 'error');
    });
}

// =========================================
// RETIRER UN ÉTUDIANT (depuis le modal)
// =========================================

function removeStudentInline(studentId) {
    const inscriptionModuleId = document.getElementById('inscription_module_detail_id').value;

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

    fetch(`/est-concours/model/api/inscription-module-detail.php?inscription_module_id=${inscriptionModuleId}&student_id=${studentId}`, {
        method: 'DELETE'
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            showToast(result.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Erreur: ' + result.message, 'error');
        }
    })
    .catch(() => {
        showToast('Erreur de connexion', 'error');
    });
}

// =========================================
// IMPORT CSV
// =========================================

function importCSVStudents() {
    const fileInput = document.getElementById('detail_csv_file');
    const file = fileInput.files[0];
    const resultDiv = document.getElementById('csvImportResult');

    if (!file) {
        showToast('Veuillez sélectionner un fichier CSV', 'warning');
        return;
    }

    const inscriptionModuleId = document.getElementById('inscription_module_detail_id').value;
    const columnName = document.getElementById('detail_column_name').value.trim() || 'cin';

    const formData = new FormData();
    formData.append('csv_file', file);
    formData.append('inscription_module_id', inscriptionModuleId);
    formData.append('column_name', columnName);

    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '<div class="loading"><div class="spinner"></div><p>Importation en cours...</p></div>';

    fetch('/est-concours/model/api/inscription-module-detail.php?action=import_csv', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            let message = `${result.inserted || 0} étudiant(s) importé(s) avec succès`;
            if (result.skipped > 0) {
                message += `, ${result.skipped} déjà inscrit(s) ignoré(s)`;
            }
            if (result.not_found && result.not_found.length > 0) {
                message += `<br>⚠️ ${result.not_found.length} étudiant(s) non trouvé(s): ${result.not_found.join(', ')}`;
            }
            resultDiv.innerHTML = `<div class="alert alert-success">✅ ${message}</div>`;
            setTimeout(() => location.reload(), 2000);
        } else {
            resultDiv.innerHTML = `<div class="alert alert-error">❌ ${result.message}</div>`;
        }
    })
    .catch(() => {
        resultDiv.innerHTML = `<div class="alert alert-error">❌ Erreur lors de l'importation</div>`;
    });
}

// =========================================
// TÉLÉCHARGER LE TEMPLATE
// =========================================

function downloadDetailTemplate() {
    const content = 'cin\nAB123456\nFZ234567\nMA345678\nSB456789';
    const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'template-inscription-students.csv';
    link.click();
}

// =========================================
// UTILITAIRES
// =========================================

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

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) {
        alert(message);
        return;
    }
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<span>${message}</span><button onclick="this.parentElement.remove()">&times;</button>`;
    container.appendChild(toast);
    setTimeout(() => {
        if (toast.parentElement) toast.remove();
    }, 4000);
}
</script>

<style>
.file-upload-wrapper {
    position: relative;
    width: 100%;
}

.file-upload-input {
    position: absolute;
    opacity: 0;
    width: 0.1px;
    height: 0.1px;
}

.file-upload-label {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 20px;
    border: 2px dashed #ced4da;
    border-radius: 8px;
    background: #f8f9fa;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #6c757d;
    font-weight: 500;
}

.file-upload-label:hover {
    border-color: #27ae60;
    background: #f0f2f5;
    color: #27ae60;
}

.file-upload-label i {
    font-size: 24px;
}

.template-link {
    color: #27ae60;
    text-decoration: none;
    font-weight: 500;
}
.template-link:hover {
    text-decoration: underline;
}

.alert {
    padding: 12px 18px;
    border-radius: 8px;
    margin-bottom: 10px;
}
.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #27ae60;
}
.alert-error {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #e74c3c;
}
.alert-warning {
    background: #fff3cd;
    color: #856404;
    border-left: 4px solid #f39c12;
}

.loading {
    text-align: center;
    padding: 20px;
}
.spinner {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #27ae60;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>