const $ = (element) => document.getElementById(element);

const url_liste_employe = $("tableau_liste_employe").dataset.url;
const tableau_liste_employe = new Tabulator("#tableau_liste_employe", {
    columns: [
        {"title": "Matricule", "field": "matricule"},
        {"title": "Nom & Prénom", "field": "employe"},
        {"title": "Fonction", "field": "fonction"},
        {"title": "Projet", "field": "projet"},
        {"title": "Téléphone", "field": "telephone"},
    ],
    // ajaxURL: url_liste_employe,
    pagination: true,
    paginationSize: 10,
    responsiveLayout : "hide"
})

fetch(url_liste_employe)
    .then(response => response.json())
    .then(data => {
            if (data.success){
                console.log(data.data)
                tableau_liste_employe.setData(data.data);
            }else{
                alert(data.message);
            }
        }
    )

tableau_liste_employe.on("rowClick", function (row, rowData) {
    const data = rowData.getData(); 
    document.getElementById('detail-id').value = data.id;
    document.getElementById('detail-matricule').value = data.matricule;
    document.getElementById('detail-employe').value = data.employe;
    document.getElementById('detail-fonction').value = data.fonction;
    document.getElementById('detail-departement').value = data.departement;
    document.getElementById('detail-sexe').value = "";
    document.getElementById('detail-dateNaissance').value = "";
    document.getElementById('detail-email').value = data.email;
    document.getElementById('detail-telephone').value = data.telephone;
    document.getElementById('detail-adresse').value = data.adresse;
    document.getElementById('detail-dateEmbauche').value = data.date_embauche;
    document.getElementById('detail-dateNaissance').value = data.date_naissance;
    document.getElementById('detail-sexe').value = data.sexe;

    document.getElementById('document-diplome').href = data.diplome;
    document.getElementById('document-diplome').textContent = data.diplome || "Aucun diplôme";
    document.getElementById('document-cv').href = data.CV;
    document.getElementById('document-cv').textContent = data.CV || "Aucun CV";
    document.getElementById('document-rib').href = data.rib;
    document.getElementById('document-rib').textContent = data.rib || "Aucun RIB";
    document.getElementById('document-casier-judiciaire').href = data.casier_judiciaire;
    document.getElementById('document-casier-judiciaire').textContent = data.casier_judiciaire || "Aucun casier judiciaire";

    document.getElementById("document-employe").innerHTML = data.employe || "Employé inconnu";

    document.getElementById("formations-list").innerHTML = "";
    for (const formation of data.formations) {
        document.getElementById("formations-list").innerHTML += `
        <div class="col-6">
            <div class="form-group mb-2">
                <label>Titre :</label>
                <input type="text" class="form-control" value="${formation.titre}">
            </div>
            <div class="form-group mb-2">
                <label>Organisme :</label>
                <input type="text" class="form-control" value="${formation.organisme}">
            </div>
            <div class="form-group mb-2">
                <label>Date d'Optention :</label>
                <input type="text" class="form-control" value="${formation.date_obtention}">
            </div>
            <div class="form-group mb-2">
                <label>Date de validitée :</label>
                <input type="text" class="form-control" value="${formation.date_fin}">
            </div>
        </div>
        `
    }
    document.getElementById("contrat-employe").innerHTML = data.employe || "Employé inconnu";
    document.getElementById("employeIdInput").value = data.id;

    document.getElementById("contrats-list").innerHTML = "";
    for (const contrat of data.contrats) {
        document.getElementById("contrats-list").innerHTML += `
        <div class="col-6">
            <div class="form-group mb-2">
                <label>Numéro de contrat :</label>
                <input type="text" class="form-control" value="${contrat.numero_contrat}">
            </div>
            <div class="form-group mb-2">
                <label>Type de contrat :</label>
                <select class="form-select">
                    <option value="">Sélectionnez un projet</option>
                    <option value="contrat_duree_determinee" ${contrat.type_contrat == 'contrat_duree_determinee' ? 'selected' : ''}>Contrat à Durée Déterminée</option>
                    <option value="contrat_duree_indeterminee" ${contrat.type_contrat == 'contrat_duree_indeterminee' ? 'selected' : ''}>Contrat à Durée Indéterminée</option>
                    <option value="contrat_prestation" ${contrat.type_contrat == 'contrat_prestation' ? 'selected' : ''}>Contrat de Prestation de Service</option>
                    <option value="contrat_stage" ${contrat.type_contrat == 'contrat_stage' ? 'selected' : ''}>Contrat de Stage</option>
                </select>
            </div>
            <div class="form-group mb-2">
                <label>Date de début :</label>
                <input type="text" class="form-control" value="${contrat.date_debut}">
            </div>
            <div class="form-group mb-2">
                <label>Date de fin :</label>
                <input type="text" class="form-control" value="${contrat.date_fin}">
            </div>
            <div class="form-group mb-2">
                <label>Salaire mensuel :</label>
                <input type="text" class="form-control" value="${contrat.salaire_mensuel}">
            </div>
            <div class="form-group mb-2">
                <label>Statut :</label>
                <input type="text" class="form-control" value="${contrat.statut}">
            </div>
            <div class="form-group mb-2">
                <label>Fichier de contrat :</label>
                <a href="${contrat.fichier_contrat}" target="_blank">Voir le document</a>
            </div>
            <button class='d-block m-auto btn btn-danger btn-supprimer-contrat' data-contratid="${contrat.numero_contrat}">
                <i class='bi bi-trash'></i> Supprimer le contrat
            </button>
        </div>
        `
    };

    const supprimerButtons = document.getElementsByClassName("btn-supprimer-contrat");
    Array.from(supprimerButtons).forEach(button => {
        button.addEventListener("click", function() {
            const contratId = this.dataset.contratid;
            fetch(`contrat/supprimer/`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({
                    "id": contratId
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                location.reload();
            })
        });
    })

    document.getElementById("affectation-nom-employe").textContent = data.employe || "Employé inconnu";
    document.getElementById("affecter_employe_id").value = data.id;

    document.getElementById("affectations-list").innerHTML = "";
    for (const affectation of data.affectations) {
        document.getElementById("affectations-list").innerHTML += `
        <div class="col-6">
            <div class="form-group mb-2">
                <label>Nom du projet :</label>
                <input type="text" class="form-control" value="${affectation.projet}">
            </div>
            <div class="form-group mb-2">
                <label>Rôle :</label>
                <input type="text" class="form-control" value="${affectation.role}">
            </div>
            <div class="form-group mb-2">
                <label>Pourcentation d'affectation :</label>
                <input type="text" class="form-control" value="${affectation.pourcentage_temps_affectation}">
            </div>
            <div class="form-group mb-2">
                <label>Date d'affectation :</label>
                <input type="date" class="form-control" value="${affectation.date_affectation}">
            </div>
            <div class="form-group mb-2">
                <label>Date de fin d'affectation :</label>
                <input type="date" class="form-control" value="${affectation.date_fin_daffectation}">
            </div>
            <button class='d-block m-auto btn btn-danger btn-supprimer-affectation' data-contratid="${affectation.id}">
                <i class='bi bi-trash'></i> Supprimer l'affectation
            </button>
        </div>
        `
    }

    Array.from(document.getElementsByClassName("btn-supprimer-affectation")).forEach(button => {
        button.addEventListener("click", function() {
            const affectationId = this.dataset.contratid;
            fetch(`affectation/supprimer/`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({
                    "id": affectationId
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                location.reload();
            })
        });
    })

    const modal = new bootstrap.Modal($("modalDetailEmploye"));
    modal.show();
})

$("enregistrerDetail").addEventListener("click", function() {
    const id_ = document.getElementById('detail-id').value;
    const fonction = document.getElementById('detail-fonction').value;
    const dateEmbauche = document.getElementById('detail-dateEmbauche').value;
    const matricule = document.getElementById('detail-matricule').value;

    const url_enregistrer_detail = $("modalDetailEmployeBody").dataset.url;
    fetch(url_enregistrer_detail, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify({
            "id": id_,
            "fonction": fonction,
            "date_embauche": dateEmbauche,
            "matricule": matricule
        })
    })
    .then(response => response.json())
    .then(data => {
        alert(data.message);
        location.reload();
    })
});

$("input-recherche").addEventListener("input", function() {
    const recherche = this.value;
    if (recherche){
        tableau_liste_employe.setFilter("employe", "like", recherche);
    }else{
        tableau_liste_employe.clearFilter();
    }
})

const listeContratExpirant = new Tabulator("#listeContratExpirant", {
    columns: [
        {"title": "Employé", "field": "employe"},
        {"title": "Type de contrat", "field": "type_contrat"},
        {"title": "Date de début", "field": "date_debut", formatter: 'datetime', formatterParams:{
            inputFormat:"yyyy-MM-dd",
            outputFormat:"dd/MM/yy",
        }},
        {"title": "Date de fin", "field": "date_fin", formatter: 'datetime', formatterParams:{
            inputFormat:"yyyy-MM-dd",
            outputFormat:"dd/MM/yy",
        }},
        {"title": "Statut", "field": "statut"},
        {"title": "Lien du fichier", "field": "fichier_contrat", formatter:"link", formatterParams:{
                target:"_blank",
            }
        },
    ],
    ajaxURL: $("boutonContratExpirants").dataset.urlexpirants,
})