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

const tableau_demande_vehicule = new Tabulator("#tableau-demande-vehicule", {
    columns: [
        {title: "Nom du passager", field: "nom_passager"},
        {title: "Lieu de depart", field: "lieu_depart"},
        {title: "Date et heure de départ", field: "date_heure_depart"},
        {title: "Lieu d'arrivée", field: "lieu_arrivee"},
        {title: "Statut de validation", field: "validation", formatter: "tickCross", formatterParams: {
            allowEmpty: true
        }},
    ],
    ajaxURL: `${$("tableau-demande-vehicule").dataset.url}`,
    pagination: true,
    paginationSize: 8
})

function valider(statut) {
    if(statut == "valider"){
        $("affichage-formulaire").style.display = "block";
        $("refus").style.display = "none";
    }else if(statut == "refuser"){
        $("affichage-formulaire").style.display = "none";
        $("refus").style.display = "block";
    }
}

$("radioValider").addEventListener("input", function () {
    valider("valider");
})

$("radioRefuser").addEventListener("input", function () {
    valider("refuser");
})

tableau_demande_vehicule.on("rowClick", function (row, rowData) {
    const data = rowData.getData();    
    const modal = new bootstrap.Modal($("confirmerDemandeModal"));
    
    $("id-demande").value = data.id_demande;
    $("nom-passager").value = data.nom_passager;
    $("lieu-depart").value = data.lieu_depart;
    $("lieu-arrivee").value = data.lieu_arrivee;
    $("date-heure-depart").value = data.date_heure_depart;

    chauffeur_champs = $("chauffeur");
    chauffeur_champs.innerHTML = "";

    data.chauffeurs.forEach(chauffeur => {
        const option = document.createElement("option");
        option.value = chauffeur.chauffeur_id;
        option.text = chauffeur.chauffeur_name;
        chauffeur_champs.appendChild(option);
    });

    $("radioValider").disabled = false;
    $("radioValider").checked = false;
    $("radioRefuser").disabled = false;
    $("radioRefuser").checked = false;
    // $("courseTermine").disabled = false;
    // $("courseTermine").checked = false;
    $("motif-refus").textContent = "";

    if(data.validation == true){
        $("radioValider").checked = true;
        $("radioValider").disabled  = true;
        $("radioRefuser").disabled  = true;
        valider("valider");

        if(data.course_terminer){
            $("courseTermine").checked = true;
            $("courseTermine").disabled = true;
            $("date_heure_retour").value = data.heure_course_termine;
            $("demanderValiderEnregistrer").disabled = true;
        }
    }else if (data.validation == false){
        valider("refuser");
        // $("radioRefuser").disabled  = true;
        $("radioValider").disabled  = true;
        $("radioRefuser").checked = true;

        $("demanderValiderEnregistrer").disabled = true;

        $("motif-refus").textContent = data.motif_refus;
        $("motif-refus").style.disabled = true;
    }else{
        $("affichage-formulaire").style.display = "none";
        $("refus").style.display = "none";
        $("radioValider").checked = false;
        $("radioRefuser").checked = false;
    }

    const vehiculeHTML = $("vehicule");
    vehiculeHTML.innerHTML = "";

    data.vehicule.forEach(vehicule => {
        const option = document.createElement("option");
        option.value = vehicule.id;
        option.textContent = vehicule.immatriculation;
        vehiculeHTML.appendChild(option);
    });

    $("validation-sortie-footer").style.display = "none";

    if(data.is_logisticien){
        $("validation-sortie-footer").style.display = "";
    }

    if(data.validation & (data.is_logisticien | data.is_chauffeur)){
        location.href = `detail-course/${data.id_demande}`
    }else{
        modal.show();
    }
})

$("filtreStatutDemande").addEventListener("change", function () {
    option_filtre = this.value;
    if(option_filtre === "valider"){
        tableau_demande_vehicule.setFilter("validation", '=', true);
    }else if(option_filtre === "refuser"){
        tableau_demande_vehicule.setFilter("validation", '=', false);
    }else if(option_filtre === "attente"){
        tableau_demande_vehicule.setFilter("validation", '=', null);
    }else if(option_filtre === "terminer"){
        tableau_demande_vehicule.setFilter("course_terminer", '=', true);
    }else if(option_filtre === "mes_demandes"){
        tableau_demande_vehicule.setFilter("user_id", "=", $("tableau-demande-vehicule").dataset.userid)
    }
    else{
        tableau_demande_vehicule.clearFilter();
    }
})

$("enregistrer-demande-form").addEventListener("submit", function (e) {
    e.preventDefault();

    const url = this.dataset.url;
    const form = this;

    fetch(
        url,
        {
            method: "POST",
            headers: {
                "X-Requested-With": "XMTHttpRequest"
            },
            body: new FormData(form)
        }
    )
    .then(response => response.json())
    .then(data => {
        const messageZone = $("messageZone");
        if(data.success){
            messageZone.innerHTML = `
            <div class="alert alert-success">
                ${data.message}
            </div>
          `;
          form.reset();
        }
    })
})

$("enregistrerDemandeModal").addEventListener("hidden.bs.modal", function () {
    location.reload();
})