// ========================================
// CONFIGURATION
// ========================================

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

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

let editMode = false;

let professorsList = [];
let membersList = [];
let detailsList = [];
let typesDiplomeList = [];

// ========================================
// INITIALISATION
// ========================================

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

    loadConcours();

    loadStats();

    loadProfessors();

    loadTypesDiplome();

    setupSearchForm();

});

// ========================================
// RECHERCHE
// ========================================

function setupSearchForm() {

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

            e.preventDefault();

            currentPage = 1;

            loadConcours();

        });

}

function resetSearch() {

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

    currentPage = 1;

    loadConcours();

}
// ========================================
// STATISTIQUES
// ========================================
function openCreateModal(){

    editMode=false;


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


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


    switchTab("info");


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

}
function loadStats() {

    fetch(API_BASE_URL + '?action=stats')

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

        .then(result => {

            if (!result.success) return;

            const s = result.data;

            document.getElementById('statTotal').textContent = s.total || 0;
            document.getElementById('statOuvert').textContent = s.ouvert || 0;
            document.getElementById('statEnCours').textContent = s.en_cours || 0;
            document.getElementById('statTermine').textContent = s.termine || 0;

        });

}

// ========================================
// EMPLOYEES
// ========================================

function loadProfessors() {

    fetch(API_BASE_URL + '?action=professors')

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

        .then(result => {

            if (!result.success) return;

            professorsList = result.data;
            populateChefSelect();
            populateMembersSelect();

        });

}
function populateChefSelect() {

    const select = document.getElementById("chef_commite_organisation");

    if (!select) return;

    select.innerHTML = '<option value="">Sélectionner</option>';

    professorsList.forEach(emp => {

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

        option.value = emp.id;

        option.textContent = emp.code + " - " + emp.nom + " " + (emp.prenom || "");

        select.appendChild(option);

    });

}
function populateMembersSelect() {

    const select = document.getElementById("memberSelect");

    if (!select) return;

    select.innerHTML =
        '<option value="">Sélectionner un membre</option>';

    professorsList.forEach(emp => {

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

        option.value = emp.id;

        option.textContent =
            emp.code +
            " - " +
            emp.nom +
            " " +
            (emp.prenom || "");

        select.appendChild(option);

    });

}

// ========================================
// TYPES DIPLOME
// ========================================

function loadTypesDiplome() {

    fetch(API_BASE_URL + '?action=types_diplome')

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

        .then(result => {

            if (!result.success) return;

            typesDiplomeList = result.data;

            const select =
                document.getElementById("detail_type_diplome");

            select.innerHTML =
                '<option value="">Sélectionner</option>';

            typesDiplomeList.forEach(type => {

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

                option.value = type.id;

                option.textContent =
                    type.libelle +
                    " (" +
                    type.code +
                    ")";

                option.dataset.code = type.code;
                option.dataset.annee = type.annee_apres_bac;

                select.appendChild(option);

            });

        });

}
// ========================================
// CHARGEMENT DES CONCOURS
// ========================================

function loadConcours() {

    showLoading(true);

    const params = new URLSearchParams({

        code: document.getElementById("searchCode").value,

        label: document.getElementById("searchLabel").value,

        filliere: document.getElementById("searchFilliere").value,

        etat_concours: document.getElementById("searchEtat").value,

        active: document.getElementById("searchActive").value,

        page: currentPage,

        per_page: perPage

    });

    fetch(API_BASE_URL + "?action=search&" + params.toString())

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

        .then(result => {

            showLoading(false);

            if (!result.success) {

                showToast(result.message, "error");

                return;

            }

            renderTable(result.data.data);

            renderPagination(result.data);

        })

        .catch(error => {

            showLoading(false);

            console.error(error);

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

        });

}

// ========================================
// TABLE
// ========================================

function renderTable(concours) {

    const tbody = document.getElementById("tableBody");

    if (concours.length === 0) {

        tbody.innerHTML = `
            <tr>
                <td colspan="9" style="text-align:center">
                    Aucun concours trouvé
                </td>
            </tr>
        `;

        return;

    }

    tbody.innerHTML = concours.map(item => `

        <tr>

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

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

            <td>${escapeHtml(item.label)}</td>

            <td>${escapeHtml(item.filliere || "")}</td>

            <td>${formatDate(item.date_lancement)}</td>

            <td>${formatDate(item.date_fin)}</td>

            <td>${item.etat_concours}</td>

            <td>

                ${item.active
                    ? '<span class="badge badge-success">Actif</span>'
                    : '<span class="badge badge-danger">Inactif</span>'
                }

            </td>

            <td>

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

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

                </button>

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

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

                </button>

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

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

                </button>

            </td>

        </tr>

    `).join("");

}

// ========================================
// PAGINATION
// ========================================

function renderPagination(data) {

    totalPages = data.totalPages;

    document.getElementById("paginationInfo").textContent =

        `Affichage de ${data.page}
         sur ${data.totalPages}
         (${data.total})`;

    let html = "";

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

        html += `

            <button

                ${i === data.page ? 'class="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 goToPage(page) {

    currentPage = page;

    loadConcours();

}

function changePage(direction) {

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

        currentPage--;

    }

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

        currentPage++;

    }

    loadConcours();

}

// ========================================
// CREATE
// ========================================

function openCreateModal() {

    editMode = false;

    membersList = [];

    detailsList = [];

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

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

    renderMembers();

    renderDetails();

    switchTab("info");

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

}

// ========================================
// EDIT
// ========================================

function openEditModal(id) {

    editMode = true;

    membersList = [];

    detailsList = [];

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

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

        .then(result => {

            if (!result.success) {

                showToast(result.message, "error");

                return;

            }

            const c = result.data;
            

            document.getElementById("concoursId").value = c.id;

            document.getElementById("code").value = c.code;

            document.getElementById("label").value = c.label;

            document.getElementById("filliere").value = c.filliere;

            document.getElementById("etat_concours").value =
                c.etat_concours;
document.getElementById("date_lancement").value =
    c.date_lancement
        ? c.date_lancement.replace(" ", "T").substring(0,16)
        : "";

document.getElementById("date_fin_inscription").value =
    c.date_fin_inscription
        ? c.date_fin_inscription.replace(" ", "T").substring(0,16)
        : "";
document.getElementById("date_affichage_ecrit").value =
    c.date_affichage_ecrit
        ? c.date_affichage_ecrit.replace(" ", "T").substring(0,16)
        : "";

document.getElementById("date_ecrit").value =
    c.date_ecrit
        ? c.date_ecrit.replace(" ", "T").substring(0,16)
        : "";

document.getElementById("date_affichage_orale").value =
    c.date_affichage_orale
        ? c.date_affichage_orale.replace(" ", "T").substring(0,16)
        : "";

document.getElementById("date_orale").value =
    c.date_orale
        ? c.date_orale.replace(" ", "T").substring(0,16)
        : "";

document.getElementById("date_affichage_resultat").value =
    c.date_affichage_resultat
        ? c.date_affichage_resultat.replace(" ", "T").substring(0,16)
        : "";
            document.getElementById("date_fin").value =
                c.date_fin
                    ? c.date_fin.replace(" ", "T").substring(0,16)
                    : "";

            document.getElementById("active").value =
                c.active;

            document.getElementById("description").value =
                c.description || "";

            membersList =
                c.members
                    ? c.members.map(m => parseInt(m.employee_id))
                    : [];
             document.getElementById("chef_commite_organisation").value =
    c.chef_commite_organisation || "";
            renderMembers();

            detailsList = c.details || [];

            renderDetails();

            switchTab("info");

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

        });

}
// ========================================
// MEMBRES
// ========================================

function addMember() {

    const select = document.getElementById("memberSelect");

    const id = parseInt(select.value);

    if (!id) {

        showToast("Sélectionnez un membre", "warning");

        return;

    }

    if (membersList.includes(id)) {

        showToast("Ce membre existe déjà", "warning");

        return;

    }

    membersList.push(id);

    renderMembers();

    select.value = "";

}

function removeMember(index) {

    membersList.splice(index, 1);

    renderMembers();

}

function renderMembers() {

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

    if (membersList.length === 0) {

        container.innerHTML =
            "<p style='color:#999'>Aucun membre sélectionné</p>";

        return;

    }

    let html = "";

    membersList.forEach((id, index) => {

        const emp =
            professorsList.find(e => parseInt(e.id) === parseInt(id));

        html += `

        <div class="member-item">

            <span>

                ${emp
                    ? emp.code + " - " + emp.nom + " " + (emp.prenom || "")
                    : id}

            </span>

            <button
                class="member-remove"
                onclick="removeMember(${index})">

                &times;

            </button>

        </div>

        `;

    });

    container.innerHTML = html;

}

// ========================================
// DETAILS
// ========================================

function addDetail() {

    const select =
        document.getElementById("detail_type_diplome");

    const typeId =
        parseInt(select.value);

    const pourcentage =
        parseFloat(
            document.getElementById("detail_pourcentage").value
        );

    const description =
        document.getElementById("detail_description").value;

    if (!typeId) {

        showToast("Sélectionnez un type", "warning");

        return;

    }

    if (detailsList.some(d => d.type_diplome_id == typeId)) {

        showToast("Type déjà ajouté", "warning");

        return;

    }

    const option =
        select.options[select.selectedIndex];

    detailsList.push({

        type_diplome_id: typeId,

        type_libelle: option.textContent,

        type_code: option.dataset.code,

        annee_apres_bac: option.dataset.annee,

        pourcentage: pourcentage,

        description: description

    });

    renderDetails();

    select.value = "";

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

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

}

function removeDetail(index) {

    detailsList.splice(index, 1);

    renderDetails();

}

function renderDetails() {

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

    if (detailsList.length === 0) {

        container.innerHTML =
            "<p style='color:#999'>Aucun type sélectionné</p>";

        return;

    }

    let total = 0;

    let html =
        "<table class='details-table'>";

    html += `
    <thead>
    <tr>

        <th>Type</th>

        <th>%</th>

        <th>Action</th>

    </tr>
    </thead>
    <tbody>
    `;

    detailsList.forEach((d, index) => {

        total += Number(d.pourcentage);

        html += `

        <tr>

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

            <td>${d.pourcentage}%</td>

            <td>

                <button

                    class="btn btn-danger btn-sm"

                    onclick="removeDetail(${index})">

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

                </button>

            </td>

        </tr>

        `;

    });

    html += `
    </tbody>

    <tfoot>

    <tr>

        <td>Total</td>

        <td>${total}%</td>

        <td></td>

    </tr>

    </tfoot>

    </table>
    `;

    container.innerHTML = html;

}

// ========================================
// SAVE
// ========================================

function saveConcours() {

    const total =
        detailsList.reduce(
            (sum, d) => sum + Number(d.pourcentage),
            0
        );

    if (total !== 100) {

        showToast(
            "Le total des pourcentages doit être 100%",
            "warning"
        );

        return;

    }

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

    const data = {

        code:
            document.getElementById("code").value,

        label:
            document.getElementById("label").value,

        filliere:
            document.getElementById("filliere").value,

        etat_concours:
            document.getElementById("etat_concours").value,

        date_lancement:
            document.getElementById("date_lancement").value,

        date_fin:
            document.getElementById("date_fin").value,
        date_fin_inscription:
    document.getElementById("date_fin_inscription").value,

date_affichage_ecrit:
    document.getElementById("date_affichage_ecrit").value,

date_ecrit:
    document.getElementById("date_ecrit").value,

date_affichage_orale:
    document.getElementById("date_affichage_orale").value,

date_orale:
    document.getElementById("date_orale").value,

date_affichage_resultat:
    document.getElementById("date_affichage_resultat").value,
        active:
            parseInt(
                document.getElementById("active").value
            ),

        description:
            document.getElementById("description").value,

        members: membersList,
          chef_commite_organisation:
    document.getElementById("chef_commite_organisation").value,
        details: detailsList.map(d => ({

            type_diplome_id: d.type_diplome_id,

            pourcentage: d.pourcentage,

            description: d.description

        }))

    };

    const url =
        id
            ? API_BASE_URL + "?id=" + id
            : API_BASE_URL;

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

    fetch(url, {

        method: method,

        headers: {

            "Content-Type": "application/json"

        },

        body: JSON.stringify(data)

    })

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

    .then(result => {

        if (!result.success) {

            showToast(result.message, "error");

            return;

        }

        showToast(result.message, "success");

        closeModal();

        loadConcours();

        loadStats();

    });

}
// ========================================
// DELETE
// ========================================

function deleteConcours(id) {

    if (!confirm("Supprimer ce concours ?")) return;

    fetch(API_BASE_URL + "?id=" + id, {

        method: "DELETE"

    })

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

    .then(result => {

        if (!result.success) {

            showToast(result.message, "error");

            return;

        }

        showToast(result.message, "success");

        loadConcours();

        loadStats();

    });

}

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

function viewDetail(id) {

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

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

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

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

        .then(result => {

            if (!result.success) {

                document.getElementById("detailContent").innerHTML =
                    result.message;

                return;

            }

            renderDetail(result.data);

        });

}

function renderDetail(data) {

    let members = "";

    if (data.members && data.members.length) {

        members = "<ul>";

        data.members.forEach(m => {

            members += `

                <li>

                    ${m.code}
                    -
                    ${m.nom}
                    ${m.prenom || ""}

                </li>

            `;

        });

        members += "</ul>";

    } else {

        members = "Aucun membre";

    }

    let details = "";

    if (data.details && data.details.length) {

        details = `

        <table class="details-table">

            <thead>

                <tr>

                    <th>Diplôme</th>

                    <th>%</th>

                    <th>Description</th>

                </tr>

            </thead>

            <tbody>

        `;

        data.details.forEach(d => {

            details += `

            <tr>

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

                <td>${d.pourcentage}%</td>

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

            </tr>

            `;

        });

        details += "</tbody></table>";

    }

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

        <h3>${escapeHtml(data.label)}</h3>

        <hr>

        <p>

            <b>Code :</b>

            ${escapeHtml(data.code)}

        </p>

        <p>

            <b>Filière :</b>

            ${escapeHtml(data.filliere)}

        </p>

        <p>

            <b>Etat :</b>

            ${escapeHtml(data.etat_concours)}

        </p>

        <p>

            <b>Date lancement :</b>

            ${formatDate(data.date_lancement)}

        </p>

        <p>

            <b>Date fin :</b>

            ${formatDate(data.date_fin)}

        </p>

        <p>

            <b>Description :</b>

            ${escapeHtml(data.description || "")}

        </p>

        <hr>

        <h4>Membres</h4>

        ${members}

        <hr>

        <h4>Types de diplôme</h4>

        ${details}

    `;

}

// ========================================
// MODAL
// ========================================

function closeModal() {

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

}

function closeDetailModal() {

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

}

// ========================================
// TABS
// ========================================

function switchTab(tab) {

    document.querySelectorAll(".tab-btn")
        .forEach(btn => btn.classList.remove("active"));

    document.querySelectorAll(".tab-content")
        .forEach(c => c.classList.remove("active"));

    document
        .querySelector(`[data-tab="${tab}"]`)
        .classList
        .add("active");

    document
        .getElementById("tab-" + tab)
        .classList
        .add("active");

}

// ========================================
// TOAST
// ========================================

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

    alert(message);

}

// ========================================
// LOADING
// ========================================

function showLoading(show) {

    const loading = document.querySelector(".loading");

    if (!loading) return;

    loading.classList.toggle("active", show);

}

// ========================================
// UTILS
// ========================================

function formatDate(date) {

    if (!date) return "";

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

}

function escapeHtml(text) {

    if (!text) return "";

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

    div.textContent = text;

    return div.innerHTML;

}

// ========================================
// EVENTS
// ========================================

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

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

        closeModal();

        closeDetailModal();

    }

});
