const API_BASE_URL = '/est-concours/model/api/filiere.php';
const API_DEPARTEMENT_URL = '/est-concours/model/api/departement.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;
let departementsMap = {};

document.addEventListener('DOMContentLoaded', function() {
    loadDepartementsForSelects();
    loadFiliere();
    loadStats();
    setupSearchForm();
});

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

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

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_DEPARTEMENT_URL}?action=stats`)
        .then(r => r.json())
        .then(result => {
            if (result.success) document.getElementById('statDepartement').textContent = result.data.total || 0;
        });
}

function loadDepartementsForSelects() {
    fetch(`${API_DEPARTEMENT_URL}?action=all`)
        .then(r => r.json())
        .then(result => {
            if (!result.success) return;
            departementsMap = {};
            result.data.forEach(dep => { departementsMap[dep.id] = dep; });

            const searchSelect = document.getElementById('searchDepartement');
            searchSelect.innerHTML = '<option value="">Tous les départements</option>';
            result.data.forEach(dep => {
                searchSelect.innerHTML += `<option value="${dep.id}">${escapeHtml(dep.libelle)} (${escapeHtml(dep.code)})</option>`;
            });

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

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

    tbody.innerHTML = filieres.map(filiere => `
        <tr>
            <td>${filiere.id}</td>
            <td><strong>${escapeHtml(filiere.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(filiere.code)}</span></td>
            <td><span class="badge badge-success">${escapeHtml(filiere.departement_libelle || '-')}</span></td>
            <td>${escapeHtml(filiere.description || '-')}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${filiere.id})"><i class="fas fa-eye"></i></button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${filiere.id})"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm" onclick="deleteFiliere(${filiere.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} filières`;
    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++; loadFiliere(); }
function goToPage(page)  { currentPage = page; loadFiliere(); }

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouvelle Filière';
    document.getElementById('filiereForm').reset();
    document.getElementById('filiereId').value = '';
    document.getElementById('departement_id').value = '';
    document.getElementById('code').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function onDepartementChange() {
    const sel = document.getElementById('departement_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 depCode = opt.dataset.code || opt.getAttribute('data-code') || '';
    const libelle = libelleInput.value.trim();

    if (libelle) {
        const filiereCode = libelle.toUpperCase()
            .replace(/\s+/g, '-')
            .replace(/[^A-Z0-9-]/g, '')
            .substring(0, 10);
        codeInput.value = `${depCode}-${filiereCode}`;
    } else {
        codeInput.value = depCode + '-';
    }
}

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

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Filière';
    document.getElementById('filiereId').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('departement_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('departement_id').disabled = false;

            if (result.success) {
                const f = result.data;
                document.getElementById('libelle').value       = f.libelle       || '';
                document.getElementById('code').value          = f.code          || '';
                document.getElementById('departement_id').value = f.departement_id || '';
                document.getElementById('description').value   = f.description   || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(() => {
            ['libelle','code','description'].forEach(f => { document.getElementById(f).disabled = false; });
            document.getElementById('departement_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(filiere) {
    const departementLibelle = filiere.departement_libelle || (departementsMap[filiere.departement_id] ? departementsMap[filiere.departement_id].libelle : '-');
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar"><i class="fas fa-building"></i></div>
                <div class="detail-title">
                    <h2>${escapeHtml(filiere.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">${escapeHtml(filiere.code)}</span>
                        <span class="badge badge-success">${escapeHtml(departementLibelle)}</span>
                    </div>
                </div>
            </div>
            <div class="detail-grid">
                <div class="detail-item"><span class="label">ID</span><span class="value">${filiere.id}</span></div>
                <div class="detail-item"><span class="label">Code</span><span class="value"><span class="badge badge-info">${escapeHtml(filiere.code)}</span></span></div>
                <div class="detail-item"><span class="label">Département</span><span class="value"><span class="badge badge-success">${escapeHtml(departementLibelle)}</span></span></div>
                <div class="detail-item full-width"><span class="label">Libellé</span><span class="value">${escapeHtml(filiere.libelle)}</span></div>
                <div class="detail-item full-width"><span class="label">Description</span><span class="value">${escapeHtml(filiere.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 saveFiliere() {
    const libelle      = document.getElementById('libelle').value.trim();
    const code         = document.getElementById('code').value.trim();
    const departement_id = document.getElementById('departement_id').value;
    const description  = document.getElementById('description').value.trim();

    if (!libelle)       { showToast('Libellé obligatoire', 'warning'); return; }
    if (!code)          { showToast('Code obligatoire', 'warning'); return; }
    if (!departement_id) { showToast('Département obligatoire', 'warning'); return; }

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

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

function exportFiliere() { 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();
    }
});