var BookingPlugin = function () {};

/**
 * Initialisation du plugin (appelé par Plugin.Register)
 */
BookingPlugin.Init = function () {

    var container = Dom.GetById("bookingPluginContainer");
    if (!container) return;

    BookingPlugin.EntityName = container.getAttribute("data-entity-name");
    BookingPlugin.EntityId   = container.getAttribute("data-entity-id");
    BookingPlugin.SelectedSlot = null;

    Event.AddByClass("openingTime", "click", BookingPlugin.OnReserveDate);
};


BookingPlugin.OnReserveDate = function(e){
 
    let id = e.srcElement.id.split("|");
    let dateStart = id[0];
    let hourStart = id[1];
      

   console.log(e.srcElement.id); 
  //  console.log( BookingPlugin.EntityName);
  //console.log( BookingPlugin.EntityId);


  Dialog.open('', {"title": Language.GetCode("Booking.ReserveDate"),
        "html": "<div id='BookingPluginDialog'></div>",
    });

    
    Plugin.SendRequest({"plugin": "BookingPlugin",
        "method": "OpenReserveDate",
        "EntityName": BookingPlugin.EntityName,
        "EntityId": BookingPlugin.EntityId,
        "DateStart" : dateStart,
        "HourStart" : hourStart
    }
    , (data) => {
        Animation.Load("BookingPluginDialog", data);

        Dialog.Reposition();

        Event.AddById("btnSendBookingForm", "click", BookingPlugin.SendResevation);

    });
};


/**
 * Soumission du formulaire de réservation
 */
BookingPlugin.SendResevation = function () {
 
    if (Form.IsValid("reservationForm")) {
        Animation.AddLoading("reservationForm");

        var request = new Http("Booking", "SaveReservation");
        request.SetData(Form.Serialize("reservationForm"));
        
        request.Post(function (data) {
        
      
          if (data.status === "error") {
                Animation.RemoveLoading("reservationForm");
                Form.RenderError("BookingPluginFormForm", data.data.Message);
            } else {
                Animation.RemoveLoading("reservationForm");
                // Masquer le formulaire et afficher un message de confirmation
                Dialog.Close();
                Animation.Notify(Language.GetCode("Booking.ReservationRecevied"));
            }
        });
    }
};



/**
 * Quand le type change : afficher le sélecteur de date
 */
BookingPlugin.OnTypeChange = function (typeId) {
    if (!typeId) return;

    BookingPlugin.TypeId = typeId;
    BookingPlugin.SelectedSlot = null;

    // Réinitialiser les étapes suivantes
    var stepSlots = Dom.GetById("stepSlots");
    var stepForm  = Dom.GetById("stepForm");
    if (stepSlots) stepSlots.style.display = "none";
    if (stepForm)  stepForm.style.display  = "none";

    // Calculer la date minimum = aujourd'hui
    var today = new Date();
    var yyyy  = today.getFullYear();
    var mm    = String(today.getMonth() + 1).padStart(2, "0");
    var dd    = String(today.getDate()).padStart(2, "0");

    var datePicker = Dom.GetById("bookingDatePicker");
    if (datePicker) {
        datePicker.min   = yyyy + "-" + mm + "-" + dd;
        datePicker.value = "";
    }

    Animation.Show("stepDate");
};

/**
 * Quand la date change : charger les créneaux disponibles via AJAX
 */
BookingPlugin.OnDateChange = function (date) {
    if (!date || !BookingPlugin.TypeId) return;

    BookingPlugin.SelectedDate = date;
    BookingPlugin.SelectedSlot = null;

    var slotsContainer = Dom.GetById("bookingSlots");
    if (slotsContainer) {
        slotsContainer.innerHTML = "<p>" + Language.GetCode("Booking.LoadingSlots") + "</p>";
    }

    Animation.Show("stepSlots");

    var request = new Http("Booking", "GetAvailableSlots");
    request.Add("TypeId",     BookingPlugin.TypeId);
    request.Add("Date",       date);
    request.Add("EntityName", BookingPlugin.EntityName);
    request.Add("EntityId",   BookingPlugin.EntityId);

    request.Post(function (data) {
        data = JSON.parse(data);

        if (data.status === "success") {
            BookingPlugin.RenderSlots(data.data.Slots);
        } else {
            if (slotsContainer) {
                slotsContainer.innerHTML = "<p class='text-danger'>" + Language.GetCode("Booking.ErrorLoadingSlots") + "</p>";
            }
        }
    });
};

/**
 * Affichage des créneaux sous forme de boutons
 */
BookingPlugin.RenderSlots = function (slots) {
    var container = Dom.GetById("bookingSlots");
    if (!container) return;

    if (!slots || slots.length === 0) {
        container.innerHTML = "<p class='text-warning'>" + Language.GetCode("Booking.NoSlotAvailable") + "</p>";
        var stepForm = Dom.GetById("stepForm");
        if (stepForm) stepForm.style.display = "none";
        return;
    }

    var html = "<div class='booking-slots-grid'>";
    for (var i = 0; i < slots.length; i++) {
        html += "<button type='button' class='btn btn-outline-primary booking-slot-btn' data-slot='" + slots[i] + "'>" + slots[i] + "</button> ";
    }
    html += "</div>";
    container.innerHTML = html;

    // Écoute des clics sur les créneaux
    var btns = document.querySelectorAll(".booking-slot-btn");
    for (var j = 0; j < btns.length; j++) {
        btns[j].addEventListener("click", function () {
            // Déselectionner les autres
            var all = document.querySelectorAll(".booking-slot-btn");
            for (var k = 0; k < all.length; k++) {
                all[k].classList.remove("btn-primary");
                all[k].classList.add("btn-outline-primary");
            }
            this.classList.remove("btn-outline-primary");
            this.classList.add("btn-primary");

            BookingPlugin.SelectSlot(this.getAttribute("data-slot"));
        });
    }
};

/**
 * Sélection d'un créneau : affichage du formulaire
 */
BookingPlugin.SelectSlot = function (slot) {
    BookingPlugin.SelectedSlot = slot;

    // Construire le datetime complet : date + heure
    var dateTime = BookingPlugin.SelectedDate + " " + slot + ":00";

    // Remplir le champ caché DateStart
    var dateStartInput = document.querySelector("#BookingPluginFormForm input[name='DateStart']");
    if (dateStartInput) dateStartInput.value = dateTime;

    // Remplir les champs TypeId, EntityName, EntityId
    var typeInput = document.querySelector("#BookingPluginFormForm input[name='TypeId']");
    if (typeInput) typeInput.value = BookingPlugin.TypeId;

    var entityNameInput = document.querySelector("#BookingPluginFormForm input[name='EntityName']");
    if (entityNameInput) entityNameInput.value = BookingPlugin.EntityName;

    var entityIdInput = document.querySelector("#BookingPluginFormForm input[name='EntityId']");
    if (entityIdInput) entityIdInput.value = BookingPlugin.EntityId;

    // Afficher le label du créneau sélectionné
    var label = Dom.GetById("bookingSelectedSlotLabel");
    if (label) {
        label.innerHTML = "<strong>" + Language.GetCode("Booking.SelectedSlot") + " : " + BookingPlugin.SelectedDate + " " + slot + "</strong>";
    }

    Animation.Show("stepForm");
};
