// js/avancement.js
const API_BASE_URL = '/est-concours/model/api/avancement.php';
const API_PROF_URL = '/est-concours/model/api/employee.php';
const API_TYPE_AVANCEMENT_URL = '/est-concours/model/api/type_avancement.php';
const API_ETAT_AVANCEMENT_URL = '/est-concours/model/api/etat_avancement.php';
const API_ECHELLON_URL = '/est-concours/model/api/echellon.php';


let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;
let allemployees = [];
let allTypes = [];
let allEtats = [];
let allEchellons = [];

// ============================================================
// INITIALIZATION
// ============================================================
document.addEventListener('DOMContentLoaded', function() {
    loadAvancements();
    loadStats();
    loadSelectOptions();
    setupSearchForm();
    setupModalEvents();
});

// ============================================================
// SEARCH & FILTER
// ============================================================
function setupSearchForm() {
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            currentPage = 1;
            loadAvancements();
        });
    }
}

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

// ============================================================
// STATS
// ============================================================
function loadStats() {
    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const stats = result.data;
                const statTotal = document.getElementById('statTotal');
                const statTypeAvancement = document.getElementById('statTypeAvancement');
                if (statTotal) statTotal.textContent = stats.total || 0;
                if (statTypeAvancement) statTypeAvancement.textContent = stats.total_types || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

// ============================================================
// LOAD SELECT OPTIONS
// ============================================================
function loadSelectOptions() {
    // Load employees
    fetch(`${API_PROF_URL}?action=list`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                allemployees = result.data;
                populateSelect('searchemployee', allemployees, 'id', 'nom', 'Tous les employees');
                populateSelect('employee_id', allemployees, 'id', 'nom', 'Sélectionner un employee');
            }
        })
        .catch(error => console.error('Error loading employees:', error));

    // Load avancement types
    fetch(`${API_TYPE_AVANCEMENT_URL}?action=list`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                allTypes = result.data;
                populateSelect('searchTypeAvancement', allTypes, 'id', 'libelle', 'Tous les types');
                populateSelect('avancement_type_id', allTypes, 'id', 'libelle', 'Sélectionner un type');
            }
        })
        .catch(error => console.error('Error loading types:', error));

    // Load etats
    fetch(`${API_ETAT_AVANCEMENT_URL}?action=list`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                allEtats = result.data;
                populateSelect('searchEtat', allEtats, 'id', 'libelle', 'Tous les états');
                populateSelect('etat_avancement_id', allEtats, 'id', 'libelle', 'Sélectionner un état');
            }
        })
        .catch(error => console.error('Error loading etats:', error));

    // Load echellons
    fetch(`${API_ECHELLON_URL}?action=list`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                allEchellons = result.data;
                populateSelect('echellon_source_id', allEchellons, 'id', 'libelle', 'Sélectionner un échelon');
                populateSelect('echellon_destination_id', allEchellons, 'id', 'libelle', 'Sélectionner un échelon');
            }
        })
        .catch(error => console.error('Error loading echellons:', error));
}

function populateSelect(selectId, data, valueKey, labelKey, defaultLabel) {
    const select = document.getElementById(selectId);
    if (!select) return;

    const currentValue = select.value;
    select.innerHTML = `<option value="">${defaultLabel}</option>`;

    data.forEach(item => {
        const option = document.createElement('option');
        option.value = item[valueKey];
        option.textContent = item[labelKey] || item.libelle || item.nom || 'Sans nom';
        select.appendChild(option);
    });

    if (currentValue && Array.from(select.options).some(opt => opt.value === currentValue)) {
        select.value = currentValue;
    }
}

// ============================================================
// employee CHANGE
// ============================================================
function onemployeeChange() {
    const employeeId = document.getElementById('employee_id').value;
    const currentEchelonInput = document.getElementById('current_echellon');
    const sourceSelect = document.getElementById('echellon_source_id');

    if (!employeeId) {
        if (currentEchelonInput) currentEchelonInput.value = '';
        if (sourceSelect) sourceSelect.value = '';
        return;
    }

    const employee = allemployees.find(p => p.id == employeeId);
    if (employee && employee.echellon_id) {
        const echelon = allEchellons.find(e => e.id == employee.echellon_id);
        if (currentEchelonInput) {
            currentEchelonInput.value = echelon ? echelon.libelle : 'Non défini';
        }
        if (echelon && sourceSelect) {
            sourceSelect.value = echelon.id;
            onEchelonSourceChange();
        }
    } else if (currentEchelonInput) {
        currentEchelonInput.value = 'Aucun échelon assigné';
        fetch(`${API_PROF_URL}?action=get&id=${employeeId}`)
            .then(response => response.json())
            .then(result => {
                if (result.success && result.data.echellon_id) {
                    const echelon = allEchellons.find(e => e.id == result.data.echellon_id);
                    if (currentEchelonInput) {
                        currentEchelonInput.value = echelon ? echelon.libelle : 'Non défini';
                    }
                    if (echelon && sourceSelect) {
                        sourceSelect.value = echelon.id;
                        onEchelonSourceChange();
                    }
                }
            })
            .catch(error => console.error('Error fetching employee details:', error));
    }
}

// ============================================================
// ECHELON SOURCE CHANGE
// ============================================================
function onEchelonSourceChange() {
    const sourceId = document.getElementById('echellon_source_id').value;
    const destSelect = document.getElementById('echellon_destination_id');

    if (!sourceId || !destSelect) {
        if (destSelect) destSelect.value = '';
        return;
    }

    const sourceEchelon = allEchellons.find(e => e.id == sourceId);
    if (sourceEchelon && sourceEchelon.echellon_suivant_id) {
        const nextEchelon = allEchellons.find(e => e.id == sourceEchelon.echellon_suivant_id);
        if (nextEchelon) {
            destSelect.value = nextEchelon.id;
            destSelect.style.borderColor = '#10b981';
            setTimeout(() => { destSelect.style.borderColor = ''; }, 2000);
            return;
        }
    }

    fetch(`${API_ECHELLON_URL}?action=get&id=${sourceId}`)
        .then(response => response.json())
        .then(result => {
            if (result.success && result.data.echellon_suivant_id) {
                const nextEchelon = allEchellons.find(e => e.id == result.data.echellon_suivant_id);
                if (nextEchelon) {
                    destSelect.value = nextEchelon.id;
                    destSelect.style.borderColor = '#10b981';
                    setTimeout(() => { destSelect.style.borderColor = ''; }, 2000);
                }
            } else {
                destSelect.value = '';
                showToast('Aucun échelon suivant disponible', 'warning');
            }
        })
        .catch(error => console.error('Error fetching echelon details:', error));
}

// ============================================================
// LOAD AVANCEMENTS
// ============================================================
function loadAvancements() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        libelle: document.getElementById('searchLibelle')?.value || '',
        employee_id: document.getElementById('searchemployee')?.value || '',
        avancement_type_id: document.getElementById('searchTypeAvancement')?.value || '',
        etat_avancement_id: document.getElementById('searchEtat')?.value || '',
        page: currentPage,
        per_page: perPage
    };

    const params = new URLSearchParams(searchData);

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

// ============================================================
// RENDER TABLE
// ============================================================
function renderTable(avancements) {
    const tbody = document.getElementById('tableBody');
    if (!tbody) return;

    if (avancements.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="10" style="text-align: center; padding: 40px; color: #666;">
                    <p style="font-size: 18px;">📭 Aucun avancement trouvé</p>
                    <p style="font-size: 14px; margin-top: 5px;">Essayez de modifier vos critères de recherche</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = avancements.map(av => `
        <tr>
            <td>${av.id}</td>
            <td><strong>${escapeHtml(av.libelle)}</strong></td>
            <td>${escapeHtml(av.employee_nom || av.employee_id || '-')}</td>
            <td>${escapeHtml(av.avancement_type_libelle || av.avancement_type_id || '-')}</td>
            <td><span class="badge ${getEtatBadgeClass(av.etat_avancement_libelle || av.etat_avancement_id)}">${escapeHtml(av.etat_avancement_libelle || av.etat_avancement_id || '-')}</span></td>
            <td>${escapeHtml(av.echellon_source_libelle || av.echellon_source_id || '-')}</td>
            <td>${escapeHtml(av.echellon_destination_libelle || av.echellon_destination_id || '-')}</td>
            <td>${formatDate(av.date_demande)}</td>
            <td>${formatDate(av.date_decision)}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${av.id})" title="Voir les détails">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${av.id})" title="Modifier">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteAvancement(${av.id})" title="Supprimer">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function getEtatBadgeClass(etatLibelle) {
    const libelle = (etatLibelle || '').toLowerCase();
    if (libelle.includes('approuvé') || libelle.includes('approuve')) return 'badge-success';
    if (libelle.includes('rejeté') || libelle.includes('rejete')) return 'badge-danger';
    if (libelle.includes('en cours')) return 'badge-warning';
    if (libelle.includes('en attente')) return 'badge-secondary';
    if (libelle.includes('révision') || libelle.includes('revision')) return 'badge-info';
    return 'badge-secondary';
}

// ============================================================
// PAGINATION
// ============================================================
function renderPagination(data) {
    const { total, page, totalPages: pages } = data;
    totalPages = pages;

    const start = (page - 1) * perPage + 1;
    const end = Math.min(page * perPage, total);
    const paginationInfo = document.getElementById('paginationInfo');
    if (paginationInfo) {
        paginationInfo.textContent = `Affichage de ${start} à ${end} sur ${total} avancements`;
    }

    const pageNumbers = document.getElementById('pageNumbers');
    if (pageNumbers) {
        let html = '';
        for (let i = 1; i <= pages; i++) {
            html += `<button onclick="goToPage(${i})" ${i === page ? 'class="active"' : ''}>${i}</button>`;
        }
        pageNumbers.innerHTML = html;
    }

    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    if (prevBtn) prevBtn.disabled = page <= 1;
    if (nextBtn) nextBtn.disabled = page >= pages;
}

function changePage(direction) {
    if (direction === 'prev' && currentPage > 1) currentPage--;
    else if (direction === 'next' && currentPage < totalPages) currentPage++;
    loadAvancements();
}

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

// ============================================================
// MODAL - CREATE / EDIT
// ============================================================
function openCreateModal() {
    editMode = false;
    const modalTitle = document.getElementById('modalTitle');
    const form = document.getElementById('avancementForm');
    const idInput = document.getElementById('avancementId');
    const currentEchelon = document.getElementById('current_echellon');
    const destSelect = document.getElementById('echellon_destination_id');

    if (modalTitle) modalTitle.textContent = 'Nouvel Avancement';
    if (form) form.reset();
    if (idInput) idInput.value = '';
    if (currentEchelon) currentEchelon.value = '';
    if (destSelect) destSelect.value = '';

    const modal = document.querySelector('.modal-overlay');
    if (modal) modal.classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    const modalTitle = document.getElementById('modalTitle');
    const idInput = document.getElementById('avancementId');

    if (modalTitle) modalTitle.textContent = 'Modifier Avancement';
    if (idInput) idInput.value = id;

    const detailModal = document.getElementById('detailModal');
    if (detailModal && detailModal.classList.contains('active')) {
        closeDetailModal();
    }

    const modal = document.querySelector('.modal-overlay');
    if (modal) modal.classList.add('active');

    const form = document.getElementById('avancementForm');
    if (form) setFormEnabled(form, false);

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (form) setFormEnabled(form, true);
            if (result.success) {
                const av = result.data;
                const employeeSelect = document.getElementById('employee_id');
                const typeSelect = document.getElementById('avancement_type_id');
                const etatSelect = document.getElementById('etat_avancement_id');
                const sourceSelect = document.getElementById('echellon_source_id');
                const destSelect = document.getElementById('echellon_destination_id');
                const dateDemande = document.getElementById('date_demande');
                const dateDecision = document.getElementById('date_decision');
                const description = document.getElementById('description');
                const libelle = document.getElementById('libelle');

                if (employeeSelect) employeeSelect.value = av.employee_id || '';
                if (typeSelect) typeSelect.value = av.avancement_type_id || '';
                if (etatSelect) etatSelect.value = av.etat_avancement_id || '';
                if (sourceSelect) sourceSelect.value = av.echellon_source_id || '';
                if (destSelect) destSelect.value = av.echellon_destination_id || '';
                if (dateDemande) dateDemande.value = av.date_demande || '';
                if (dateDecision) dateDecision.value = av.date_decision || '';
                if (description) description.value = av.description || '';
                if (libelle) libelle.value = av.libelle || '';

                if (av.employee_id) onemployeeChange();
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(error => {
            if (form) setFormEnabled(form, true);
            showToast('Erreur de connexion au serveur', 'error');
            closeModal();
            console.error('Error:', error);
        });
}

function setFormEnabled(form, enabled) {
    const inputs = form.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        if (input.id !== 'current_echellon') {
            input.disabled = !enabled;
        }
    });
    const saveBtn = document.getElementById('saveBtn');
    if (saveBtn) saveBtn.disabled = !enabled;
}

// ============================================================
// SAVE AVANCEMENT
// ============================================================
function saveAvancement() {
    const libelle = document.getElementById('libelle');
    const employeeId = document.getElementById('employee_id');
    const typeId = document.getElementById('avancement_type_id');
    const etatId = document.getElementById('etat_avancement_id');
    const sourceId = document.getElementById('echellon_source_id');
    const destId = document.getElementById('echellon_destination_id');
    const dateDemande = document.getElementById('date_demande');
    const dateDecision = document.getElementById('date_decision');
    const description = document.getElementById('description');
    const avancementId = document.getElementById('avancementId');

    const data = {
        libelle: libelle ? libelle.value.trim() : '',
        employee_id: employeeId ? employeeId.value : '',
        avancement_type_id: typeId ? typeId.value : '',
        etat_avancement_id: etatId ? etatId.value : '',
        echellon_source_id: sourceId ? sourceId.value : '',
        echellon_destination_id: destId ? destId.value : '',
        date_demande: dateDemande ? dateDemande.value || null : null,
        date_decision: dateDecision ? dateDecision.value || null : null,
        description: description ? description.value.trim() || null : null
    };

    // Validation
    if (!data.libelle) {
        showToast('Veuillez saisir un libellé', 'warning');
        if (libelle) libelle.focus();
        return;
    }
    if (!data.employee_id) {
        showToast('Veuillez sélectionner un employee', 'warning');
        if (employeeId) employeeId.focus();
        return;
    }
    if (!data.avancement_type_id) {
        showToast('Veuillez sélectionner un type d\'avancement', 'warning');
        if (typeId) typeId.focus();
        return;
    }
    if (!data.etat_avancement_id) {
        showToast('Veuillez sélectionner un état', 'warning');
        if (etatId) etatId.focus();
        return;
    }
    if (!data.echellon_source_id) {
        showToast('Veuillez sélectionner un échelon source', 'warning');
        if (sourceId) sourceId.focus();
        return;
    }
    if (!data.echellon_destination_id) {
        showToast('Veuillez sélectionner un échelon destination', 'warning');
        if (destId) destId.focus();
        return;
    }

    const employee = allemployees.find(p => p.id == data.employee_id);
    if (employee && employee.echellon_id) {
        if (parseInt(data.echellon_source_id) !== parseInt(employee.echellon_id)) {
            if (!confirm('L\'échelon source ne correspond pas à l\'échelon actuel du employee. Voulez-vous continuer quand même ?')) {
                return;
            }
        }
    }

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

    const saveBtn = document.getElementById('saveBtn');
    const originalText = saveBtn ? saveBtn.innerHTML : 'Enregistrer';
    if (saveBtn) {
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';
        saveBtn.disabled = true;
    }

    fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            if (saveBtn) {
                saveBtn.innerHTML = originalText;
                saveBtn.disabled = false;
            }
            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadAvancements();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            if (saveBtn) {
                saveBtn.innerHTML = originalText;
                saveBtn.disabled = false;
            }
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ============================================================
// DELETE
// ============================================================
function deleteAvancement(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cet avancement ?\n\nCette action est irréversible.')) return;

    const btn = document.querySelector(`button[onclick="deleteAvancement(${id})"]`);
    if (btn) {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
    }

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(response => response.json())
        .then(result => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }
            if (result.success) {
                showToast(result.message, 'success');
                loadAvancements();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

// ============================================================
// DETAIL VIEW
// ============================================================
function viewDetail(id) {
    currentDetailId = id;

    const detailModal = document.getElementById('detailModal');
    const detailContent = document.getElementById('detailContent');
    const editBtn = document.getElementById('editFromDetailBtn');

    if (detailModal) detailModal.classList.add('active');
    if (detailContent) {
        detailContent.innerHTML = `
            <div class="loading active">
                <div class="spinner"></div>
                <p style="margin-top: 10px;">Chargement des détails...</p>
            </div>
        `;
    }
    if (editBtn) editBtn.style.display = 'none';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
            } else if (detailContent) {
                detailContent.innerHTML = `
                    <div class="error-state">
                        <i class="fas fa-exclamation-circle"></i>
                        <p>Erreur: ${result.message}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            if (detailContent) {
                detailContent.innerHTML = `
                    <div class="error-state">
                        <i class="fas fa-exclamation-circle"></i>
                        <p>Erreur de connexion au serveur</p>
                    </div>
                `;
            }
            console.error('Error:', error);
        });
}

function renderDetail(av) {
    const getLabel = (id, list) => {
        if (!id) return '-';
        const item = list.find(i => i.id == id);
        return item ? item.libelle : id;
    };

    const detailContent = document.getElementById('detailContent');
    const editBtn = document.getElementById('editFromDetailBtn');

    if (detailContent) {
        detailContent.innerHTML = `
            <div class="detail-section">
                <div class="detail-header">
                    <div class="detail-avatar">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                    <div class="detail-title">
                        <h2>${escapeHtml(av.libelle)}</h2>
                        <div class="detail-meta">
                            <span class="badge badge-info">
                                <i class="fas fa-hashtag"></i> #${av.id}
                            </span>
                            <span class="meta-text">
                                <i class="fas fa-calendar-alt"></i> 
                                Créé le ${formatDate(av.date_creation)}
                            </span>
                            ${av.date_modification ? `
                                <span class="meta-text">
                                    <i class="fas fa-edit"></i> 
                                    Mis à jour le ${formatDate(av.date_modification)}
                                </span>
                            ` : ''}
                        </div>
                    </div>
                </div>
                
                <h3><i class="fas fa-info-circle"></i> Informations de l'Avancement</h3>
                <div class="detail-grid">
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-user"></i> employee</span>
                        <span class="value">${escapeHtml(getLabel(av.employee_id, allemployees))}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-tag"></i> Type</span>
                        <span class="value">${escapeHtml(getLabel(av.avancement_type_id, allTypes))}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-layer-group"></i> État</span>
                        <span class="value"><span class="badge ${getEtatBadgeClass(getLabel(av.etat_avancement_id, allEtats))}">${escapeHtml(getLabel(av.etat_avancement_id, allEtats))}</span></span>
                    </div>
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-arrow-up"></i> Échelon Source</span>
                        <span class="value">${escapeHtml(getLabel(av.echellon_source_id, allEchellons))}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-arrow-right"></i> Échelon Destination</span>
                        <span class="value">${escapeHtml(getLabel(av.echellon_destination_id, allEchellons))}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-calendar-day"></i> Date Demande</span>
                        <span class="value">${formatDate(av.date_demande)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label"><i class="fas fa-calendar-check"></i> Date Décision</span>
                        <span class="value">${formatDate(av.date_decision)}</span>
                    </div>
                    <div class="detail-item full-width">
                        <span class="label"><i class="fas fa-align-left"></i> Description</span>
                        <span class="value ${!av.description ? 'empty' : ''}">
                            ${av.description ? escapeHtml(av.description) : 'Aucune description'}
                        </span>
                    </div>
                </div>
                
                <div class="detail-metadata">
                    <h4><i class="fas fa-clock"></i> Métadonnées</h4>
                    <div class="metadata-grid">
                        <div class="meta-item">
                            <span class="meta-label">Date de création:</span>
                            <span class="meta-value">${formatDate(av.date_creation)}</span>
                        </div>
                        <div class="meta-item">
                            <span class="meta-label">Dernière mise à jour:</span>
                            <span class="meta-value">${av.date_modification ? formatDate(av.date_modification) : 'Jamais'}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    if (editBtn) editBtn.style.display = 'inline-flex';
}

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

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

// ============================================================
// EXPORT
// ============================================================
function exportAvancements() {
    const searchData = {
        employee_id: document.getElementById('searchemployee')?.value || '',
        avancement_type_id: document.getElementById('searchTypeAvancement')?.value || '',
        etat_avancement_id: document.getElementById('searchEtat')?.value || ''
    };
    const params = new URLSearchParams(searchData);
    window.location.href = `${API_BASE_URL}?action=export&${params.toString()}`;
}

// ============================================================
// MODAL EVENTS
// ============================================================
function setupModalEvents() {
    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') {
            const detailModal = document.getElementById('detailModal');
            if (detailModal && detailModal.classList.contains('active')) {
                closeDetailModal();
            } else if (document.querySelector('.modal-overlay.active')) {
                closeModal();
            }
        }
    });

    const btnNew = document.getElementById('btnNouvelAvancement');
    if (btnNew) btnNew.addEventListener('click', openCreateModal);
}

function closeModal() {
    const modal = document.querySelector('.modal-overlay');
    if (modal) modal.classList.remove('active');
    const form = document.getElementById('avancementForm');
    if (form) {
        form.querySelectorAll('.form-group').forEach(g => g.classList.remove('has-error'));
    }
}

// ============================================================
// UTILITY FUNCTIONS
// ============================================================
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');
    if (!container) return;

    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 formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    return date.toLocaleString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

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