// app/view/admin/type_avancement/list/main.js
const API_BASE_URL = '/est-concours/model/api/type_avancement.php'; 
let currentPage = 1;
const perPage = 10;
let totalPages = 1;

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

function setupSearchForm() {
    const form = document.getElementById('searchForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault(); // Bloquer le comportement par défaut du formulaire
            currentPage = 1;
            loadTypes();
        });
    }
}

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

// FIX DIAL FILTRAGE : Passation de action=search s7i7a f l'URL
function loadTypes() {
    const codeVal = document.getElementById('searchCode') ? document.getElementById('searchCode').value : '';
    const libelleVal = document.getElementById('searchLibelle') ? document.getElementById('searchLibelle').value : '';

    // Construction dial les paramètres dial l'URL
    const params = new URLSearchParams();
    params.append('action', 'search'); // Hna dman-na anna $_GET['action'] gha t-koun 'search'
    params.append('code', codeVal);
    params.append('libelle', libelleVal);
    params.append('page', currentPage);
    params.append('per_page', perPage);

    fetch(`${API_BASE_URL}?${params.toString()}`)
        .then(res => {
            if (!res.ok) throw new Error("Erreur serveur");
            return res.json();
        })
        .then(result => {
            if (result.success) {
                // Vérification dial la structure dial l'API data
                let items = [];
                if (result.data) {
                    items = result.data.data ? result.data.data : (Array.isArray(result.data) ? result.data : []);
                }
                renderTable(items);
                renderPagination(result.data || { page: 1, totalPages: 1 });
            } else {
                alert("Erreur API : " + result.message);
            }
        })
        .catch(err => {
            console.error("Erreur AJAX:", err);
        });
}

function renderTable(types) {
    const tbody = document.getElementById('tableBody');
    if (!tbody) return;

    if (!types || types.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:20px;color:#dc3545;">📭 Aucun type d\'avancement trouvé.</td></tr>';
        return;
    }

    tbody.innerHTML = types.map(type => `
        <tr>
            <td>${type.id}</td>
            <td><strong>${escapeHtml(type.code)}</strong></td>
            <td>${escapeHtml(type.libelle)}</td>
            <td>${escapeHtml(type.description || '-')}</td>
            <td><span class="badge badge-success">Actif</span></td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${type.id})" style="padding:4px 8px; margin-right:2px;"><i class="fas fa-eye"></i></button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${type.id})" style="padding:4px 8px; margin-right:2px;"><i class="fas fa-edit"></i></button>
                <button class="btn btn-danger btn-sm" onclick="deleteType(${type.id})" style="padding:4px 8px;"><i class="fas fa-trash"></i></button>
            </td>
        </tr>
    `).join('');
}

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

function goToPage(p) { 
    currentPage = p; 
    loadTypes(); 
}

function openCreateModal() {
    document.getElementById('modalTitle').textContent = "Ajouter un Type d'Avancement";
    const form = document.getElementById('typeAvancementForm');
    if (form) form.reset();
    document.getElementById('typeAvancementId').value = '';
    document.getElementById('typeAvancementModal').classList.add('active');
}

function openEditModal(id) {
    document.getElementById('modalTitle').textContent = "Modifier la Configuration";
    document.getElementById('typeAvancementId').value = id;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(res => res.json())
        .then(result => {
            if (result.success) {
                const t = result.data;
                document.getElementById('code').value = t.code;
                document.getElementById('libelle').value = t.libelle;
                document.getElementById('description').value = t.description || '';
                document.getElementById('typeAvancementModal').classList.add('active');
            }
        });
}

// FIX DIAL ENREGISTRER / MODIFIER : URL specifique m3a action s7i7a
function saveTypeAvancement() {
    const id = document.getElementById('typeAvancementId').value;
    const codeVal = document.getElementById('code') ? document.getElementById('code').value : '';
    const libelleVal = document.getElementById('libelle') ? document.getElementById('libelle').value : '';
    const descriptionVal = document.getElementById('description') ? document.getElementById('description').value : '';

    if (!libelleVal) { 
        alert('Le champ Libellé est obligatoire !'); 
        return; 
    }

    const data = {
        code: codeVal || null,
        libelle: libelleVal,
        description: descriptionVal || null
    };

    // Hna zdna l'action explicitement f l'URL bach l'API matchoufch 'search' par défaut
    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : `${API_BASE_URL}?action=create`;
    const methodType = id ? 'PUT' : 'POST';

    fetch(url, {
        method: methodType,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(res => res.json())
    .then(res => {
        if (res.success) {
            closeModal();
            loadTypes();
            alert(res.message || 'Opération réussie !');
        } else {
            alert('Erreur: ' + res.message);
        }
    })
    .catch(err => {
        console.error("Erreur Enregistrement:", err);
        alert("Erreur de communication avec le serveur.");
    });
}

function viewDetail(id) {
    document.getElementById('detailModal').classList.add('active');
    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(res => res.json())
        .then(res => {
            if (res.success) {
                document.getElementById('detailContent').innerHTML = `
                    <div style="padding: 10px 0;">
                        <p style="margin-bottom:10px;"><strong>Code :</strong> ${escapeHtml(res.data.code)}</p>
                        <p style="margin-bottom:10px;"><strong>Libellé :</strong> ${escapeHtml(res.data.libelle)}</p>
                        <p style="margin-bottom:10px;"><strong>Description :</strong> ${escapeHtml(res.data.description || 'Aucune')}</p>
                    </div>
                `;
            }
        });
}

function deleteType(id) {
    if (!confirm('Voulez-vous vraiment supprimer ce type d\'avancement ?')) return;
    fetch(`${API_BASE_URL}?action=delete&id=${id}`, { method: 'DELETE' })
        .then(res => res.json())
        .then(res => {
            if (res.success) { loadTypes(); alert('Supprimé avec succès !'); }
        });
}

function closeModal() { document.getElementById('typeAvancementModal').classList.remove('active'); }
function closeDetailModal() { document.getElementById('detailModal').classList.remove('active'); }

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