const API_BASE_URL      = '/est-concours/model/api/echelle.php';
const API_GRADE_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 gradesMap   = {};
let allGrades   = [];

document.addEventListener('DOMContentLoaded', function() {
    loadTypeGradesForSearch();
    loadGradesForSelects();
    loadEchelles();
    loadStats();
    setupSearchForm();
});

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

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchTypeGrade').value = '';
    document.getElementById('searchGrade').innerHTML = '<option value="">Tous les grades</option>';
    currentPage = 1;
    loadEchelles();
}

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;
                document.getElementById('statEchellons').textContent = result.data.total_echellons || 0;
            }
        });
}

// ── Type Grade pour recherche ──
function loadTypeGradesForSearch() {
    fetch(`${API_TYPE_GRADE_URL}?action=all`)
        .then(r => r.json())
        .then(result => {
            if (!result.success) return;
            const sel = document.getElementById('searchTypeGrade');
            sel.innerHTML = '<option value="">Tous les types</option>';
            result.data.forEach(t => {
                sel.innerHTML += `<option value="${t.id}">${escapeHtml(t.libelle)}</option>`;
            });
        });
}

// ── Cascade : quand on change Type Grade dans recherche ──
function onSearchTypeGradeChange() {
    const typeId  = document.getElementById('searchTypeGrade').value;
    const gradeSel = document.getElementById('searchGrade');
    gradeSel.innerHTML = '<option value="">Tous les grades</option>';

    if (!typeId) {
        allGrades.forEach(g => {
            gradeSel.innerHTML += `<option value="${g.id}">${escapeHtml(g.libelle)}</option>`;
        });
        return;
    }

    allGrades.filter(g => g.type_grade_id == typeId).forEach(g => {
        gradeSel.innerHTML += `<option value="${g.id}">${escapeHtml(g.libelle)}</option>`;
    });
}

// ── Grades pour selects ──
function loadGradesForSelects() {
    fetch(`${API_GRADE_URL}?action=all`)
        .then(r => r.json())
        .then(result => {
            if (!result.success) return;
            allGrades = result.data;
            gradesMap = {};
            result.data.forEach(g => { gradesMap[g.id] = g; });

            // Recherche
            const searchSel = document.getElementById('searchGrade');
            searchSel.innerHTML = '<option value="">Tous les grades</option>';
            result.data.forEach(g => {
                searchSel.innerHTML += `<option value="${g.id}">${escapeHtml(g.libelle)}</option>`;
            });

            // Formulaire modal
            const formSel = document.getElementById('grade_id');
            if (formSel) {
                formSel.innerHTML = '<option value="">Sélectionner un grade</option>';
                result.data.forEach(g => {
                    formSel.innerHTML += `<option value="${g.id}" data-code="${escapeHtml(g.code)}" data-type-code="${escapeHtml(g.type_code || '')}">${escapeHtml(g.libelle)} (${escapeHtml(g.code)})</option>`;
                });
            }
        });
}

// ── Auto-générer code Échelle quand on choisit le grade ──
function onGradeChange() {
    const gradeSel = document.getElementById('grade_id');
    const opt      = gradeSel.options[gradeSel.selectedIndex];
    const libSel   = document.getElementById('libelle');
    const codeSel  = document.getElementById('code');

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

    const gradeCode = opt.dataset.code || '';
    const libelle   = libSel.value.trim();

    // Code format: GRADE_CODE-ECHxx
    // Ex: ADMIN-ING-ECH10
    const echelleNum = libelle.match(/\d+/)?.[0] || '';
    if (echelleNum) {
        codeSel.value = `${gradeCode}-ECH${echelleNum}`;
    } else {
        codeSel.value = `${gradeCode}-ECH`;
    }

    // Auto description
    const descSel = document.getElementById('description');
    if (descSel && !descSel.value) {
        descSel.value = `Échelle ${libelle || ''} pour ${opt.textContent.split('(')[0].trim()}`;
    }
}

function onLibelleEchelleChange() {
    const gradeSel = document.getElementById('grade_id');
    if (!gradeSel || !gradeSel.value) return;
    onGradeChange();
}

function loadEchelles() {
    showLoading(true);
    const params = new URLSearchParams({
        libelle:        document.getElementById('searchLibelle')?.value     || '',
        code:           document.getElementById('searchCode')?.value         || '',
        grade_id:       document.getElementById('searchGrade')?.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(echelles) {
    const tbody = document.getElementById('tableBody');
    if (!echelles || echelles.length === 0) {
        tbody.innerHTML = `<tr><td colspan="9" style="text-align:center;padding:40px;">📭 Aucune échelle trouvée</td></tr>`;
        return;
    }

    tbody.innerHTML = echelles.map(e => `
        <tr>
            <td>${e.id}</td>
            <td><strong>${escapeHtml(e.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(e.code)}</span></td>
            <td><span class="badge badge-success">${escapeHtml(e.grade_libelle || '-')}</span></td>
            <td>${escapeHtml(e.description || '-')}</td>
            <td class="text-center">${e.echellon_depart}</td>
            <td class="text-center">${e.echellon_fin}</td>
            <td class="text-center"><span class="badge badge-primary">${e.echellon_count || 0}</span></td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${e.id})"><i class="fas fa-eye"></i></button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${e.id})"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm" onclick="deleteEchelle(${e.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} échelles`;
    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++; loadEchelles(); }
function goToPage(page)  { currentPage = page; loadEchelles(); }

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouvelle Échelle';
    document.getElementById('echelleForm').reset();
    document.getElementById('echelleId').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Échelle';
    document.getElementById('echelleId').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; });
    ['grade_id','echellon_depart','echellon_fin'].forEach(f => { document.getElementById(f).disabled = true; });

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(r => r.json())
        .then(result => {
            ['libelle','code','description','grade_id','echellon_depart','echellon_fin'].forEach(f => { document.getElementById(f).disabled = false; });
            if (result.success) {
                const e = result.data;
                document.getElementById('libelle').value        = e.libelle        || '';
                document.getElementById('code').value           = e.code           || '';
                document.getElementById('grade_id').value       = e.grade_id       || '';
                document.getElementById('echellon_depart').value = e.echellon_depart || '';
                document.getElementById('echellon_fin').value   = e.echellon_fin   || '';
                document.getElementById('description').value    = e.description    || '';
            } else { showToast(result.message, 'error'); closeModal(); }
        })
        .catch(() => { ['libelle','code','description','grade_id','echellon_depart','echellon_fin'].forEach(f => { document.getElementById(f).disabled = false; }); showToast('Erreur', '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></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(e) {
    const gradeLibelle = e.grade_libelle || (gradesMap[e.grade_id] ? gradesMap[e.grade_id].libelle : '-');
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar"><i class="fas fa-layer-group"></i></div>
                <div class="detail-title">
                    <h2>${escapeHtml(e.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">${escapeHtml(e.code)}</span>
                        <span class="badge badge-success">${escapeHtml(gradeLibelle)}</span>
                        <span class="badge badge-primary">${e.echellon_count || 0} échelons</span>
                    </div>
                </div>
            </div>
            <div class="detail-grid">
                <div class="detail-item"><span class="label">ID</span><span class="value">${e.id}</span></div>
                <div class="detail-item"><span class="label">Grade</span><span class="value"><span class="badge badge-success">${escapeHtml(gradeLibelle)}</span></span></div>
                <div class="detail-item"><span class="label">Échelon Départ</span><span class="value">${e.echellon_depart}</span></div>
                <div class="detail-item"><span class="label">Échelon Fin</span><span class="value">${e.echellon_fin}</span></div>
                <div class="detail-item full-width"><span class="label">Description</span><span class="value">${escapeHtml(e.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 saveEchelle() {
    const libelle        = document.getElementById('libelle').value.trim();
    const code           = document.getElementById('code').value.trim();
    const grade_id       = document.getElementById('grade_id').value;
    const echellon_depart = parseInt(document.getElementById('echellon_depart').value);
    const echellon_fin   = parseInt(document.getElementById('echellon_fin').value);
    const description    = document.getElementById('description').value.trim();

    if (!libelle)    { showToast('Libellé obligatoire', 'warning'); return; }
    if (!code)       { showToast('Code obligatoire', 'warning'); return; }
    if (!grade_id)   { showToast('Grade obligatoire', 'warning'); return; }
    if (isNaN(echellon_depart) || echellon_depart < 1) { showToast('Échelon de départ invalide', 'warning'); return; }
    if (isNaN(echellon_fin)    || echellon_fin    < 1) { showToast('Échelon de fin invalide', 'warning'); return; }
    if (echellon_depart >= echellon_fin) { showToast('Départ doit être < Fin', 'warning'); return; }

    const id  = document.getElementById('echelleId').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, grade_id: parseInt(grade_id), echellon_depart, echellon_fin, description: description || null })
    })
    .then(r => r.json())
    .then(result => {
        saveBtn.innerHTML = orig; saveBtn.disabled = false;
        if (result.success) { showToast(result.message, 'success'); closeModal(); loadEchelles(); loadStats(); }
        else showToast('Erreur: ' + result.message, 'error');
    })
    .catch(() => { saveBtn.innerHTML = orig; saveBtn.disabled = false; showToast('Erreur de connexion', 'error'); });
}

function deleteEchelle(id) {
    if (!confirm('Supprimer cette échelle et tous ses échelons ?')) return;
    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(r => r.json())
        .then(result => {
            if (result.success) { showToast(result.message, 'success'); loadEchelles(); loadStats(); }
            else showToast('Erreur: ' + result.message, 'error');
        });
}

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

function showLoading(show) {
    const el = document.querySelector('.loading');
    if (el) el.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();
    }
});