let calendar; // הכרזה גלובלית
var currentContactId;
var selectedHour;
var selectedDateStr;
var selectedDate;

document.addEventListener('DOMContentLoaded', () => {
    // document.querySelectorAll('.row.gx-0.gy-4').forEach(el => {
    //     el.style.display = 'none';
    // });
    document.querySelectorAll('.ms-lg-5.ps-lg-5').forEach(el => {
        el.style.display = 'none';
    });

    document.querySelectorAll('.mb-1.fw-medium').forEach(el => {
        el.style.display = 'none';
    }); 

      document.querySelectorAll('.display-flex.gap-20.fs-14.mb-5').forEach(el => {
         el.style.setProperty('display', 'none', 'important');
    }); 
    
  const dateTimeCol = document.getElementById('dateTimeColumn');
  if (dateTimeCol) {
    dateTimeCol.style.display = 'none';
  }

    const { Calendar } = window.VanillaCalendarPro;

    const currentDate = new Date();
    const currentMonth = currentDate.getMonth();
    const currentYear = currentDate.getFullYear();

    const options = {
        locale: 'he',
        firstWeekday: 0,
        selectedTheme: 'light',
        selectedMonth: currentMonth,
        selectedYear: currentYear
    };

    const calendarElement = document.querySelector('.calendar');
    if (calendarElement) {
        calendar = new Calendar(calendarElement, options); // שימוש במשתנה גלובלי
        calendar.init();

        // הגדרה של מעבר חודש:
        calendar.onMonthChange = (data) => {

            // שלב 2: עדכון תצוגה לפי החודש החדש
            const displayedMonth = data.selectedMonth;
            const displayedYear = data.selectedYear;

            const firstDayOfMonth = new Date(displayedYear, displayedMonth, 1);
            applyFilters(firstDayOfMonth);
        };
    }
    
    const calendarWrapper = document.querySelector('.calendar');
    if (calendarWrapper) {
        calendarWrapper.addEventListener('click', async (event) => {
            const clickedDateElement = event.target.closest('.vc-date');
            if (clickedDateElement && clickedDateElement.classList.contains('calendar-range')) {
                const selectedDate = await handleDateClick(clickedDateElement);
                if (selectedDate) {
                    window.selectedDate = selectedDate;
                }
            }
        });
    }


    const prevButton = document.querySelector('.vc-arrow_prev');
    const nextButton = document.querySelector('.vc-arrow_next');

   if (prevButton) {
        prevButton.addEventListener('click', () => {
            setTimeout(() => {
                const displayedMonth = parseInt(document.querySelector('[data-vc="month"]').getAttribute('data-vc-month'));
                const displayedYear = parseInt(document.querySelector('[data-vc="year"]').getAttribute('data-vc-year'));
                const firstDayOfMonth = new Date(displayedYear, displayedMonth, 1);
                applyFilters(firstDayOfMonth);
            }, 100); // השהייה קצרה כדי לתת ללוח שנה זמן להתעדכן
        });
    }

    if (nextButton) {
        nextButton.addEventListener('click', () => {
            setTimeout(() => {
                const displayedMonth = parseInt(document.querySelector('[data-vc="month"]').getAttribute('data-vc-month'));
                const displayedYear = parseInt(document.querySelector('[data-vc="year"]').getAttribute('data-vc-year'));
                const firstDayOfMonth = new Date(displayedYear, displayedMonth, 1);
                applyFilters(firstDayOfMonth);
            }, 100);
        });
    }


    document.addEventListener('click', async (event) => {
        const clickedDateElement = event.target.closest('.available');
        if (!clickedDateElement) {
            return;
        }
    
        selectedDateStr = clickedDateElement.getAttribute('data-vc-date');
        await handleDateClick(clickedDateElement);
    });

    document.addEventListener('change', function (event) {
        if (event.target.type === 'checkbox') { 
            selectedHour = event.target.value;
        }
    });

    document.getElementById('submitButton').addEventListener('click', async function () {
        debugger
        var submitButton = document.getElementById('submitButton');
        submitButton.innerHTML = "מעבד...";
        var enter = getParameterByName('enter');

        const checkedHourCheckbox = document.querySelector('#dateTimeColumn input[type="checkbox"]:checked');
        const selectedHour = checkedHourCheckbox ? checkedHourCheckbox.value : null;

        if (!selectedHour) {
        alert("בחר שעה לפני המשך קביעת התור");
        return;
        }

        var meetingData = await getDataFromMeetingRequest();
        var accountServiceName; 
        var meetingId;
       
        if (meetingData) {
            meetingId = meetingData.appointmentId;
            accountServiceName = meetingData.accountServiceName;
        }
        // const resourceId = await fetchBookableResourceByContact(currentContactId, selectedDate);
        // if (resourceId) {
        //      console.log("Resource ID:", resourceId);
        // }

        try {
            if (!enter) {
                console.log("!enter")

                var laterChecked = document.getElementById('laterMeeting').checked;
           
                if (laterChecked) {
                    await UpdateMeetingRequest(0, 100000002, meetingId);
                } 
                if ((!selectedHour || !selectedDate) && !laterChecked) { 
                    alert("יש לבחור מועד ושעה לקיום הפגישה");
                    submitButton.innerHTML = "שליחה";
                    return;
                }
                else{
                    statuscode = 100000003;
                    await createAndUpdateAppointment(selectedHour, selectedDate, statuscode, accountServiceName); 
                } 
            }
            else if (enter){
        
                var cancelChecked = document.getElementById('cancelMeeting').checked;

                if (cancelChecked) {
                    console.log("cancel")
                    await UpdateMeetingRequest(1, 100000004, meetingId);
                }

                if ((!selectedHour || !selectedDate) && !cancelChecked) { 
                    alert("יש לבחור מועד ושעה לקיום הפגישה");
                    submitButton.innerHTML = "שליחה";
                    return;
                }
                if (meetingId) {
                    await updateHoursAppointment(selectedHour, selectedDate, meetingId); 
                    await UpdateMeetingRequest(0, 100000003, meetingId);
                } else {
                    await createAndUpdateAppointment(selectedHour, selectedDate, 100000003); 
                }
            }
        } catch (err) {
            alert("Error: " + err.message);
        }
    });

    async function createAndUpdateAppointment(selectedHour, selectedDate, statuscode, accountServiceName,meetingId) {
        debugger;
        try {
            var statecode = 0;
            CreateAppointment(selectedHour, selectedDate, accountServiceName) 
            .then(function(meetingId) {
                    UpdateMeetingRequest(statecode, statuscode, meetingId); 
                })
                .catch(function(error) {
                    console.error("שגיאה ביצירת פגישה:", error);
                });
        } catch (err) {
            alert("Error: " + err.message);
        }
    }

    async function UpdateMeetingRequest(statecode, statuscode, meetingId) {
        debugger
        var meetingRequestId = getParameterByName('id');

        if (!meetingRequestId) {
            console.log("Invalid meeting request ID");
            return;
        }
        var updateData = {
            "statuscode": statuscode,
            "statecode": statecode
        };

        if (currentContactId) {
            updateData["pmn_id_contact@odata.bind"] = "/contacts(" + currentContactId + ")";
        }
        if (meetingId) {
            updateData["pmn_id_appointment@odata.bind"] = "/appointments(" + meetingId + ")";
        }

        try {
            await webapi.safeAjax({
                type: "PATCH",
                url: "/_api/pmn_meeting_requests(" + meetingRequestId + ")",
                contentType: "application/json",
                data: JSON.stringify(updateData)
            });

            console.log("Success: Meeting request updated successfully.");
            if(statuscode=="100000004" && meetingId){
                UpdateMeeting(meetingId,4,2)
            }
            window.location.href = '/ThankPage/'; // מעבר לדף תודה
        } catch (xhrError) {
            console.log("Error occurred while updating meeting request:", xhrError);
            console.log("UpdateMeetingRequest - Error details: " + xhrError.responseText);

            if (xhrError && xhrError.responseJSON && xhrError.responseJSON.error) {
                console.log("Error Code:", xhrError.responseJSON.error.code);
                console.log("Error Message:", xhrError.responseJSON.error.message);
            }

            alert("An error occurred while updating the meeting request. Please try again later.");
        }
    }

    async function UpdateMeeting(meetingId, statuscode,statecode) {
        var updateData = {
            "statuscode": statuscode,
            "statecode": statecode
        };
        try {
            await webapi.safeAjax({
                type: "PATCH",
                url: "/_api/appointments(" + meetingId + ")",
                contentType: "application/json",
                data: JSON.stringify(updateData)
            });
            console.log("Success: Meeting updated successfully.");
            window.location.href = '/ThankPage/'; // מעבר לדף תודה
        } catch (xhrError) {
            console.log("Error occurred while updating meeting :", xhrError);

            if (xhrError && xhrError.responseJSON && xhrError.responseJSON.error) {
                console.log("Error Code:", xhrError.responseJSON.error.code);
                console.log("Error Message:", xhrError.responseJSON.error.message);
            }

            alert("An error occurred while updating the meeting request. Please try again later.");
        }
    }

    async function updateHoursAppointment(selectedHour, selectedDate, meetingId) {
        debugger
        if (!selectedHour) {
            alert("יש לבחור שעה לקיום הפגישה");
            return;
        }

        return new Promise((resolve, reject) => {
            try {
                var record = {};
                var [hours, minutes] = selectedHour.split(":");
                var newSelectedDate = new Date(selectedDate); // השתמש בתאריך שהועבר
                newSelectedDate.setHours(hours);
                newSelectedDate.setMinutes(minutes);
                newSelectedDate.setSeconds(0);

                var endSelectedDate = new Date(newSelectedDate);
                endSelectedDate.setMinutes(endSelectedDate.getMinutes() + 60);
                endSelectedDate.setSeconds(0);

                record["scheduledstart"] = newSelectedDate.toISOString();
                record["scheduledend"] = endSelectedDate.toISOString();

                // if (resourceId) {
                //     record["pmn_id_bookableresource@odata.bind"] = "/bookableresources(" + resourceId + ")";
                // }
                
                if (meetingId && meetingId !== 'undefined') {
                    webapi.safeAjax({
                        type: "PATCH",
                        url: "/_api/appointments(" + meetingId + ")",
                        contentType: "application/json",
                        data: JSON.stringify(record),
                        success: function (res, status, xhr) {
                            resolve(xhr.getResponseHeader("entityid"));
                        },
                        error: function (xhr, status, error) {
                            console.log("There was an error while updating the appointment.");
                            console.log("Error details: " + xhr.responseText);
                            reject(new Error("Failed to update appointment: " + error));
                        }
                    });
                } else {
                    console.log("Invalid meetingId");
                    reject(new Error("Invalid meetingId"));
                }
            } catch (err) {
                console.log("An error occurred: " + err.message);
                reject(err);
            }
        });
    }

    const genderCheckboxes = document.querySelectorAll('.droplist[data-type="gender"] .droplist-check input[type="checkbox"]');
    const languageCheckboxes = document.querySelectorAll('.droplist[data-type="language"] .droplist-check input[type="checkbox"]');

    genderCheckboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            updateSelectedText('gender');
        });
    });

    languageCheckboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            updateSelectedText('language');
        });
    });

    function updateSelectedText(type) {
        const selectedValues = [];

        let checkboxes;
        let labelTextElement;

        if (type === 'gender') {
            checkboxes = genderCheckboxes;
            labelTextElement = document.querySelector('.droplist[data-type="gender"] .droplist-label span');
        } else if (type === 'language') {
            checkboxes = languageCheckboxes;
            labelTextElement = document.querySelector('.droplist[data-type="language"] .droplist-label span');
        }

        checkboxes.forEach(function(checkbox) {
            if (checkbox.checked) {
                const label = checkbox.closest('label');
                const text = label ? label.textContent.trim() : '';
                selectedValues.push(text);
            }
        });

        if (selectedValues.length > 0) {
            labelTextElement.textContent = selectedValues.join(', ');
        } else {
            labelTextElement.textContent = 'בחר';
        }
    }
});

function fetchBookableResourceByContact(contactId, selectedDateTime) {
  return new Promise((resolve, reject) => {
    if (!contactId || !selectedDateTime) {
      reject(new Error("חסר contactId או selectedDateTime"));
      return;
    }

    const isoDate = new Date(selectedDateTime).toISOString();

    const fetchXml = `
      <fetch top="1">
        <entity name="bookableresource">
          <attribute name="bookableresourceid" />
          <attribute name="name" />
          <order attribute="name" />
          <link-entity name="contact" from="contactid" to="resourceid" link-type="inner">
            <filter>
              <condition attribute="contactid" operator="eq" value="${contactId}" />
            </filter>
          </link-entity>
          <filter>
            <condition attribute="statecode" operator="eq" value="0" />
          </filter>
        </entity>
      </fetch>
    `;

    const req = new XMLHttpRequest();
    req.open("GET", "/_api/bookableresources?fetchXml=" + encodeURIComponent(fetchXml), true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", 'odata.include-annotations="*"');

    req.onreadystatechange = function () {
      if (req.readyState === 4) {
        if (req.status === 200) {
          const results = JSON.parse(req.responseText).value;
          if (results.length > 0) {
            const resourceId = results[0].bookableresourceid;
            resolve(resourceId);
          } else {
            resolve(null); // לא נמצא
          }
        } else {
          reject(new Error("שגיאה בשליפת Bookable Resource"));
        }
      }
    };

    req.send();
  });
}

async function applyFilters(displayedDate = new Date()) {
 
    document.querySelectorAll('.ms-lg-5.ps-lg-5').forEach(el => {
       el.style.display = 'block';
    });

    const dateTimeCol = document.getElementById('dateTimeColumn');
    if (dateTimeCol) {
        dateTimeCol.style.display = 'none';
    }

    document.querySelectorAll('.mb-1.fw-medium').forEach(el => {
       el.style.display = 'block';
    });

    document.querySelectorAll('.display-flex.gap-20.fs-14.mb-5').forEach(el => {
        el.style.display = 'none';
    }); 

    const gender = getSelectedGender();
    const language = getSelectedLanguage();
    const formattedDate = formatDate(displayedDate); // להשתמש בתאריך של החודש המוצג

    const requestData = {
        date: formattedDate,
        gender: gender,
        language: language,
        KindService:893450000
    };

    console.log("Request Data being sent:", requestData);
    showLoading();

    try {
        const response = await fetch('https://paamonimazureapp.azurewebsites.net/api/GetAvailableDates?code=caFLtNq4NLuxeSWsLvxkbrd1c7kzuLCx5/pfVoMn64wOA89jJMSzDg==', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        hideLoading();
        console.log("Data received from API:", data);
        processAvailableDates(data);
    } catch (error) {
        console.error('Error fetching available dates:', error);
        hideLoading();
    }
}

function processAvailableDates(data) {
    const dateTimeCol = document.getElementById('dateTimeColumn');
    if (dateTimeCol) {
        dateTimeCol.style.display = 'block';
    }
  const availableDays = new Set();
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const month = parseInt(document.querySelector('[data-vc="month"]').getAttribute('data-vc-month'));
  const year = parseInt(document.querySelector('[data-vc="year"]').getAttribute('data-vc-year'));

  data.forEach(item => {
    if (!item.dates) return;

    item.dates.forEach(date => {
      if (date.IsPosible) {
        const fullDate = new Date(year, month, date.day);
        fullDate.setHours(0, 0, 0, 0);

        if (fullDate >= today) {
          const isoDate = fullDate.toISOString().split('T')[0];
          availableDays.add(isoDate);
          console.log('Adding available day:', isoDate);
        }
      }
    });
  });

  const calendarDays = document.querySelectorAll('.vc-date');

  calendarDays.forEach(dayElement => {
    // 💡 הוספה חשובה: רק ימים מהחודש הנוכחי
    if (dayElement.dataset.vcDateMonth !== 'current') {
      return;
    }

    const dateStr = dayElement.dataset.vcDate; // בפורמט YYYY-MM-DD
    const date = new Date(dateStr);
    date.setHours(0, 0, 0, 0);
    const isoDate = date.toISOString().split('T')[0];

    if (availableDays.has(isoDate) && date >= today) {
      dayElement.classList.add('calendar-range');

      // הסרת מאזין קודם אם קיים
      const cloned = dayElement.cloneNode(true);
      dayElement.replaceWith(cloned);

      cloned.addEventListener('click', async () => {
        const selected = await handleDateClick(cloned);
        if (selected) window.selectedDate = selected;
      });
    } else {
      dayElement.classList.remove('calendar-range');
    }
  });
}

async function handleDateClick(dayElement) {
    showLoading();

    const day = parseInt(dayElement.textContent);

    const calendarMonth = parseInt(document.querySelector('[data-vc="month"]').getAttribute('data-vc-month'));
    const calendarYear = parseInt(document.querySelector('[data-vc="year"]').getAttribute('data-vc-year'));
    const date = new Date(calendarYear, calendarMonth, day);
    const KindService = 893450000;
    hideLoading();

    const requestData = {
        date: date,
        gender: getSelectedGender(),
        language: getSelectedLanguage()
    };
    var selectedDate = date;
    try {
        const response = await fetch('https://paamonimazureapp.azurewebsites.net/api/GetSlots?code=yVy/JPumYSpP9zLPx0QJaYkkiLeaDf6uyZMDnL6lfyMHdNuwSN/F2A==', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
       const data = await response.json();

        // שמירת איש קשר עם סלוטים זמינים
        const contactWithSlots = data.find(contact => 
            Array.isArray(contact.contactSlot) && contact.contactSlot.length > 0
        );

        if (contactWithSlots) {
            currentContactId = contactWithSlots.contactId;
        } else {
            currentContactId = null;
        }

        hideLoading();

        processAvailableSlots(data); 

        return selectedDate;
    } catch (error) {
        console.error('Error fetching available slots:', error);
    }
}

async function CreateAppointment(selectedHour, selectedDate, accountServiceName) {
    debugger
    console.log('selectedHour',selectedHour)
  return new Promise(async (resolve, reject) => {
    try {
      // ודא שהשעה בפורמט תקין
      if (!selectedHour || typeof selectedHour !== "string" || !selectedHour.includes(":")) {
        throw new Error("שעה לא תקינה");
      }

      var [hours, minutes] = selectedHour.split(":");

      // אם selectedDate הוא לא Date – המרה
      if (!(selectedDate instanceof Date)) {
        selectedDate = new Date(selectedDate); // מחרוזת לתאריך
      }

      if (isNaN(selectedDate.getTime())) {
        throw new Error("תאריך לא תקין");
      }

      // קביעת שעה לתאריך
      var newSelectedDate = new Date(selectedDate);
      newSelectedDate.setHours(parseInt(hours));
      newSelectedDate.setMinutes(parseInt(minutes));
      newSelectedDate.setSeconds(0);

      // הגדרת תאריך סיום
      var endSelectedDate = new Date(newSelectedDate);
      endSelectedDate.setMinutes(endSelectedDate.getMinutes() + 60);

      // שליחת הפגישה ל-CRM
      webapi.safeAjax({
        type: "POST",
        url: "/_api/appointments",
        contentType: "application/json",
        data: JSON.stringify({
          subject: "פגישת ",
          scheduledstart: newSelectedDate.toISOString(),
          scheduledend: endSelectedDate.toISOString()
          // אפשר להוסיף כאן מזהים נוספים אם צריך
        }),
        success: function (res, status, xhr) {
          const entityId = xhr.getResponseHeader("entityid");
          resolve(entityId);
        },
        error: function (xhr, ajaxOptions, thrownError) {
          var errorMsg = "Ajax request failed: " + xhr.responseText;
          alert(errorMsg);
          reject(new Error(errorMsg));
        }
      });
    } catch (error) {
      console.error("Error in CreateAppointment:", error.message);
      alert("שגיאה: " + error.message);
      reject(error);
    }
  });
}

function showLoading() {
    const loadingDiv = document.createElement('div');
    loadingDiv.id = 'loading';
    loadingDiv.style.position = 'fixed';
    loadingDiv.style.top = '50%';
    loadingDiv.style.left = '50%';
    loadingDiv.style.transform = 'translate(-50%, -50%)';
    loadingDiv.style.textAlign = 'center';

    const spinner = document.createElement('div');
    spinner.style.border = '8px solid #f3f3f3';
    spinner.style.borderTop = '8px solid #3498db';
    spinner.style.borderRadius = '50%';
    spinner.style.width = '60px';
    spinner.style.height = '60px';
    spinner.style.animation = 'spin 2s linear infinite';
    loadingDiv.appendChild(spinner);

    const text = document.createElement('p');
    text.textContent = 'מעבד ...';
    text.style.marginTop = '10px';
    loadingDiv.appendChild(text);

    document.body.appendChild(loadingDiv);

    const style = document.createElement('style');
    style.innerHTML = `@keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }`;
    document.head.appendChild(style);
}

function hideLoading() {
    const loadingDiv = document.getElementById('loading');
    if (loadingDiv) {
        loadingDiv.remove();
    }
}

function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${month}-${day}-${year}`;
}

function getSelectedGender() {
    const genderCheckboxes = document.querySelectorAll('input[data-type="gender"]');
    for (const checkbox of genderCheckboxes) {
        if (checkbox.checked) {
            return checkbox.value;
        }
    }
    return ''; // ברירת מחדל אם לא נבחר מגדר
}

function getSelectedLanguage() {
    const languageCheckboxes = document.querySelectorAll('input[data-type="language"]');
    for (const checkbox of languageCheckboxes) {
        if (checkbox.checked) {
            return checkbox.value;
        }
    }
    return ''; // ברירת מחדל אם לא נבחרה שפה
}

function processAvailableSlots(data) {
    const morningSlots = [];
    const afternoonSlots = [];
    const eveningSlots = [];

    const seenTimes = new Set(); // כדי לא לאפשר כפילויות

    data.forEach(item => {
          console.log('Item:', item);

        item.contactSlot.forEach(slot => {
            if (slot.isPosible) {
                const time = slot.s_startHour.split(' ')[1]; // רק השעה, למשל "13:30"
                if (!seenTimes.has(time)) {
                    seenTimes.add(time);
                    const hour = parseInt(time.split(':')[0]);

                    if (hour < 12) {
                        morningSlots.push(slot);
                    } else if (hour < 17) {
                        afternoonSlots.push(slot);
                    } else {
                        eveningSlots.push(slot);
                    }
                }
            }
        });
    });

    displaySlots('morning-slots-container', morningSlots);
    displaySlots('afternoon-slots-container', afternoonSlots);
    displaySlots('evening-slots-container', eveningSlots);
}

async function getDataFromMeetingRequest() {
    debugger
    var meetingRequestId = getParameterByName('id');

    if (!meetingRequestId) {
        console.log("Invalid meeting request ID");
        return null;
    }

    try {
        var response = await webapi.safeAjax({
            type: "GET",
            url: "/_api/pmn_meeting_requests(" + meetingRequestId + ")",
            contentType: "application/json"
        });

        var result = response;

        var id_appointment = result["_pmn_id_appointment_value"];
        var id_accountService = result["_pmn_id_accountserviceid_value"];
        var id_account = result["_pmn_id_account_value"];

        if (!id_appointment) {
            console.log("No appointment ID found for this meeting request.");
        } else {
            console.log("Appointment ID found:", id_appointment);
        }
        if (!id_accountService) {
            console.log("No account service ID found for this meeting request.");
        } else {
            console.log("Account Service ID found:", id_accountService);
        }
        if (!id_account) {
            console.log("No account ID found.");
        } else {
            console.log("Account ID:", id_account);
        }

        if (id_appointment && id_accountService && id_account ) {
            return {
                appointmentId: id_appointment,
                accountServiceId: id_accountService,
                accountId: id_account
            };
        } else {
            console.log("One or more fields are missing.");
            return null;
        }

    } catch (xhrError) {
        console.error("Error details:", xhrError);
        console.log("Error occurred while fetching meeting details.");
        return null;
    }
}

function displaySlots(containerId, slots) {
    const container = document.getElementById(containerId);
    container.innerHTML = ''; // ניקוי תוכן קודם

    if (slots.length === 0) {
        container.innerHTML = '<p class="mb-0">אין פניות בשעות אלו</p>';
    } else {
        slots.forEach(slot => {

            const slotElement = document.createElement('div');
            // פיצול המחרוזת כדי לקבל רק את השעה
            const startTime = slot.s_startHour.split(' ')[1]; // פיצול לפי רווח וקבלת החלק השני
            slotElement.innerHTML = `
                    <span class="checkbox">
                        <input type="checkbox" id="check-${startTime}" value="${startTime}">
                        <span class="checkbox-mark"></span>
                        <label for="check-${startTime}">${startTime}</label>
                    </span>
            `;
            container.appendChild(slotElement);

            // הוספת event listener
            const checkboxSpan = slotElement.querySelector('.checkbox');
            checkboxSpan.addEventListener('click', function() {
                const checkboxInput = this.querySelector('input[type="checkbox"]');
                checkboxInput.checked = !checkboxInput.checked;
            });
        });
    }
}

function getParameterByName(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}
