const $ = (element) => document.getElementById(element);
const { Schedule } = calendarjs;

let dateAUtiliser = new Date().toISOString().split('T')[0];
let currentReservationId = null;

const calendrier = Schedule(document.getElementById('planning-reservation'), {
    type: 'weekdays',
    value: dateAUtiliser,
    validRange: ['08:00', '18:00'],
    ondblclick: function(self, event) {
        const modal = new bootstrap.Modal($("modalDetailReservation"));
        modal.show();
        fetch (`/gestion-salle/revervation/details/${event.guid}`)
        .then(response => response.json())
        .then(data => {
            currentReservationId = data.id_reservation;
            console.log(data);
            $("id_reservation_detail").value = data.id_reservation;
            $("id_reservation_refus").value = data.id_reservation;
            $("id_reservation_zoom").value = data.id_reservation;
            $("employe").value=data.employe;
            $("salle").value=data.salle;
            $("statut-reservation").innerHTML=data.statut;
            $("date_evenement").value=data.date_evenement;
            $("heure_debut").value=data.heure_debut;
            $("heure_fin").value=data.heure_fin;
            $("motif_reservation").value=data.motif_reservation;
            $("besoin_zoom").checked=data.besoin_zoom;
            $("besoin_ordinateur").checked=data.besoin_ordinateur;
            $("lien_zoom").value=data.lien_zoom;

            if(data.statut !== "annulee"){
                $("motif_refus_container").className = "d-none";
            }else{
                $("motif_refus").value=data.motif_refus;
            }
        })
    }
});

$("modalReservation").addEventListener('shown.bs.modal', (e) => {
    $("id_salle").value = $("liste-salle").value;
})

$('semaineDate').addEventListener('change', () => {
    calendrier.value = $('semaineDate').value;
    calendrier.render();
})

evenement_defini = null

$("liste-salle").addEventListener("change", (e) => {
    if(evenement_defini === null){
        evenement_defini = calendrier.getData();
    }
    evenements = evenement_defini;
    evenement_filtrer = evenements.filter((evenement) => {
        if(evenement.title == $("liste-salle").value){
            return evenement
        }
    })
    calendrier.setData(evenement_filtrer);
})

function chargement_evenement(){
    const url = $("planning-reservation").dataset.url;
    fetch (url)
    .then(response => response.json())
    .then(data => {
        calendrier.setData(data);
    })
}

document.addEventListener("DOMContentLoaded", function () {
    chargement_evenement()
})

$("bouton-annuler").addEventListener("click", (e) => {
    const csrf = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const url_annuler = $("formulaire-details").dataset.urlannuler;

    fetch(
        url_annuler,
        {
            method: "POST",
            headers: {
                "X-Requested-With": "XMTHttpRequest",
                "X-CSRFToken": csrf
            },
            body: new FormData($("formulaire-details"))
        }
    )
    .then(response => response.json())
    .then(data => console.log(data))
})

if($("bouton-valider")){
    $("bouton-valider").addEventListener("click", (e) => {
        const csrf = document.querySelector("[name=csrfmiddlewaretoken]").value;
        const urlvalider = $("formulaire-details").dataset.urlvalider;

        fetch(
            urlvalider,
            {
                method: "POST",
                headers: {
                    "X-Requested-With": "XMTHttpRequest",
                    "X-CSRFToken": csrf
                },
                body: new FormData($("formulaire-details"))
            }
        )
        .then(response => response.json())
        .then(data => console.log(data))
    })
}

if($("ajoutZoom")){
    $("ajoutZoom").addEventListener("click", (e) => {
        e.preventDefault();
        bootstrap.Modal.getOrCreateInstance($("modalDetailReservation")).hide();
        new bootstrap.Modal($("modalZoom")).show();
    })
}

if($("refuserReservation")){
    $("refuserReservation").addEventListener("click", (e) => {
        const csrf = document.querySelector("[name=csrfmiddlewaretoken]").value;
        const url = e.currentTarget.dataset.lienrefus; 
        const idRes = $("id_reservation_detail").value;

        fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRFToken": csrf
            },
            body: JSON.stringify({ "id_reservation": idRes })
        })
        .then(response => response.json())
        .then(data => alert(data.message))
        .catch(error => console.error("Erreur:", error));
    });
}

const tableau_reservation_attente = new Tabulator("#tableau-reservation-attente", {
    columns: [
        {title: "Employé", field: "employe"},
        {title: "Salle", field: "salle"},
        {title: "Date de l'evenement", field: "date_debut"},
        {title: "Heure de début", field: "heure_debut"},
        {title: "Heure de fin", field: "heure_fin"},
        {title: "Motif de reservation", field: "motif_reservation"},
    ],
    placeholder: "Aucune reservation en attente.",
    ajaxURL : $("tableau-reservation-attente").dataset.reservationattentes
})

tableau_reservation_attente.on("rowClick", (row, rowData) => {
    const data = rowData.getData();

    console.log(data);

    if(data.besoin_zoom === false){
        $("lien_zoom_container").className = 'd-none';
    }

    if(data.statut !== "refusee"){
        $("motif_refus_container").className = 'd-none';
    }

    $("id_reservation_detail").value = data.id;
    $("id_reservation_refus").value = data.id;
    $("id_reservation_zoom").value = data.id;

    $("employe").value=data.employe;
    $("salle").value=data.salle;
    $("statut-reservation").innerHTML=data.statut;
    $("date_evenement").value=data.date_debut;
    $("heure_debut").value=data.heure_debut;
    $("heure_fin").value=data.heure_fin;
    $("motif_reservation").value=data.motif_reservation;
    $("besoin_zoom").checked=data.besoin_zoom;
    $("besoin_ordinateur").checked=data.besoin_ordi;
    $("lien_zoom").value=data.lien_zoom;
    $("motif_refus").value=data.motif_refus;

    const modal = new bootstrap.Modal($("modalDetailReservation"));
    bootstrap.Modal.getOrCreateInstance($("modalReservationAttente")).hide();
    modal.show();
})
