const API_URL = '/est-concours/model/api/type_diplome.php';

let currentPage = 1;
let perPage = 10;
let totalPages = 1;

let currentId = null;
let editMode = false;

document.addEventListener("DOMContentLoaded", () => {

    loadStats();

    loadData();

    document
        .getElementById("searchForm")
        .addEventListener("submit", function (e) {

            e.preventDefault();

            currentPage = 1;

            loadData();

        });

});

function loadData() {

    loadTypes();

}

function resetSearch() {

    document
        .getElementById("searchForm")
        .reset();

    currentPage = 1;

    loadData();

}

function loadStats() {

    fetch(API_URL + "?action=stats")

        .then(r => r.json())

        .then(res => {

            if (res.success) {

                document
                    .getElementById("statTotal")
                    .innerHTML = res.data.total;

                // Get stats by year
                fetch(API_URL + "?action=all")
                    .then(r => r.json())
                    .then(allRes => {
                        if (allRes.success) {
                            const years = {};
                            allRes.data.forEach(item => {
                                const year = item.annee_apres_bac || 0;
                                years[year] = (years[year] || 0) + 1;
                            });
                            let statText = '';
                            for (const [year, count] of Object.entries(years)) {
                                statText += `${year}ans: ${count} `;
                            }
                            document.getElementById("statByYear").innerHTML = statText || 'Aucun';
                        }
                    });

            }

        });

}

function loadTypes() {

    const id =
        document.getElementById("searchId").value;

    const libelle =
        document.getElementById("searchLibelle").value;

    const code =
        document.getElementById("searchCode").value;

    const annee_apres_bac =
        document.getElementById("searchAnneeApresBac").value;

    fetch(
        API_URL +
        "?action=search" +
        "&id=" + encodeURIComponent(id) +
        "&libelle=" + encodeURIComponent(libelle) +
        "&code=" + encodeURIComponent(code) +
        "&annee_apres_bac=" + encodeURIComponent(annee_apres_bac) +
        "&page=" + currentPage +
        "&per_page=" + perPage
    )

        .then(r => r.json())

        .then(res => {

            if (res.success) {

                renderTable(res.data.data);

                renderPagination(res.data);

            }
            else {

                showToast(res.message, "error");

            }

        });

}

function renderTable(data) {

    let html = "";

    if (data.length === 0) {

        html = `
            <tr>
                <td colspan="5" style="text-align:center;">
                    Aucun résultat
                </td>
            </tr>
        `;

    } else {

        data.forEach(t => {

            html += `

            <tr>

                <td>${t.id}</td>

                <td>${escapeHtml(t.libelle)}</td>

                <td><span class="badge badge-info">${escapeHtml(t.code)}</span></td>

                <td><span class="badge badge-success">${t.annee_apres_bac || 0} ans</span></td>

                <td>

                    <button
                        class="btn btn-info btn-sm"
                        onclick="viewDetail(${t.id})">

                        <i class="fas fa-eye"></i>

                    </button>

                    <button
                        class="btn btn-warning btn-sm"
                        onclick="openEditModal(${t.id})">

                        <i class="fas fa-edit"></i>

                    </button>

                    <button
                        class="btn btn-danger btn-sm"
                        onclick="deleteTypeDiplome(${t.id})">

                        <i class="fas fa-trash"></i>

                    </button>

                </td>

            </tr>

            `;

        });

    }

    document.getElementById("tableBody").innerHTML = html;

}

function renderPagination(data) {

    totalPages = data.totalPages;

    document.getElementById("paginationInfo").innerHTML =
        "Affichage de " +
        (((data.page - 1) * perPage) + 1) +
        " à " +
        Math.min(data.page * perPage, data.total) +
        " sur " +
        data.total;

    let html = "";

    for (let i = 1; i <= totalPages; i++) {

        html += `

        <button
            class="${i == data.page ? "active" : ""}"
            onclick="goToPage(${i})">

            ${i}

        </button>

        `;

    }

    document.getElementById("pageNumbers").innerHTML = html;

    document.getElementById("prevBtn").disabled =
        data.page == 1;

    document.getElementById("nextBtn").disabled =
        data.page == totalPages;

}

function changePage(type) {

    if (type == "prev" && currentPage > 1) {

        currentPage--;

    }

    if (type == "next" && currentPage < totalPages) {

        currentPage++;

    }

    loadData();

}

function goToPage(page) {

    currentPage = page;

    loadData();

}

function openCreateModal() {

    editMode = false;

    currentId = null;

    document.getElementById("modalTitle").innerHTML =
        "Nouveau Type de Diplôme";

    document.getElementById("typeDiplomeId").value = "";

    document.getElementById("typeDiplomeForm").reset();

    document.getElementById("formModal").classList.add("active");

}

function openEditModal(id) {

    editMode = true;

    currentId = id;

    document.getElementById("modalTitle").innerHTML =
        "Modifier Type de Diplôme";

    // Close detail modal if open
    if (document.getElementById("detailModal").classList.contains("active")) {
        closeDetailModal();
    }

    document.getElementById("formModal").classList.add("active");

    // Disable fields while loading
    ['libelle', 'code', 'annee_apres_bac'].forEach(f => {
        document.getElementById(f).disabled = true;
        document.getElementById(f).value = 'Chargement...';
    });

    fetch(API_URL + "?action=get&id=" + id)

        .then(r => r.json())

        .then(res => {

            ['libelle', 'code', 'annee_apres_bac'].forEach(f => {
                document.getElementById(f).disabled = false;
            });

            if (res.success) {

                const data = res.data;

                document.getElementById("libelle").value = data.libelle || "";
                document.getElementById("code").value = data.code || "";
                document.getElementById("annee_apres_bac").value = data.annee_apres_bac || 0;

            } else {

                showToast(res.message, "error");

                closeModal();

            }

        })

        .catch(() => {

            ['libelle', 'code', 'annee_apres_bac'].forEach(f => {
                document.getElementById(f).disabled = false;
            });

            showToast("Erreur de connexion", "error");

            closeModal();

        });

}

function viewDetail(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 des détails...</p>
        </div>
    `;

    document.getElementById("editFromDetailBtn").style.display = "none";

    fetch(API_URL + "?action=get&id=" + id)

        .then(r => r.json())

        .then(res => {

            if (res.success) {

                renderDetail(res.data);

                document.getElementById("editFromDetailBtn").style.display = "inline-flex";
                document.getElementById("editFromDetailBtn").onclick = function() {
                    closeDetailModal();
                    setTimeout(() => openEditModal(id), 300);
                };

            } else {

                document.getElementById("detailContent").innerHTML =
                    `<p class="text-danger">${res.message}</p>`;

            }

        });

}

function renderDetail(data) {

    document.getElementById("detailContent").innerHTML = `

        <div class="detail-section">

            <div class="detail-header">

                <div class="detail-avatar">

                    <i class="fas fa-graduation-cap"></i>

                </div>

                <div class="detail-title">

                    <h2>${escapeHtml(data.libelle)}</h2>

                    <div class="detail-meta">

                        <span class="badge badge-info">${escapeHtml(data.code)}</span>

                        <span class="badge badge-success">${data.annee_apres_bac || 0} ans après Bac</span>

                    </div>

                </div>

            </div>

            <div class="detail-grid">

                <div class="detail-item">

                    <span class="label">ID</span>

                    <span class="value">${data.id}</span>

                </div>

                <div class="detail-item">

                    <span class="label">Code</span>

                    <span class="value"><span class="badge badge-info">${escapeHtml(data.code)}</span></span>

                </div>

                <div class="detail-item">

                    <span class="label">Années après Bac</span>

                    <span class="value"><span class="badge badge-success">${data.annee_apres_bac || 0} ans</span></span>

                </div>

                <div class="detail-item full-width">

                    <span class="label">Libellé</span>

                    <span class="value">${escapeHtml(data.libelle)}</span>

                </div>

            </div>

        </div>

    `;

}

function closeDetailModal() {

    document.getElementById("detailModal").classList.remove("active");

}

function editFromDetail() {

    // This is handled inline in viewDetail now

}

function saveTypeDiplome() {

    const libelle =
        document.getElementById("libelle").value.trim();

    const code =
        document.getElementById("code").value.trim();

    const annee_apres_bac =
        document.getElementById("annee_apres_bac").value;

    if (!libelle) {

        showToast("Le libellé est obligatoire", "warning");

        return;

    }

    if (!code) {

        showToast("Le code est obligatoire", "warning");

        return;

    }

    if (annee_apres_bac === "" || isNaN(annee_apres_bac) || parseInt(annee_apres_bac) < 0) {

        showToast("Le nombre d'années après bac doit être un nombre positif", "warning");

        return;

    }

    const id =
        document.getElementById("typeDiplomeId").value;

    const url = id ?
        API_URL + "?action=update&id=" + id :
        API_URL;

    const method = id ? "PUT" : "POST";

    const saveBtn = document.querySelector('#formModal .btn-primary');

    const origText = saveBtn.innerHTML;

    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

    saveBtn.disabled = true;

    fetch(url, {

        method: method,

        headers: {

            "Content-Type": "application/json"

        },

        body: JSON.stringify({

            libelle: libelle,

            code: code,

            annee_apres_bac: parseInt(annee_apres_bac)

        })

    })

        .then(r => r.json())

        .then(res => {

            saveBtn.innerHTML = origText;

            saveBtn.disabled = false;

            if (res.success) {

                showToast(res.message, "success");

                closeModal();

                loadData();

                loadStats();

            } else {

                showToast(res.message, "error");

            }

        })

        .catch(() => {

            saveBtn.innerHTML = origText;

            saveBtn.disabled = false;

            showToast("Erreur de connexion", "error");

        });

}

function deleteTypeDiplome(id) {

    if (!confirm("Supprimer ce type de diplôme ?")) {

        return;

    }

    fetch(API_URL + "?action=delete&id=" + id, {

        method: "DELETE"

    })

        .then(r => r.json())

        .then(res => {

            if (res.success) {

                showToast(res.message, "success");

                loadData();

                loadStats();

            } else {

                showToast(res.message, "error");

            }

        });

}

function exportData() {

    window.location.href = API_URL + "?action=export";

}

function closeModal() {

    document.getElementById("formModal").classList.remove("active");

}

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;

}

// Close modals on overlay click
document.querySelectorAll('.modal-overlay').forEach(modal => {

    modal.addEventListener('click', function(e) {

        if (e.target === this) {

            if (this.id === 'detailModal') closeDetailModal();

            else closeModal();

        }

    });

});

// Close modals on ESC key
document.addEventListener('keydown', function(e) {

    if (e.key === 'Escape') {

        if (document.getElementById('detailModal').classList.contains('active')) closeDetailModal();

        else if (document.getElementById('formModal').classList.contains('active')) closeModal();

    }

});
