const API_BASE_URL = '/est-concours/model/api/grade.php';
const API_TYPE_GRADE_URL = '/est-concours/model/api/type_grade.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;
let typeGradesMap = {};

document.addEventListener('DOMContentLoaded', function() {
    loadTypeGradesForSelects();
    loadGrades();
    loadStats();
    setupSearchForm();
});

function setupSearchForm() {
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        currentPage = 1;
        loadGrades();
    });
}

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchTypeGrade').value = '';
    currentPage = 1;
    loadGrades();
}

function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(r => r.json())
        .then(result => {
            if (result.success) document.getElementById('statTotal').textContent = result.data.total || 0;
        });

    fetch(`${API_TYPE_GRADE_URL}?action=stats`)
        .then(r => r.json())
        .then(result => {
            if (result.success) document.getElementById('statTypeGrade').textContent = result.data.total || 0;
        });
}

function loadTypeGradesForSelects() {
    fetch(`${API_TYPE_GRADE_URL}?action=all`)
        .then(r => r.json())
        .then(result => {
            if (!result.success) return;
            typeGradesMap = {};
            result.data.forEach(type => { typeGradesMap[type.id] = type; });

            const searchSelect = document.getElementById('searchTypeGrade');
            searchSelect.innerHTML = '<option value="">Tous les types</option>';
            result.data.forEach(type => {
                searchSelect.innerHTML += `<option value="${type.id}">${escapeHtml(type.libelle)} (${escapeHtml(type.code)})</option>`;
            });

            const formSelect = document.getElementById('type_grade_id');
            if (formSelect) {
                formSelect.innerHTML = '<option value="">Sélectionner un type de grade</option>';
                result.data.forEach(type => {
                    formSelect.innerHTML += `<option value="${type.id}" data-code="${escapeHtml(type.code)}">${escapeHtml(type.libelle)} (${escapeHtml(type.code)})</option>`;
                });
            }
        });
}

function loadGrades() {
    showLoading(true);
    const params = new URLSearchParams({
        libelle:       document.getElementById('searchLibelle')?.value    || '',
        code:          document.getElementById('searchCode')?.value        || '',
        type_grade_id: document.getElementById('searchTypeGrade')?.value  || '',
        description:   document.getElementById('searchDescription')?.value || '',
        page:     currentPage,
        per_page: perPage
    });

    fetch(`${API_BASE_URL}?action=search&${params}`)
        .then(r => r.json())
        .then(result => {
            showLoading(false);
            if (result.success) { renderTable(result.data.data); renderPagination(result.data); }
            else showToast('Erreur: ' + result.message, 'error');
        })
        .catch(() => { showLoading(false); showToast('Erreur de connexion', 'error'); });
}

function renderTable(grades) {
    const tbody = document.getElementById('tableBody');
    if (!grades || grades.length === 0) {
        tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;padding:40px;">📭 Aucun grade trouvé</td></tr>`;
        return;
    }

    tbody.innerHTML = grades.map(grade => `
        <tr>
            <td>${grade.id}</td>
            <td><strong>${escapeHtml(grade.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(grade.code)}</span></td>
            <td><span class="badge badge-success">${escapeHtml(grade.type_grade_libelle || '-')}</span></td>
            <td>${escapeHtml(grade.description || '-')}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${grade.id})"><i class="fas fa-eye"></i></button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${grade.id})"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm" onclick="deleteGrade(${grade.id})"><i class="fas fa-trash"></i></button>
            </td>
        </tr>
    `).join('');
}

function renderPagination(data) {
    totalPages = data.totalPages;
    const start = (data.page - 1) * perPage + 1;
    const end   = Math.min(data.page * perPage, data.total);
    document.getElementById('paginationInfo').textContent = `Affichage de ${start} à ${end} sur ${data.total} grades`;
    let html = '';
    for (let i = 1; i <= data.totalPages; i++) html += `<button onclick="goToPage(${i})" ${i === data.page ? 'class="active"' : ''}>${i}</button>`;
    document.getElementById('pageNumbers').innerHTML = html;
    document.getElementById('prevBtn').disabled = data.page <= 1;
    document.getElementById('nextBtn').disabled = data.page >= data.totalPages;
}

function changePage(dir) { if (dir==='prev'&&currentPage>1) currentPage--; else if (dir==='next'&&currentPage<totalPages) currentPage++; loadGrades(); }
function goToPage(page)  { currentPage = page; loadGrades(); }

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Grade';
    document.getElementById('gradeForm').reset();
    document.getElementById('gradeId').value = '';
    document.getElementById('type_grade_id').value = '';
    document.getElementById('code').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function onTypeGradeChange() {
    const sel = document.getElementById('type_grade_id');
    const opt = sel.options[sel.selectedIndex];
    const libelleInput = document.getElementById('libelle');
    const codeInput    = document.getElementById('code');

    if (!opt || !opt.value) { codeInput.value = ''; return; }

    const typeCode = opt.dataset.code || opt.getAttribute('data-code') || '';
    const libelle  = libelleInput.value.trim();

    // Auto-generate code: TYPEGRADE-LIBELLE
    if (libelle) {
        const gradeCode = libelle.toUpperCase()
            .replace(/\s+/g, '-')
            .replace(/[^A-Z0-9-]/g, '')
            .substring(0, 10);
        codeInput.value = `${typeCode}-${gradeCode}`;
    } else {
        codeInput.value = typeCode + '-';
    }
}

function onLibelleChange() {
    const sel = document.getElementById('type_grade_id');
    if (!sel || !sel.value) return;
    onTypeGradeChange();
}

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

    if (document.getElementById('detailModal').classList.contains('active')) closeDetailModal();

    document.querySelector('.modal-overlay').classList.add('active');
    ['libelle','code','description'].forEach(f => { document.getElementById(f).value = 'Chargement...'; document.getElementById(f).disabled = true; });
    document.getElementById('type_grade_id').disabled = true;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(r => r.json())
        .then(result => {
            ['libelle','code','description'].forEach(f => { document.getElementById(f).disabled = false; });
            document.getElementById('type_grade_id').disabled = false;

            if (result.success) {
                const g = result.data;
                document.getElementById('libelle').value       = g.libelle       || '';
                document.getElementById('code').value          = g.code          || '';
                document.getElementById('type_grade_id').value = g.type_grade_id || '';
                document.getElementById('description').value   = g.description   || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(() => {
            ['libelle','code','description'].forEach(f => { document.getElementById(f).disabled = false; });
            document.getElementById('type_grade_id').disabled = false;
            showToast('Erreur de connexion', 'error');
            closeModal();
        });
}

function viewDetail(id) {
    currentDetailId = 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...</p></div>';
    document.getElementById('editFromDetailBtn').style.display = 'none';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(r => r.json())
        .then(result => {
            if (result.success) renderDetail(result.data);
        });
}

function renderDetail(grade) {
    const typeGradeLibelle = grade.type_grade_libelle || (typeGradesMap[grade.type_grade_id] ? typeGradesMap[grade.type_grade_id].libelle : '-');
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar"><i class="fas fa-graduation-cap"></i></div>
                <div class="detail-title">
                    <h2>${escapeHtml(grade.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">${escapeHtml(grade.code)}</span>
                        <span class="badge badge-success">${escapeHtml(typeGradeLibelle)}</span>
                    </div>
                </div>
            </div>
            <div class="detail-grid">
                <div class="detail-item"><span class="label">ID</span><span class="value">${grade.id}</span></div>
                <div class="detail-item"><span class="label">Code</span><span class="value"><span class="badge badge-info">${escapeHtml(grade.code)}</span></span></div>
                <div class="detail-item"><span class="label">Type de Grade</span><span class="value"><span class="badge badge-success">${escapeHtml(typeGradeLibelle)}</span></span></div>
                <div class="detail-item full-width"><span class="label">Libellé</span><span class="value">${escapeHtml(grade.libelle)}</span></div>
                <div class="detail-item full-width"><span class="label">Description</span><span class="value">${escapeHtml(grade.description || 'Aucune description')}</span></div>
            </div>
        </div>`;
    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';
}

function editFromDetail() {
    if (currentDetailId) { closeDetailModal(); setTimeout(() => openEditModal(currentDetailId), 300); }
}

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

function saveGrade() {
    const libelle      = document.getElementById('libelle').value.trim();
    const code         = document.getElementById('code').value.trim();
    const type_grade_id = document.getElementById('type_grade_id').value;
    const description  = document.getElementById('description').value.trim();

    if (!libelle)       { showToast('Libellé obligatoire', 'warning'); return; }
    if (!code)          { showToast('Code obligatoire', 'warning'); return; }
    if (!type_grade_id) { showToast('Type de grade obligatoire', 'warning'); return; }

    const id  = document.getElementById('gradeId').value;
    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : API_BASE_URL;

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

    fetch(url, {
        method: id ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ libelle, code, type_grade_id: parseInt(type_grade_id), description: description || null })
    })
    .then(r => r.json())
    .then(result => {
        saveBtn.innerHTML = orig; saveBtn.disabled = false;
        if (result.success) { showToast(result.message, 'success'); closeModal(); loadGrades(); loadStats(); }
        else showToast('Erreur: ' + result.message, 'error');
    })
    .catch(() => { saveBtn.innerHTML = orig; saveBtn.disabled = false; showToast('Erreur de connexion', 'error'); });
}

function deleteGrade(id) {
    if (!confirm('Supprimer ce grade ?')) return;
    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(r => r.json())
        .then(result => {
            if (result.success) { showToast(result.message, 'success'); loadGrades(); loadStats(); }
            else showToast('Erreur: ' + result.message, 'error');
        });
}

function exportGrades() { window.location.href = `${API_BASE_URL}?action=export`; }
function closeModal()    { document.querySelector('.modal-overlay').classList.remove('active'); }

function showLoading(show) {
    const loading = document.querySelector('.loading');
    if (loading) loading.classList.toggle('active', show);
}

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    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);
}

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

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 if (document.querySelector('.modal-overlay.active')) closeModal();
    }
});