const API_BASE_URL = '/est-concours/model/api/type_document_dossier_administratif.php';

let currentPage = 1;
let perPage = 10;
let totalPages = 1;
let editMode = false;
let currentId = null;

document.addEventListener("DOMContentLoaded", () => {
    loadTypes();
    loadStats();
    loadData();

    document.getElementById("searchForm").addEventListener("submit", function (e) {
        e.preventDefault();
        currentPage = 1;
        loadData();
    });
});

function resetSearch() {
    document.getElementById("searchForm").reset();
    currentPage = 1;
    loadData();
}

function loadStats() {

    fetch(API_BASE_URL + "?action=stats")
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                document.getElementById("statTotal").innerHTML = res.data.total;
            }
        });
}

function loadTypes() {

    const id = document.getElementById("searchId")?.value || "";
    const libelle = document.getElementById("searchLibelle")?.value || "";
    const code = document.getElementById("searchCode")?.value || "";

    fetch(API_BASE_URL +
        "?action=search" +
        "&id=" + encodeURIComponent(id) +
        "&libelle=" + encodeURIComponent(libelle) +
        "&code=" + encodeURIComponent(code) +
        "&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 loadData() {
    loadTypes();
}

function renderTable(data) {
    let html = "";
    if (data.length == 0) {
        html = `
        <tr>
            <td colspan="5">
                Aucun résultat
            </td>

        </tr>
        `;

    } else {

        data.forEach(t => {

            html += `

            <tr>
                <td>${t.id}</td>
                <td>${escapeHtml(t.libelle)}</td>
                <td>${escapeHtml(t.code)}</td>
                <td>${escapeHtml(t.description ?? "-")}</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="deleteType(${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;

    document.getElementById("modalTitle").innerHTML =
        "Nouveau Type Document Dossier Administratif";

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

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

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

}

function openEditModal(id) {

    editMode = true;

    document.getElementById("modalTitle").innerHTML =
        "Modifier Type de Document Administratif";

    document.getElementById("typeDocumentId").value = id;

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

    fetch(API_BASE_URL + "?action=get&id=" + id)
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                const d = res.data;
                document.getElementById("libelle").value = d.libelle;
                document.getElementById("code").value = d.code;
                document.getElementById("description").value =
                    d.description ?? "";

            } else {
                showToast(res.message, "error");
            }
        });
}

function saveTypeDocument() {

    const id =
        document.getElementById("typeDocumentId").value;
    const data = {
        libelle:
            document.getElementById("libelle").value.trim(),
        code:
            document.getElementById("code").value.trim(),
        description:
            document.getElementById("description").value.trim()

    };

    if (data.libelle == "") {
        showToast("Libellé obligatoire", "warning");
        return;

    }

    if (data.code == "") {
        showToast("Code obligatoire", "warning");
        return;

    }

    const method = id ? "PUT" : "POST";
    const url = id
        ? API_BASE_URL + "?action=update&id=" + id
        : API_BASE_URL;

    fetch(url, {
        method: method,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)

    })

        .then(r => r.json())
        .then(res => {
            if (res.success) {
                showToast(res.message, "success");
                closeModal();
                loadData();
                loadStats();
            } else {
                showToast(res.message, "error");
            }
        });

}

function closeModal() {
    document
        .getElementById("formModal")
        .classList
        .remove("active");

}

function viewDetail(id) {

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

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

        .then(res => {

            if (!res.success) {

                showToast(res.message, "error");
                return;

            }

            const d = res.data;

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

            <table class="table">

                <tr>

                    <th>ID</th>

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

                </tr>

                <tr>

                    <th>Libellé</th>

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

                </tr>

                <tr>

                    <th>Code</th>

                    <td>${escapeHtml(d.code)}</td>

                </tr>

                <tr>

                    <th>Description</th>

                    <td>${escapeHtml(d.description ?? "-")}</td>

                </tr>

            </table>

        `;

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

        });

}

function closeDetailModal() {

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

}

function deleteType(id) {

    if (!confirm("Supprimer cet élément ?"))
        return;

    fetch(API_BASE_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 exportTypes() {
    window.location.href = `${API_BASE_URL}?action=export`;
}

function showToast(message, type = "info") {

    const container =
        document.getElementById("toastContainer");

    const toast =
        document.createElement("div");

    toast.className =
        "toast toast-" + type;

    toast.innerHTML = message;

    container.appendChild(toast);

    setTimeout(() => {

        toast.remove();

    }, 3000);

}

function escapeHtml(text) {

    if (text == null)
        return "";

    const div = document.createElement("div");

    div.textContent = text;

    return div.innerHTML;

}

document.querySelectorAll(".modal-overlay")
    .forEach(m => {

        m.addEventListener("click", function (e) {

            if (e.target === this) {

                if (this.id == "detailModal") {

                    closeDetailModal();

                } else {

                    closeModal();

                }

            }

        });

    });

document.addEventListener("keydown", function (e) {

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

        closeModal();

        closeDetailModal();

    }

});
