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

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

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

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

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

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

    tbody.innerHTML = departements.map(departement => `
        <tr>
            <td>${departement.id}</td>
            <td><strong>${escapeHtml(departement.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(departement.code)}</span></td>
            <td>${escapeHtml(departement.description || '-')}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${departement.id})"><i class="fas fa-eye"></i></button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${departement.id})"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm" onclick="deleteDepartement(${departement.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} départements`;
    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++;
    loadDepartements();
}

function goToPage(page) {
    currentPage = page;
    loadDepartements();
}

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Département';
    document.getElementById('departementForm').reset();
    document.getElementById('departementId').value = '';
    document.getElementById('code').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function onLibelleChange() {
    const libelleInput = document.getElementById('libelle');
    const codeInput = document.getElementById('code');
    const libelle = libelleInput.value.trim();

    if (libelle) {
        const code = libelle.toUpperCase()
            .replace(/\s+/g, '-')
            .replace(/[^A-Z0-9-]/g, '')
            .substring(0, 20);
        codeInput.value = code;
    }
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Département';
    document.getElementById('departementId').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;
    });

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

            if (result.success) {
                const d = result.data;
                document.getElementById('libelle').value = d.libelle || '';
                document.getElementById('code').value = d.code || '';
                document.getElementById('description').value = d.description || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(() => {
            ['libelle', 'code', 'description'].forEach(f => {
                document.getElementById(f).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(departement) {
    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(departement.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">${escapeHtml(departement.code)}</span>
                    </div>
                </div>
            </div>
            <div class="detail-grid">
                <div class="detail-item"><span class="label">ID</span><span class="value">${departement.id}</span></div>
                <div class="detail-item"><span class="label">Code</span><span class="value"><span class="badge badge-info">${escapeHtml(departement.code)}</span></span></div>
                <div class="detail-item full-width"><span class="label">Libellé</span><span class="value">${escapeHtml(departement.libelle)}</span></div>
                <div class="detail-item full-width"><span class="label">Description</span><span class="value">${escapeHtml(departement.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 saveDepartement() {
    const libelle = document.getElementById('libelle').value.trim();
    const code = document.getElementById('code').value.trim();
    const description = document.getElementById('description').value.trim();

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

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

function deleteDepartement(id) {
    if (!confirm('Supprimer ce département ? Cette action est irréversible.')) return;

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                loadDepartements();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(() => {
            showToast('Erreur de connexion', 'error');
        });
}

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