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

const url_liste_activite = $("tableau-liste-activite").dataset.urllisteactivite
const tableau_liste_activite = new Tabulator("#tableau-liste-activite", {
    columns: [
        {title: "Activité", field: "titre"},
        {title: "Date début", field: "date_debut"},
        {title: "Date fin", field: "date_fin"},
        {title: "Budget prévu", field: "budget_prevu"},
        {title: "Budget dépensé", field: "budget_depense"},
        {title: "Motif de changement de budget", field: "motif_changement_budget"},
        {title: "Statut", field: "statut"},
    ],
    ajaxURL: url_liste_activite,
})
tableau_liste_activite.on("rowClick", function (row, rowData) {
    const data = rowData.getData();   
    $("idDetailActivite").value = data.id;
    $("titreDetailActivite").value = data.titre;
    $("descriptionDetailActivite").value = data.description;
    $("date_debutDetailActivite").value = data.date_debut;
    $("date_finDetailActivite").value = data.date_fin;
    $("statutDetailActivite").value = data.statut;
    $("budget_prevuDetailActivite").value = data.budget_prevu;
    $("besoin_ressources_materiellesDetailActivite").value = data.besoin_ressource_materielle;
    const modal = new bootstrap.Modal($("modalDetailActivite"));
    modal.show();

    fetch(`liste-des-livrables/${data.id}/`)
        .then(response => response.json())
        .then(livrables => {
            tableau_liste_livrable.setData(livrables);
        })
})

const tableau_liste_livrable = new Tabulator("#listeLivrables", {
    columns: [
        {title: "Livrable", field: "titre"},
        {title: "Lien du livrable", field: "lien", formatter: "link", formatterParams: {blank: true}},
    ],
    placeholder: "Aucun livrable trouvé",
})

$("btnMiseAJourDepense").addEventListener("click", function() {
    const modal = new bootstrap.Modal($("modalDepenseActivite"));
    bootstrap.Modal.getOrCreateInstance($("modalDetailActivite")).hide();
    const idActivite = $("idDetailActivite").value;
    const budgetPrevu = $("budget_prevuDetailActivite").value;

    $("id_activite_depense").value = idActivite;
    $("budget_prevu").value = budgetPrevu;
    modal.show();
})

$("btnAnnulerActivite").addEventListener("click", function(event) {
    new bootstrap.Modal($("modalAnnulerActivite")).show();
    $("id_activite_annulation").value = $("idDetailActivite").value;
    bootstrap.Modal.getOrCreateInstance($("modalDetailActivite")).hide();
})