
const API_BASE_URL = '/est-concours/model/api/demande_document.php';
const API_PROFESSEURS_URL = API_BASE_URL + '?action=professeurs';
const API_TYPE_DOCUMENT_URL = API_BASE_URL + '?action=type_documents';
const API_ETATS_URL = API_BASE_URL + '?action=etats';

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

let editMode = false;
let currentDetailId = null;

// Maps
let professeursMap = {};
let typeDocumentsMap = {};
let etatsMap = {};

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

    loadSelects();
    loadDemandes();
    loadStats();
    setupSearchForm();

});

function setupSearchForm() {
    const form = document.getElementById('searchForm');
    if (!form) return;
    form.addEventListener('submit', function(e){
        e.preventDefault();
        currentPage = 1;
        loadDemandes();
    });
}

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


async function loadSelects(){
    await Promise.all([
        loadProfesseurs(),
        loadTypesDocuments(),
        loadEtats()
    ]);
}

async function loadProfesseurs(){
    try{
        const response = await fetch(API_PROFESSEURS_URL);
        const result = await response.json();
        if(!result.success) return;
        professeursMap = {};
        const recherche = document.getElementById('searchProfesseur');
        const formulaire = document.getElementById('professeur_id');
        recherche.innerHTML =
            '<option value="">Tous les professeurs</option>';
        formulaire.innerHTML =
            '<option value="">Sélectionner un professeur</option>';
        result.data.forEach(p=>{
            professeursMap[p.id]=p;
            const texte =
                `${p.nom} ${p.prenom}`;
            recherche.innerHTML +=
                `<option value="${p.id}">${texte}</option>`;
            formulaire.innerHTML +=
                `<option value="${p.id}">${texte}</option>`;
        });

    }catch(e){
        console.error(e);
    }
}

async function loadTypesDocuments(){
    try{
        const response = await fetch(API_TYPE_DOCUMENT_URL);
        const result = await response.json();
        if(!result.success) return;
        typeDocumentsMap = {};
        const recherche =
            document.getElementById('searchTypeDocument');
        const formulaire =
            document.getElementById('type_document_id');
        recherche.innerHTML =
            '<option value="">Tous les types</option>';
        formulaire.innerHTML =
            '<option value="">Sélectionner un type</option>';
        result.data.forEach(t=>{
            typeDocumentsMap[t.id]=t;
            recherche.innerHTML +=
            `<option value="${t.id}">
                ${t.libelle}
            </option>`;
            formulaire.innerHTML +=
            `<option value="${t.id}">
                ${t.libelle}
            </option>`;
        });

    }catch(e){
        console.error(e);
    }
}

async function loadEtats(){
    try{
        const response = await fetch(API_ETATS_URL);
        const result = await response.json();
        if(!result.success) return;
        etatsMap={};
        const recherche =
            document.getElementById('searchEtat');
        const formulaire =
            document.getElementById('etat_demande_document_id');
        recherche.innerHTML =
        '<option value="">Tous les états</option>';
        formulaire.innerHTML =
        '<option value="">Sélectionner un état</option>';
        result.data.forEach(etat=>{
            etatsMap[etat.id]=etat;
            recherche.innerHTML +=
            `<option value="${etat.id}">
                ${etat.libelle}
            </option>`;
            formulaire.innerHTML +=
            `<option value="${etat.id}">
                ${etat.libelle}
            </option>`;
        });

    }catch(e){
        console.error(e);
    }
}


async function loadStats(){
    try{
        const response =
        await fetch(API_BASE_URL+'?action=stats');
        const result =
        await response.json();
        if(!result.success) return;
        const stats=result.data;
        document.getElementById('statTotal').textContent =
            stats.total ?? 0;
        document.getElementById('statEnAttente').textContent =
            stats.en_attente ?? 0;
        document.getElementById('statApprouvees').textContent =
            stats.approuvees ?? 0;
        document.getElementById('statRejetees').textContent =
            stats.rejetees ?? 0;

    }catch(e){
        console.error(e);
    }
}
function escapeHtml(text) {
    if (text === null || text === undefined) {
        return "";
    }

    return String(text)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
function showToast(message, type = "success") {
    alert(message);
}
function showLoading(show) {
    const loading = document.querySelector('.loading');

    if (!loading) return;

    if (show) {
        loading.classList.add('active');
    } else {
        loading.classList.remove('active');
    }
}
async function loadDemandes() {
    showLoading(true);
    const params = new URLSearchParams({
        id: document.getElementById('searchId').value,
        libelle: document.getElementById('searchLibelle').value,
        professeur_id: document.getElementById('searchProfesseur').value,
        type_document_id: document.getElementById('searchTypeDocument').value,
        etat_demande_document_id: document.getElementById('searchEtat').value,
        date_soumission_debut: document.getElementById('searchDateDebut').value,
        date_soumission_fin: document.getElementById('searchDateFin').value,
        page: currentPage,
        per_page: perPage
    });

    try {
        const response =
            await fetch(API_BASE_URL + '?action=search&' + params);
        const result = await response.json();
        showLoading(false);
        if (!result.success) {
            showToast(result.message, 'error');
            return;
        }

        renderTable(result.data.data);
        renderPagination(result.data);
    }

    catch (e) {
        showLoading(false);
        console.error(e);
        showToast("Erreur serveur", "error");
    }
}
function formatDate(date) {

    if (!date) return "-";

    return new Date(date).toLocaleDateString("fr-FR");

}

function renderTable(data) {
    const tbody = document.getElementById("tableBody");
    if (!data || data.length === 0) {
        tbody.innerHTML = `
        <tr>
            <td colspan="8" class="text-center">
                Aucune donnée trouvée
            </td>
        </tr>
        `;
        return;
    }

    tbody.innerHTML = "";
    data.forEach(d => {
        tbody.innerHTML += `

<tr>
<td>${d.id}</td>
<td>${escapeHtml(d.libelle)}</td>
<td>
${escapeHtml(d.professeur_nom ?? '')}
${escapeHtml(d.professeur_prenom ?? '')}
</td>
<td>
${escapeHtml(d.type_document_libelle ?? '')}
</td>
<td>
${getEtatBadge(d.etat_demande_libelle)}
</td>
<td>
${formatDate(d.date_soumission)}
</td>
<td>
${d.date_reponse
    ? formatDate(d.date_reponse)
    : '-'}
</td>
<td>

<button
class="btn btn-info btn-sm"
onclick="viewDetail(${d.id})">
<i class="fas fa-eye"></i>
</button>
<button
class="btn btn-warning btn-sm"
onclick="openEditModal(${d.id})">
<i class="fas fa-edit"></i>
</button>
<button
class="btn btn-danger btn-sm"
onclick="deleteDemande(${d.id})">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
`;
    });
}

function getEtatBadge(libelle) {
    if (!libelle) return "-";
    let couleur = "secondary";
    const txt = libelle.toLowerCase();
    if (txt.includes("attente"))
        couleur = "warning";
    else if (txt.includes("cours"))
        couleur = "info";
    else if (txt.includes("appr"))
        couleur = "success";
    else if (txt.includes("rejet"))
        couleur = "danger";
    else if (txt.includes("revision"))
        couleur = "primary";
    return `
<span class="badge bg-${couleur}">
${escapeHtml(libelle)}
</span>
`;
}

function renderPagination(data) {
    totalPages = data.totalPages;
    document.getElementById("paginationInfo").textContent =
        `Affichage de ${data.total} résultat(s)`;
    document.getElementById("prevBtn").disabled =
        currentPage <= 1;
    document.getElementById("nextBtn").disabled =
        currentPage >= totalPages;
    const pages =
        document.getElementById("pageNumbers");
    pages.innerHTML = "";
    for (let i = 1; i <= totalPages; i++) {
        pages.innerHTML += `
<button
onclick="goToPage(${i})"
class="${i===currentPage?'active':''}">
${i}
</button>
`;
    }
}

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

function changePage(direction){
    if(direction==="prev" && currentPage>1){
        currentPage--;
    }
    if(direction==="next" && currentPage<totalPages){
        currentPage++;
    }
    loadDemandes();
}
// =====================================
// AJOUT
// =====================================

function openCreateModal() {

    editMode = false;

    document.getElementById("modalTitle").textContent =
        "Nouvelle Demande";

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

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

    document.getElementById("date_soumission").value =
        new Date().toISOString().split("T")[0];

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

}
function closeModal() {
    document.getElementById("formModal").classList.remove("active");
    document.getElementById("demandeForm").reset();
    editMode = false;
}

function closeDetailModal() {
    document.getElementById("detailModal").classList.remove("active");
}
// =====================================
// MODIFIER
// =====================================

async function openEditModal(id){

    editMode = true;

    document.getElementById("modalTitle").textContent =
        "Modifier Demande";

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

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

    try{

        const response =
            await fetch(API_BASE_URL+"?action=get&id="+id);

        const result =
            await response.json();

        if(!result.success){

            showToast(result.message,"error");

            return;

        }

        const d = result.data;

        document.getElementById("libelle").value =
            d.libelle ?? "";

        document.getElementById("description").value =
            d.description ?? "";

        document.getElementById("professeur_id").value =
            d.professeur_id ?? "";

        document.getElementById("type_document_id").value =
            d.type_document_id ?? "";

        document.getElementById("etat_demande_document_id").value =
            d.etat_demande_document_id ?? "";

        document.getElementById("date_soumission").value =
            d.date_soumission ?? "";

        document.getElementById("date_reponse").value =
            d.date_reponse ?? "";

    }

    catch(e){

        console.error(e);

        showToast("Erreur serveur","error");

    }

}

// =====================================
// DETAIL
// =====================================

async function viewDetail(id){

    currentDetailId = id;

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

    document.getElementById("detailContent").innerHTML =
        "<p>Chargement...</p>";

    try{

        const response =
            await fetch(API_BASE_URL+"?action=get&id="+id);

        const result =
            await response.json();

        if(!result.success){

            showToast(result.message,"error");

            return;

        }

        renderDetail(result.data);

    }

    catch(e){

        console.error(e);

        showToast("Erreur serveur","error");

    }

}

// =====================================
// AFFICHAGE DETAIL
// =====================================

function renderDetail(d){

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

<div class="detail-grid">

<div class="detail-item">
<strong>ID</strong><br>
${d.id}
</div>

<div class="detail-item">
<strong>Libellé</strong><br>
${escapeHtml(d.libelle)}
</div>

<div class="detail-item">
<strong>Professeur</strong><br>
${escapeHtml(d.professeur_nom ?? "")}
${escapeHtml(d.professeur_prenom ?? "")}
</div>

<div class="detail-item">
<strong>Type document</strong><br>
${escapeHtml(d.type_document_libelle ?? "")}
</div>

<div class="detail-item">
<strong>Etat</strong><br>
${getEtatBadge(d.etat_demande_libelle)}
</div>

<div class="detail-item">
<strong>Date soumission</strong><br>
${formatDate(d.date_soumission)}
</div>

<div class="detail-item">
<strong>Date réponse</strong><br>
${d.date_reponse
?formatDate(d.date_reponse)
:"-"}
</div>

<div class="detail-item">
<strong>Description</strong><br>
${escapeHtml(d.description ?? "-")}
</div>

</div>

`;
    document.getElementById("editFromDetailBtn")
        .style.display="inline-block";
}

function editFromDetail(){
    closeDetailModal();
    openEditModal(currentDetailId);
}

function closeDetailModal(){
    document.getElementById("detailModal")
        .classList.remove("active");
}
async function deleteDemande(id) {

    if (!confirm("Voulez-vous vraiment supprimer cette demande ?")) {
        return;
    }

    try {

        const response = await fetch(API_BASE_URL, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: new URLSearchParams({
                action: "delete",
                id: id
            })
        });

        const result = await response.json();

        if (result.success) {

            showToast("Suppression effectuée", "success");

            loadDemandes();

            loadStats();

        } else {

            showToast(result.message, "error");

        }

    } catch (e) {

        console.error(e);

        showToast("Erreur serveur", "error");

    }
}
async function exportDemandes() {

    try {

        window.open(
            API_BASE_URL + "?action=export",
            "_blank"
        );

    } catch (e) {

        console.error(e);

        showToast("Erreur lors de l'export", "error");

    }

}
async function saveDemande() {
    const data = {
        action: editMode ? "update" : "create", // إضافة الـ action هنا
        libelle: document.getElementById("libelle").value,
        description: document.getElementById("description").value,
        professeur_id: document.getElementById("professeur_id").value,
        type_document_id: document.getElementById("type_document_id").value,
        etat_demande_document_id: document.getElementById("etat_demande_document_id").value,
        date_soumission: document.getElementById("date_soumission").value,
        date_reponse: document.getElementById("date_reponse").value
    };

    if (editMode) {
        data.id = document.getElementById("demandeId").value;
    }

    try {
        // نرسل دائماً POST إلى نفس العنوان
        const response = await fetch(API_BASE_URL, {
            method: "POST", 
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();

        if (result.success) {

            showToast(
                editMode
                    ? "Modification effectuée"
                    : "Création effectuée",
                "success"
            );

            closeModal();
            loadDemandes();
            loadStats();

        } else {

            showToast(result.message, "error");

        }

    } catch (e) {

        console.error(e);
        showToast("Erreur serveur", "error");

    }
}
