// js/inscriptions.js
const API_BASE_URL = '../../../../model/api/inscriptions.php';
let editMode = false;
let inscriptionsData = [];
let groupedData = [];

// ========================================
// CHARGEMENT INITIAL
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    loadInscriptions();
    loadStats();
    loadConcours();
    loadStudents();
    loadTypeDiplome();
    setupSearchForm();
    setupMoyenneCalculation();
});

// ========================================
// RECHERCHE
// ========================================
function setupSearchForm() {
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        searchInscriptions();
    });
}

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

function searchInscriptions() {
    const searchData = {
        code: document.getElementById('searchCode').value,
        label: document.getElementById('searchLabel').value,
        concours_id: document.getElementById('searchConcours').value,
        type_diplome_id: document.getElementById('searchTypeDiplome').value,
        etat_inscription: document.getElementById('searchEtat').value,
        resultat_inscription: document.getElementById('searchResultat').value,
        active: document.getElementById('searchActive') ? document.getElementById('searchActive').value : ''
    };

    const params = new URLSearchParams(searchData);

    fetch(`${API_BASE_URL}?action=search&${params.toString()}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                inscriptionsData = result.data;
                renderTable(inscriptionsData);
                loadGroupedData();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ========================================
// STATISTIQUES
// ========================================
function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => 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));
}

// ========================================
// DROPDOWNS
// ========================================
function loadConcours() {
    fetch(`${API_BASE_URL}?action=concours`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                populateDropdown('searchConcours', result.data, 'code', 'label');
                populateDropdown('concours_id', result.data, 'code', 'label');
            }
        })
        .catch(error => console.error('Error loading concours:', error));
}

function loadStudents() {
    fetch(`${API_BASE_URL}?action=students`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                populateDropdown('student_id', result.data, 'nom', 'prenom', 'email');
            }
        })
        .catch(error => console.error('Error loading students:', error));
}

function loadTypeDiplome() {
    fetch(`${API_BASE_URL}?action=types_diplome`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                populateDropdown('searchTypeDiplome', result.data, 'libelle', 'code');
                populateDropdown('type_diplome', result.data, 'libelle', 'code');
            }
        })
        .catch(error => console.error('Error loading type diplome:', error));
}

function populateDropdown(selectId, data, labelField, subField, extraField) {
    const select = document.getElementById(selectId);
    if (!select) return;

    const firstOption = select.options[0];
    select.innerHTML = '';
    select.appendChild(firstOption);

    data.forEach(item => {
        const option = document.createElement('option');
        option.value = item.id;
        let label = item[labelField] || '';
        if (subField && item[subField]) {
            label += ' - ' + item[subField];
        }
        if (extraField && item[extraField]) {
            label += ' (' + item[extraField] + ')';
        }
        option.textContent = label;
        select.appendChild(option);
    });
}

// ========================================
// LISTE DES INSCRIPTIONS
// ========================================
function loadInscriptions() {
    showLoading(true);

    fetch(`${API_BASE_URL}?action=list`)
        .then(response => response.json())
        .then(result => {
            showLoading(false);
            if (result.success) {
                inscriptionsData = result.data;
                renderTable(inscriptionsData);
                loadGroupedData();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function renderTable(inscriptions) {
    const tbody = document.getElementById('tableBody');

    if (!inscriptions || inscriptions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <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;
    }

    tbody.innerHTML = inscriptions.map(item => `
        <tr>
            <td>${item.id}</td>
            <td><strong>${escapeHtml(item.code)}</strong></td>
            <td>${escapeHtml(item.label)}</td>
            <td>${escapeHtml(item.concours_code || '-')}</td>
            <td>${escapeHtml(item.student_nom || '')} ${escapeHtml(item.student_prenom || '')}</td>
            <td><span class="badge badge-info">${escapeHtml(item.diplome_libelle || '-')}</span></td>
            <td>${item.moyenne_general_calcule || '-'}</td>
            <td><strong style="color: var(--primary-color);">${item.moyenne_ecrit || '-'}</strong></td>
            <td><strong style="color: var(--secondary-color);">${item.moyenne_orale || '-'}</strong></td>
            <td><span class="badge ${getEtatBadge(item.etat_inscription)}">${escapeHtml(item.etat_inscription)}</span></td>
            <td><span class="badge ${getResultatBadge(item.resultat_inscription)}">${escapeHtml(item.resultat_inscription)}</span></td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${item.id})">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${item.id})">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteInscription(${item.id})">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function getEtatBadge(etat) {
    const map = {
        'VALIDE': 'badge-success',
        'EN_ATTENTE': 'badge-warning',
        'REJETE': 'badge-danger'
    };
    return map[etat] || 'badge-secondary';
}

function getResultatBadge(resultat) {
    const map = {
        'ADMIS': 'badge-success',
        'LISTE_ATTENTE': 'badge-warning',
        'NON_ADMIS': 'badge-danger',
        'EN_COURS': 'badge-info'
    };
    return map[resultat] || 'badge-secondary';
}

// ========================================
// GROUPEMENT PAR TYPE DE DIPLÔME
// ========================================
function loadGroupedData() {
    fetch(`${API_BASE_URL}?action=grouped`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                groupedData = result.data;
                renderGroupedData(groupedData);
            }
        })
        .catch(error => console.error('Error loading grouped data:', error));
}

function renderGroupedData(groups) {
    const container = document.getElementById('groupContainer');

    if (!groups || groups.length === 0) {
        container.innerHTML = `
            <div style="text-align: center; padding: 30px; color: #999;">
                <i class="fas fa-graduation-cap" style="font-size: 48px; display: block; margin-bottom: 10px;"></i>
                <p>Aucune donnée de regroupement disponible</p>
            </div>
        `;
        document.getElementById('groupCount').textContent = '0 types';
        return;
    }

    document.getElementById('groupCount').textContent = groups.length + ' types';

    let html = `<div class="group-grid">`;
    groups.forEach(group => {
        const total = parseInt(group.total_inscriptions) || 0;
        const valide = parseInt(group.valide) || 0;
        const enAttente = parseInt(group.en_attente) || 0;
        const admis = parseInt(group.admis) || 0;

        html += `
            <div class="group-card" onclick="filterByType(${group.type_diplome_id})">
                <div class="group-header">
                    <div class="group-icon">
                        <i class="fas fa-graduation-cap"></i>
                    </div>
                    <div class="group-title">
                        <h4>${escapeHtml(group.type_diplome_libelle)}</h4>
                        <span class="badge badge-primary">${group.type_diplome_code}</span>
                    </div>
                </div>
                <div class="group-stats">
                    <div class="group-stat">
                        <span class="stat-number">${total}</span>
                        <span class="stat-label">Total</span>
                    </div>
                    <div class="group-stat">
                        <span class="stat-number" style="color: var(--success-color);">${valide}</span>
                        <span class="stat-label">Validées</span>
                    </div>
                    <div class="group-stat">
                        <span class="stat-number" style="color: var(--warning-color);">${enAttente}</span>
                        <span class="stat-label">En Attente</span>
                    </div>
                    <div class="group-stat">
                        <span class="stat-number" style="color: var(--info-color);">${admis}</span>
                        <span class="stat-label">Admis</span>
                    </div>
                </div>
                <div class="group-progress">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${total > 0 ? (valide/total*100) : 0}%; background: var(--success-color);"></div>
                        <div class="progress-fill" style="width: ${total > 0 ? (enAttente/total*100) : 0}%; background: var(--warning-color); margin-left: ${total > 0 ? (valide/total*100) : 0}%;"></div>
                    </div>
                    <small>${group.moyenne_generale ? 'Moyenne: ' + parseFloat(group.moyenne_generale).toFixed(2) : 'N/A'}</small>
                </div>
                <div class="group-actions">
                    <button class="btn btn-sm btn-info" onclick="event.stopPropagation(); filterByType(${group.type_diplome_id})">
                        <i class="fas fa-filter"></i> Filtrer
                    </button>
                    <span class="badge badge-secondary">${group.annee_apres_bac} ans</span>
                </div>
            </div>
        `;
    });
    html += `</div>`;

    container.innerHTML = html;
}

function filterByType(typeId) {
    // Filtrer le tableau des inscriptions
    const filtered = inscriptionsData.filter(item => item.type_diplome == typeId);
    renderTable(filtered);

    // Mettre en surbrillance la carte du groupe
    document.querySelectorAll('.group-card').forEach(card => {
        card.classList.remove('active');
    });
    const cards = document.querySelectorAll('.group-card');
    cards.forEach(card => {
        if (card.querySelector('.group-title h4').textContent.trim() ===
            groupedData.find(g => g.type_diplome_id == typeId)?.type_diplome_libelle) {
            card.classList.add('active');
        }
    });

    showToast('Filtré par type de diplôme', 'info');
}

// ========================================
// MOYENNE CALCUL
// ========================================
function setupMoyenneCalculation() {
    const semestreFields = ['note_semstre1', 'note_semstre2', 'note_semstre3', 'note_semstre4'];
    semestreFields.forEach(field => {
        const el = document.getElementById(field);
        if (el) {
            el.addEventListener('input', calculateMoyenne);
        }
    });
}

function calculateMoyenne() {
    const notes = [];
    const semestreFields = ['note_semstre1', 'note_semstre2', 'note_semstre3', 'note_semstre4'];
    semestreFields.forEach(field => {
        const value = parseFloat(document.getElementById(field).value);
        if (!isNaN(value) && value > 0) {
            notes.push(value);
        }
    });

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

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

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

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

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

                // Diplome info
                document.getElementById('type_diplome').value = data.type_diplome || '';
                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_semstre1').value = data.note_semstre1 || '';
                document.getElementById('note_semstre2').value = data.note_semstre2 || '';
                document.getElementById('note_semstre3').value = data.note_semstre3 || '';
                document.getElementById('note_semstre4').value = data.note_semstre4 || '';

                calculateMoyenne();

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

function saveInscription() {
    const code = document.getElementById('code').value;
    const label = document.getElementById('label').value;
    const concours_id = document.getElementById('concours_id').value;
    const student_id = document.getElementById('student_id').value;

    if (!code || !label || !concours_id || !student_id) {
        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),
        student_id: parseInt(student_id),
        etat_inscription: document.getElementById('etat_inscription').value,
        resultat_inscription: document.getElementById('resultat_inscription').value,
        moyenne_ecrit: document.getElementById('moyenne_ecrit').value ? parseFloat(document.getElementById('moyenne_ecrit').value) : null,
        moyenne_orale: document.getElementById('moyenne_orale').value ? parseFloat(document.getElementById('moyenne_orale').value) : null,
        active: parseInt(document.getElementById('active').value),
        description: document.getElementById('description').value || null,
        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: document.getElementById('type_diplome').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_semstre1: document.getElementById('note_semstre1').value || null,
        note_semstre2: document.getElementById('note_semstre2').value || null,
        note_semstre3: document.getElementById('note_semstre3').value || null,
        note_semstre4: document.getElementById('note_semstre4').value || null
    };

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

    const btn = document.querySelector('.modal-footer .btn-primary');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            btn.disabled = false;
            btn.innerHTML = originalText;

            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadInscriptions();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = originalText;
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ========================================
// SUPPRESSION
// ========================================
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();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ========================================
// DÉTAILS
// ========================================
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) {
                renderDetail(result.data);
            } else {
                document.getElementById('detailContent').innerHTML = `
                    <p style="color: var(--danger-color);">Erreur: ${result.message}</p>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <p style="color: var(--danger-color);">Erreur de connexion au serveur</p>
            `;
            console.error('Error:', error);
        });
}

function renderDetail(data) {
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <h3>📋 Informations Générales</h3>
            </div>
        
        <div class="detail-section">
            <h3>🎓 Baccalauréat</h3>
            </div>
        
        <div class="detail-section">
            <h3>📜 Diplôme</h3>
            </div>
        
        <div class="detail-section">
            <h3>📊 Notes & Résultats Concours</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label">Note Écrit</span>
                    <span class="value" style="color: var(--primary-color); font-weight: bold;">${data.moyenne_ecrit ? data.moyenne_ecrit + ' / 20' : '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Note Oral</span>
                    <span class="value" style="color: var(--secondary-color); font-weight: bold;">${data.moyenne_orale ? data.moyenne_orale + ' / 20' : '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Semestre 1</span>
                    <span class="value">${data.note_semstre1 || '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Semestre 2</span>
                    <span class="value">${data.note_semstre2 || '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Semestre 3</span>
                    <span class="value">${data.note_semstre3 || '-'}</span>
                </div>
                <div class="detail-item">
                    <span class="label">Semestre 4</span>
                    <span class="value">${data.note_semstre4 || '-'}</span>
                </div>
                <div class="detail-item" style="grid-column: 1 / -1;">
                    <span class="label">Moyenne Générale</span>
                    <span class="value" style="font-weight: bold; color: var(--primary-color); font-size: 1.2em;">${data.moyenne_general_calcule || '-'}</span>
                </div>
            </div>
        </div>
        `;
}
function closeDetailModal() {
    document.getElementById('detailModal').classList.remove('active');
}

// ========================================
// UTILITAIRES
// ========================================
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 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;
}

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

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