let allCalendarEvents = [];
let allScheduleDraggedEvents = [];
let allCombineScheduleEvents = [];

// Mobile detection function
function isMobileDevice() {
  return window.innerWidth <= 768;
}

// Get mobile-optimized calendar configuration
function getMobileCalendarConfig() {
  if (isMobileDevice()) {
    return {
      height: 'auto',
      aspectRatio: 1.2,
      dayHeaderFormat: { weekday: 'short', day: 'numeric' },
      slotMinWidth: 65, // Increased to prevent overlap
      slotLabelFormat: {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true
      },
      headerToolbar: {
        left: "prev,next today",
        center: "title",
        right: "timeGridWeek,timeGridDay,listMonth",
      },
      // Additional mobile optimizations
      dayHeaderFormat: { weekday: 'narrow', day: 'numeric' }, // Use single letter for weekdays
      columnHeaderFormat: { weekday: 'narrow' },
      expandRows: true,
      height: 'auto'
    };
  }
  return {
    height: 'auto',
    aspectRatio: 1.35,
    dayHeaderFormat: { weekday: 'long', day: 'numeric' },
    slotMinWidth: 60,
    slotLabelFormat: {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    },
    headerToolbar: {
      left: "prev,next today tableView",
      center: "title",
      right: "multiMonthYear,dayGridMonth,timeGridWeek,timeGridDay,listMonth",
    }
  };
}

$(document).ready(function () {
  $("#isWeeklyViewEle").bootstrapSwitch();
  addSwitchForWeeklyCalendarView();
  document.getElementById("isWeeklyViewEle").value=true;
  scheduleDataRequest({
    get_weekly_schedule: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
  
  // Handle window resize for mobile responsiveness
  let resizeTimer;
  window.addEventListener('resize', function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      if (calendar) {
        calendar.updateSize();
        // Re-render with mobile-optimized settings if needed
        if (isMobileDevice()) {
          calendar.setOption('dayHeaderFormat', { weekday: 'short', day: 'numeric' });
          calendar.setOption('slotMinWidth', 50);
        } else {
          calendar.setOption('dayHeaderFormat', { weekday: 'long', day: 'numeric' });
          calendar.setOption('slotMinWidth', 60);
        }
      }
    }, 250);
  });
});

async function scheduleDataRequest(data) {
  $.ajax({
    url: "include/property_builder/schedule/schedule_requests.php",
    type: "post",
    data,
    success: async function (response) {
      if (
        data?.addEventToCalendar ||
        data?.updateCalendarAddedEventThroughModal
      ) {
        $("#createCalendarEventModal").modal("hide");
        window.location.reload();
      } else if (data?.getAddedEventsToCalendar) {
        // initializeCalendarEvents(response);
      } else if (
        data?.add_weekly_schedule ||
        data?.delete_weekly_schedule
      ) {
        openCreateCalendarEventModal(false, true);
        // window.location.reload();
        scheduleDataRequest({
          get_weekly_schedule: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      } else if (data?.get_weekly_schedule) {
        allCombineScheduleEvents=response;
        initializeCalendarEvents(response);
      } else if (data?.add_custom_calendar_schedule_request) {
        showSuccessGlobalToastMessage("Added successfully");
        openCreateCalendarEventModal(false, true);
        scheduleDataRequest({
          get_weekly_schedule: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      } else if (data?.delete_custom_calendar_schedule) {
        showSuccessGlobalToastMessage("Deleted successfully");
        scheduleDataRequest({
          get_weekly_schedule: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }else if (data?.edit_custom_calendar_schedule_request) {
        showSuccessGlobalToastMessage("Updated successfully");
        openCreateCalendarEventModal(false, true);
        scheduleDataRequest({
          get_weekly_schedule: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }else if(data?.edit_weekly_schedule){
        showSuccessGlobalToastMessage("Updated successfully");
        scheduleDataRequest({
          get_weekly_schedule: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
        openCreateCalendarEventModal(false, true);
        if(response?.isControlingDevices){
          const backendNodeUrl = await getBackendStreamingUrlForCronJob({ get_streaming_url_request: true });
          await sendCronJobUpdateRequest(backendNodeUrl+'/delete_schedule_task',{scheduleId:response?.updated_id});
          showConfirmModal("Its controling the devices. Do you want to update the cron job also?",function(){
            window.location.href="/command_center.php";
          });
        }

      }
    },
    error: function (xhr, status, error) {
      showScheduleToastMessage(xhr?.responseJSON?.error || error);
    },
  });
}

async function getBackendStreamingUrlForCronJob(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/property_builder/command_center/command_center_requests.php",
      type: "post",
      data,
      success: function (resp) {
        backendNodeUrl = `${resp?.data}/api`;
        resolve(backendNodeUrl);
      },
      error: function (xhr, status, error) {
        reject(xhr || error);
      },
    });
  });
}

async function sendCronJobUpdateRequest(url,payload,token=null) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url,
      type: "POST",
      data: JSON.stringify(payload),
      contentType: "application/json",
      headers: {
        authorization: `${token}`
      },
      success: function (resp) {
          resolve(resp);
      },
      error: function (xhr, status, error) {
        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
        else reject(error);
      },
    });
  });
}

function initializeCalendarEvents(response) {
  allCalendarEvents = response;
  const allEvents = get_all_events(response);
  initializeCalendar(allEvents);
}

function get_all_events(response){
  let allEvents = [];
  for (let item of response) {
    if (item?.periods?.length > 0) {
      for (let period of item.periods) {
        const activeDays = Object.keys(period.days).filter(
          (day) => period.days[day]?.is_active // Check if the day is active
        );

        activeDays.forEach((day) => {
          const dayMap = {
            sun: 0,
            mon: 1,
            tue: 2,
            wed: 3,
            thu: 4,
            fri: 5,
            sat: 6,
          };
          const targetDay = dayMap[day];

          const periodStartDate = new Date(period?.start_date);
          let periodEndDate = null;
          if (!period?.end_date) {
            const sevenDaysLater = new Date();
            sevenDaysLater.setDate(sevenDaysLater.getDate() + 7);
            periodEndDate = sevenDaysLater.toISOString().slice(0, 10);
            console.log("Generated end_date:", periodEndDate);
            periodEndDate=new Date(periodEndDate)
        }else periodEndDate = new Date(period?.end_date);

          let currentDate = new Date(periodStartDate);
          while (currentDate <= periodEndDate) {
            // Check if current date matches the target day
            if (currentDate.getDay() === targetDay) {
              const startTime = period?.days[day]?.day_startTime || period?.start_time;
              const endTime = period?.days[day]?.day_endTime || period?.end_time;

              if (!startTime || !endTime) {
                currentDate.setDate(currentDate.getDate() + 1);
                continue;
              }

              const [startHour, startMinute] = startTime.split(":");
              const [endHour, endMinute] = endTime.split(":");

              const startDate = new Date(currentDate);
              startDate.setHours(parseInt(startHour), parseInt(startMinute), 0);
              const endDate = new Date(currentDate);
              endDate.setHours(parseInt(endHour), parseInt(endMinute), 0);

              const event = {
                schedule_id: item.schedule_id,
                schedule_uuid: null,
                dayId: period.days[day].day_id,
                period_id: period.period_id,
                id: period.days[day].day_id,
                title: `${item.title} (period ${period?.period_number})`,
                allDay: false,
                start: startDate ? new Date(startDate).toISOString() : null,
                end: endDate ? new Date(endDate).toISOString() : null,
                backgroundColor: item.backgroundColor,
                borderColor: item.backgroundColor,
                schedule_type: item.schedule_type,
              };
              allEvents.push(event);
            }
            // Move to next day
            currentDate.setDate(currentDate.getDate() + 1);
          }
        });
      }
    } else if (item?.uuid) {
      const event = {
        schedule_id: item.id,
        schedule_uuid: item.uuid,
        dayId: null,
        period_id: null,
        id: item.id,
        title: item.title,
        allDay: false,
        start: item?.start ? new Date(item?.start).toISOString() : null,
        end: item?.end ? new Date(item?.end).toISOString() : null,
        backgroundColor: item.backgroundColor,
        borderColor: item.borderColor,
        schedule_type: item.schedule_type,
      };
      allEvents.push(event);
    }
  }

  return allEvents;
}

function ini_events(ele) {
  ele.each(function () {
    var eventObject = {
      title: $.trim($(this).text()), // use the element's text as the event title
    };
    $(this).data("eventObject", eventObject);
  });
}

async function updateEventToCalendar(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "include/property_builder/schedule/schedule_requests.php",
      type: "post",
      data,
      success: function (response) {
        resolve(response);
      },
      error: function (xhr, status, error) {
        console.log("xhr", xhr);
        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
        else reject(error);
      },
    });
  });
}

function deleteEventFromCalendar(
  id,
  schedule_id,
  period_id,
  schedule_uuid = null,
  onSuccessCallback = null
) {
  // resetForm();
  if (schedule_uuid) {
    scheduleDataRequest({
      delete_custom_calendar_schedule: true,
      schedule_uuid,
    }).then(response => {
      if (onSuccessCallback) {
        onSuccessCallback();
      }
    });
    return;
  }
  scheduleDataRequest({ delete_weekly_schedule: true, id, schedule_id }).then(response => {
    if (onSuccessCallback) {
      onSuccessCallback();
    }
  });
}

function completeDeleteEventFromCalendar(schedule_id,onSuccessCallback = null) {
  scheduleDataRequest({ complete_delete_weekly_schedule: true, schedule_id }).then(response => {
    if (onSuccessCallback) {
      onSuccessCallback();
    }
  });
}

function initializeCalendar(events) {
  /* initialize the external events */
  $(document).ready(function () {
    ini_events($("#external-events div.external-event"));
  });
  /* initialize the calendar */

  var Calendar = FullCalendar.Calendar;
  // Call the ini_events function on page load to initialize the external events
  var Draggable = FullCalendar.Draggable;
  var containerEl = document.getElementById("external-events");
  var calendarEl = document.getElementById("calendar");
  calendarEl.innerHTML = "";
  var calendarHeader = document.querySelector(".fc-header-toolbar");
  if (calendarHeader === null) {
    new Draggable(containerEl, {
      itemSelector: ".external-event",
      eventData: function (eventEl) {
        return {
          title: eventEl.innerText,
          backgroundColor: window
            .getComputedStyle(eventEl, null)
            .getPropertyValue("background-color"),
          borderColor: window
            .getComputedStyle(eventEl, null)
            .getPropertyValue("background-color"),
          textColor: window
            .getComputedStyle(eventEl, null)
            .getPropertyValue("color"),
        };
      },
    });

    // Get mobile-optimized configuration
    const mobileConfig = getMobileCalendarConfig();
    
    calendar = new Calendar(calendarEl, {
      nowIndicator: true,
      initialView: "timeGridWeek",
      customButtons: {
        tableView: {
          text: 'Schedule List',
          click: function() {
            // const allEvents = get_all_events(allCalendarEvents);
            changeScheduleView(allCombineScheduleEvents);
          }
        }
      },
      headerToolbar: mobileConfig.headerToolbar,
      themeSystem: "bootstrap",
      // themeSystem: 'bootstrap5', // Optional: If you're using Bootstrap 5, you can apply it directly here.
      eventBorderColor: "#0056b3",
      events: events,
      editable: true,
      multiMonthMinWidth: 500,
      droppable: true, // this allows things to be dropped onto the calendar
      
      height: mobileConfig.height,
      aspectRatio: mobileConfig.aspectRatio,
      dayHeaderFormat: mobileConfig.dayHeaderFormat,
      slotMinWidth: mobileConfig.slotMinWidth,
      slotLabelFormat: mobileConfig.slotLabelFormat,
      eventDrop: function (info) {
        var event = info.event;
        let update_payload;

        if (event.extendedProps?.schedule_uuid) {
          const selected = allCalendarEvents.find(
            (ele) => ele?.uuid == event.extendedProps?.schedule_uuid
          );
          let startDate = new Date(event.startStr);
          let endDate = new Date(event.endStr);
          let formattedStartDate =
            moment(startDate).format("MM/DD/YYYY hh:mm A");
          let formattedEndDate = moment(endDate).format("MM/DD/YYYY hh:mm A");

          update_payload = {
            id: selected.id,
            uuid: selected.uuid,
            backgroundColor: selected.backgroundColor,
            borderColor: selected.borderColor,
            title: selected.title,
            end: formattedEndDate,
            start: formattedStartDate,
            allDay: false,
            edit_drag_drop_custom_calendar_schedule_request: true,
          };
        } else {
          if (formatDateTimeInCalendar(event.startStr).day !== formatDateTimeInCalendar(event.endStr).day) {
            console.log("Weekly schedule cannot have two days");
            showScheduleToastMessage(
              "Weekly schedule cannot have two days. You can not lead a single event to the next day. Please edit the event."
            );
            info.revert();
            return;
          }

          const schedule = allCalendarEvents.find(ele => ele.schedule_id === event.extendedProps.schedule_id);
          const period = schedule?.periods?.find(p => p.period_id === event.extendedProps.period_id);
          
          if (!period) {
            showScheduleToastMessage("Could not find the period information");
            info.revert();
            return;
          }

          const newDay = formatDateTimeInCalendar(event.startStr).day;
          const periodStartDate = new Date(period.start_date);
          const periodEndDate = new Date(period.end_date);
          const newDate = new Date(event.startStr);
          
          if (newDate < periodStartDate || newDate > periodEndDate) {
            showScheduleToastMessage(
              `Cannot move event outside the period's date range (${period.start_date} to ${period.end_date})`
            );
            info.revert();
            return;
          }

          update_payload = {
            schedule_id: event.extendedProps?.schedule_id,
            schedule_uuid: event.extendedProps?.schedule_uuid,
            dayId: event.extendedProps?.dayId,
            period_id: event.extendedProps.period_id,
            title: event._def.title,
            allDay: false,
            startTime: formatDateTimeInCalendar(event.startStr).time,
            day: formatDateTimeInCalendar(event.startStr).day,
            endTime: formatDateTimeInCalendar(event.endStr).time,
            update_on_drag_drop_weekly_schedule: true,
          };
        }

        showConfirmModal(
          "Are you sure you want to update the event",
          async function () {
            try {
              await updateEventToCalendar(update_payload);
              showSuccessGlobalToastMessage("Updated successfully");
              scheduleDataRequest({
                get_weekly_schedule: true,
                property_id: sessionStorage.getItem("propertyId"),
              });
            } catch (error) {
              console.log("error in updating ", error);
              showScheduleToastMessage(error);
              info.revert();
            }
          },
          function () {
            info.revert();
          }
        );
      },
      eventResize: function (info) {
        var event = info.event;

        let update_payload;
        if (event.extendedProps?.schedule_uuid) {
          const selected = allCalendarEvents.find(
            (ele) => ele?.uuid == event.extendedProps?.schedule_uuid
          );
          let startDate = new Date(event.startStr);
          let endDate = new Date(event.endStr);
          let formattedStartDate =
            moment(startDate).format("MM/DD/YYYY hh:mm A");
          let formattedEndDate = moment(endDate).format("MM/DD/YYYY hh:mm A");

          update_payload = {
            id: selected.id,
            uuid: selected.uuid,
            backgroundColor: selected.backgroundColor,
            borderColor: selected.borderColor,
            title: selected.title,
            end: formattedEndDate,
            start: formattedStartDate,
            allDay: false,
            edit_drag_drop_custom_calendar_schedule_request: true,
          };
        } else {
          if (
            formatDateTimeInCalendar(event.startStr).day !==
            formatDateTimeInCalendar(event.endStr).day
          ) {
            console.log("Weekly schedule cannot have two days");
            showScheduleToastMessage(
              "Weekly schedule cannot have two days.You can not lead a single event to the next day. Please edit the event."
            );
            info.revert();
            return;
          }

          update_payload = {
            schedule_id: event.extendedProps.schedule_id,
            dayId: event.extendedProps.dayId,
            schedule_uuid: event.extendedProps.schedule_uuid,
            period_id: event.extendedProps.period_id,
            title: event._def.title,
            allDay: false,
            startTime: formatDateTimeInCalendar(event.startStr).time,
            day: formatDateTimeInCalendar(event.startStr).day,
            endTime: formatDateTimeInCalendar(event.endStr).time,
            update_on_drag_drop_weekly_schedule: true,
          };
        }

        showConfirmModal(
          "Are you sure you want to update the event",
          async function () {
            try {
              await updateEventToCalendar(update_payload);
              showSuccessGlobalToastMessage("Updated successfully");
            } catch (error) {
              console.log("error in updating ", error);
              showScheduleToastMessage(error);
              info.revert();
            }
          },
          function () {
            info.revert();
          }
        );
      },
      eventContent: function (arg) {
        // Create the parent div with flex class
        let parentDiv = document.createElement("div");
        parentDiv.classList.add(
          "d-flex",
          "justify-content-between",
          "align-items-center",
          "flex-wrap",
          "w-100"
        );

        let iconsDiv = document.createElement("div");
        iconsDiv.classList.add(
          "icons-container",
          "d-flex",
          "align-items-center"
        );

        // Create the dot for the event color
        let dotDiv = document.createElement("div");
        dotDiv.style.width = "10px";
        dotDiv.style.height = "10px";
        dotDiv.style.borderRadius = "50%";
        dotDiv.style.backgroundColor = arg.event.backgroundColor;
        dotDiv.style.marginRight = "5px";

        // Create the event data div
        let eventDataDiv = document.createElement("div");
        eventDataDiv.innerHTML = arg.event.title;
        eventDataDiv.classList.add(
          "event-data",
          "d-flex",
          "justify-content-between",
          "align-items-center"
        );

        // Create the edit icon div
        let editIconDiv = document.createElement("div");
        editIconDiv.classList.add("edit-icon");
        let editIcon = document.createElement("span");
        editIcon.innerHTML = "✏️"; // Use an edit icon (or Font Awesome/Bootstrap icon)
        editIcon.style.cursor = "pointer";
        editIcon.style.color = "blue";
        editIcon.style.fontSize = "10px";
        // editIcon.style.padding = "8px";
        editIcon.addEventListener("click", function (event) {
          event.stopPropagation();
          editCalendarSchedule(
            arg.event.extendedProps.schedule_id,
            arg?.event.extendedProps.schedule_uuid
          );
        });
        editIconDiv.appendChild(editIcon);

        // Create the delete icon div
        let deleteIconDiv = document.createElement("div");
        deleteIconDiv.classList.add("delete-icon");
        let deleteIcon = document.createElement("span");
        deleteIcon.innerHTML = "&times;"; // or use an icon class for a font awesome icon
        deleteIcon.style.cursor = "pointer";
        deleteIcon.style.color = "red";
        deleteIcon.addEventListener("click", function (event) {
          event.stopPropagation();
          showConfirmModal(
            "Are you sure you want to delete this event?",
            function () {
              arg.event.remove(); // Remove event from calendar
              deleteEventFromCalendar(
                arg.event.id,
                arg.event.extendedProps.schedule_id,
                arg.event.extendedProps.period_id,
                arg.event.extendedProps.schedule_uuid
              );
            }
          );
        });

        deleteIconDiv.appendChild(deleteIcon);

        iconsDiv.appendChild(editIcon);
        iconsDiv.appendChild(deleteIcon);
        // Append the dot and event data div to the parent div
        eventDataDiv.prepend(dotDiv);
        parentDiv.appendChild(eventDataDiv);
        parentDiv.appendChild(deleteIconDiv);
        parentDiv.appendChild(iconsDiv);

        let arrayOfDomNodes = [parentDiv];

        return { domNodes: arrayOfDomNodes };
      },
    });
    calendar.render();
  } else {
    console.log("Calendar already initialized");
  }
}

function changeScheduleView(allEvents) {
  // Toggle table view
  let tableContainer = document.getElementById('calendar-table-view');
  let calendarEl = document.getElementById('calendar');
  if (!tableContainer) {
    tableContainer = document.createElement('div');
    tableContainer.id = 'calendar-table-view';
    tableContainer.style.marginTop = '20px';
    calendarEl.parentNode.insertBefore(tableContainer, calendarEl.nextSibling);
  }

  // If table is already visible, toggle back to calendar view
  if (tableContainer.style.display === 'block') {
    tableContainer.style.display = 'none';
    calendarEl.style.display = 'block';
    return;
  }

  // Hide calendar
  calendarEl.style.display = 'none';
  // Show table
  tableContainer.style.display = 'block';

  // Build table HTML
  let html = `
  <div style="padding: 0px 10px 10px 15px;">
    <button class="btn btn-primary" onclick="showCalendarView()">Calendar View</button>
  </div>
  <table class="table table-bordered table-striped"><thead><tr><th>Name</th><th>Type</th><th>Action</th></tr></thead><tbody>`;
  if (Array.isArray(allEvents)) {
    allEvents.forEach(event => {
      html += `<tr>
        <td>${event.title || ''}</td>
        <td>${event.schedule_type || ''}</td>
        <td>
          <i onclick='editCalendarSchedule(${event.schedule_id}, ${event.schedule_uuid})' class="fas fa-edit text-primary mx-1"></i>
          <i class="fas fa-trash text-danger" onclick='delete_schedule_from_table(${JSON.stringify(event.schedule_id)})'></i>
        </td>
      </tr>`;
    });
  }
  html += '</tbody></table>';
  tableContainer.innerHTML = html;
}

function showCalendarView() {

  let tableContainer = document.getElementById('calendar-table-view');
  let calendarEl = document.getElementById('calendar');
  if (tableContainer) tableContainer.style.display = 'none';
  if (calendarEl) calendarEl.style.display = 'block';
  const allEvents = get_all_events(allCombineScheduleEvents);
  initializeCalendar(allEvents);
}

function delete_schedule_from_table(id) {
  showConfirmModal(
    "Are you sure you want to delete this event?",
    function () {
      completeDeleteEventFromCalendar(
        id,
        function onDeleteSuccess() {
          const allEvents = get_all_events(allCalendarEvents);
          changeScheduleView(allEvents);
        }
      );
    }
  );
}

function formatDateTimeInCalendar(dateString) {
  const date = new Date(dateString);
  const options = { weekday: "short" }; // "Sun", "Mon", "Tue", etc.
  const day = date.toLocaleDateString("en-US", options).toLocaleLowerCase();
  const time = date.toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: false, // 24-hour format
  });
  return { day, time };
}

$(function () {
  //Datemask dd/mm/yyyy
  $("#datemask").inputmask("dd/mm/yyyy", {
    placeholder: "dd/mm/yyyy",
  });
  //Datemask2 mm/dd/yyyy
  $("#datemask2").inputmask("mm/dd/yyyy", {
    placeholder: "mm/dd/yyyy",
  });
  //Money Euro
  $("[data-mask]").inputmask();

  //Date range picker with time picker
  $("#reservationtime").daterangepicker({
    timePicker: true,
    timePickerIncrement: 30,
    locale: {
      format: "MM/DD/YYYY hh:mm A",
    },
  });

  //Timepicker
  $("#timepicker").datetimepicker({
    format: "LT",
  });

  //Colorpicker
  $(".my-colorpicker1").colorpicker();
  //color picker with addon
  $(".my-colorpicker2").colorpicker();

  $(".my-colorpicker2").on("colorpickerChange", function (event) {
    $(".my-colorpicker2 .fa-square").css("color", event.color.toString());
  });

  $("input[data-bootstrap-switch]").each(function () {
    $(this).bootstrapSwitch("state", $(this).prop("checked"));
  });
});
// BS-Stepper Init
document.addEventListener("DOMContentLoaded", function () {
  window.stepper = new Stepper(document.querySelector(".bs-stepper"));
});

function isAllDayChecked() {
  let isAllDay = $("#isAllDay").prop("checked");
  if (isAllDay) {
    $("#startDateForAllDay").show();
  } else {
    $("#startDateForAllDay").hide();
  }
}

function openCreateCalendarEventModal(newRecord = false, close = false) {
  const schedule_form = document.getElementById("schedule_form");
  const schedule_calendar = document.getElementById("schedule_calendar");
  if (newRecord){
    resetFormValue();
    document.getElementById("isWeeklyViewEle").checked = true;
    changeWeeklyView();
  } 
  if (close) {
    schedule_form.style.display = "none";
    schedule_calendar.style.display = "block";
    scheduleDataRequest({
      get_weekly_schedule: true,
      property_id: sessionStorage.getItem("propertyId"),
    });
  } else {
    schedule_form.style.display = "block";
    schedule_calendar.style.display = "none";
  }
}

function resetFormValue() {
  document.getElementById("schedule_id").value = "";
  document.getElementById("schedule_title").value = "";
  document.getElementById("schedule_type").selectedIndex = 0;
  document.getElementById("schedule_priority").selectedIndex = 0;

  // Keep only one blank row in the table
  const tbody = document.querySelector("#Schedule_table tbody");
  tbody.innerHTML = ""; // Clear all rows

  const rowContent = `
    <tr>
      <td style="vertical-align: middle;" data-period="1">Period 1</td>
      <td style="vertical-align: middle;">
        <input type="date" name="dayStartDate" id="dayStartDate" oninput="validateTime(this,false)" class="form-control" />
      </td>
      <td style="vertical-align: middle;">
        <input type="date" id="dayEndDate" name="dayEndDate" oninput="validateTime(this,false)" class="form-control" />
      </td>
      <td style="vertical-align: middle;">
        <input type="time" name="start_time" oninput="validateTime(this,true)" class="form-control" />
      </td>
      <td style="vertical-align: middle;">
        <input type="time" id="end_time" oninput="validateTime(this,true)" name="end_time" class="form-control" />
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="sun_check_period_1" type="checkbox" data-day-id="sun" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="mon_check_period_1" type="checkbox" data-day-id="mon" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="tue_check_period_1" type="checkbox" data-day-id="tue" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="wed_check_period_1" type="checkbox" data-day-id="wed" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="thu_check_period_1" type="checkbox" data-day-id="thu" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="fri_check_period_1" type="checkbox" data-day-id="fri" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
      <td style="vertical-align: middle; text-align: center;">
        <input id="sat_check_period_1" type="checkbox" data-day-id="sat" data-period="1" onchange="checkDayIsInGivenDates(this)">
      </td>
    </tr>
  `;

  const wrappedRow = `<table><tbody>${rowContent}</tbody></table>`;

  const cleanWrapped = DOMPurify.sanitize(wrappedRow, {
    ADD_ATTR: ['data-period', 'data-day-id', 'onchange', 'type', 'name', 'id', 'class', 'value', 'checked'],
    ADD_TAGS: ['input', 'td', 'tr', 'table', 'tbody'],
    ALLOW_DATA_ATTR: true
  });

  const sanitizedRow = $(cleanWrapped).find("tbody").html();
  tbody.innerHTML = sanitizedRow;
  addScheduleTimeEvents();
}

function addScheduleTimeEvents() {
  const $table = $("#Schedule_table tbody");
  $table.off("input", 'input[type="time"]');
  $table.off("input", 'input[type="date"]');
  $table.off("change", 'input[type="checkbox"]');
  $table.on("input", 'input[type="time"]', function () {
    validateTime(this, true);
  });
  $table.on("input", 'input[type="date"]', function () {
    validateTime(this, false);
  });
  $table.on("change", 'input[type="checkbox"]', function () {
    checkDayIsInGivenDates(this);
  });
}

function getDataAndAddNewRowForSchedule() {
  const data = getLastRowData();
  if (data?.success) {
    addNewRowForScheduleTable();
  }
}

function getLastRowData() {
  const table = document.getElementById("Schedule_table");
  const lastRow = table.rows[table.rows.length - 1];
  const periodCell = lastRow.querySelector("td[data-period]");
  const periodNumber = periodCell
    ? periodCell.getAttribute("data-period")
    : "1";
  const startTime = lastRow.querySelector('input[name="start_time"]').value;
  const endTime = lastRow.querySelector('input[name="end_time"]').value;
  const days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
  const dayStatus = {};
  let isAnyDayChecked = false;

  days.forEach((day) => {
    const checkbox = lastRow.querySelector(
      `#${day}_check_period_${periodNumber}`
    );
    if (checkbox) {
      dayStatus[day] = checkbox.checked;
      if (checkbox.checked) {
        isAnyDayChecked = true;
      }
    }
  });
  if (!isAnyDayChecked) {
    showScheduleToastMessage(
      "start and end time are required and mark at least one day of the week "
    );
  }
  const isValid = startTime && endTime && isAnyDayChecked;
  const lastRowData = {
    data: {
      period: periodNumber,
      startTime,
      endTime,
      dayStatus,
    },
    success: isValid,
  };

  return lastRowData;
}

function submitScheduleData() {
  // Get General Information
  const title = document.getElementById("schedule_title").value;
  const type = document.getElementById("schedule_type").value;
  const priority = document.getElementById("schedule_priority").value;
  const schedule_id = document.getElementById("schedule_id").value;

  // Validate General Information
  if (!title || !type || !priority) {
    showScheduleToastMessage(
      "Please fill in all the required fields in the General section."
    );
    return;
  }
  // Get Time Periods Data
  const table = document.getElementById("Schedule_table");
  const rows = table.querySelectorAll("tbody tr");
  const periods = [];

  for (let row of rows) {
    const periodNumber = row
      .querySelector("td[data-period]")
      .getAttribute("data-period");
    const startDate = row.querySelector('input[name="dayStartDate"]').value;
    const endDate = row.querySelector('input[name="dayEndDate"]').value;
    const startTime = row.querySelector('input[name="start_time"]').value;
    const endTime = row.querySelector('input[name="end_time"]').value;

    // if (!startDate || !endDate) {
    if (!startDate) {
      showScheduleToastMessage(
        `Please select both start and end dates for Period ${periodNumber}.`
      );
      return;
    }

    if (endDate && startDate > endDate) {
      showScheduleToastMessage(
        `Start date cannot be greater than End date for Period ${periodNumber}.`
      );
      return;
    }

    if (endDate && startTime >= endTime) {
      showScheduleToastMessage(
        `Start time cannot be greater than or equal to End time for Period ${periodNumber}.`
      );
      return;
    }

    const days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

    let isAnyDayChecked = false;
    const dayStatus = [];
    days.forEach((day) => {
      const checkbox = row.querySelector(
        `#${day}_check_period_${periodNumber}`
      );
      if (checkbox) {
        if (checkbox.checked) isAnyDayChecked = true;
        dayStatus.push({
          day,
          start_time: startTime,
          end_time: endTime,
          is_active: checkbox.checked ? true : false,
        });
      }
    });

    if (!startTime || !endTime || !isAnyDayChecked) {
      showScheduleToastMessage(
        `Please complete all fields for Period ${periodNumber}.`
      );
      return;
    }

    periods.push({
      period_number: periodNumber,
      start_date: startDate ? new Date(startDate).toISOString() : null,
      end_date: endDate ? new Date(endDate).toISOString() : null,
      start_time: startTime,
      end_time: endTime,
      days: dayStatus,
    });
  }

  const payload = {
    title: title,
    schedule_type: type,
    priority: priority,
    property_id: sessionStorage.getItem("propertyId"),
    periods: periods,
  };
  if (schedule_id) {
    const convertingFromCustomToWeekly= allCalendarEvents.find(ele=>ele.uuid==schedule_id);
    if(convertingFromCustomToWeekly?.uuid){
      payload["id"] = schedule_id;
      payload["add_weekly_schedule"] = true;
    }else {
      payload["id"] = schedule_id;
      payload["edit_weekly_schedule"] = true;
    }
  } else {
    payload["add_weekly_schedule"] = true;
  }

  scheduleDataRequest(payload);
}

// Add New Row with Delete Button
function addNewRowForScheduleTable() {
  const table = document
    .getElementById("Schedule_table")
    .querySelector("tbody");
  const lastRow = table.lastElementChild;
  const lastPeriodNumber = parseInt(
    lastRow.querySelector("td[data-period]").getAttribute("data-period")
  );
  const newPeriodNumber = lastPeriodNumber + 1;

  const newRow = document.createElement("tr");
  newRow.innerHTML = `
    <td style="vertical-align: middle;" data-period="${newPeriodNumber}">Period ${newPeriodNumber}</td>
    <td style="vertical-align: middle;">
      <input type="date" name="dayStartDate" id="dayStartDate" oninput="validateTime(this,false)" class="form-control" />
    </td>
    <td style="vertical-align: middle;">
      <input type="date" id="dayEndDate" name="dayEndDate" oninput="validateTime(this,false)" class="form-control" />
    </td>
    <td style="vertical-align: middle;">
      <input type="time" name="start_time" oninput="validateTime(this,true)" class="form-control" />
    </td>
    <td style="vertical-align: middle;">
      <input type="time" name="end_time" oninput="validateTime(this,true)" class="form-control" />
    </td>
    ${["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
      .map(
        (day) => `
      <td style="vertical-align: middle; text-align: center;">
        <input id="${day}_check_period_${newPeriodNumber}" type="checkbox" onchange="checkDayIsInGivenDates(this)">
      </td>
    `
      )
      .join("")}
    <td style="vertical-align: middle; text-align: center;">
      <button type="button" class="btn btn-danger btn-sm" onclick="deleteScheduleRow(this)">Delete</button>
    </td>
  `;
  table.appendChild(newRow);
}

// **Validation Function**
function validateTime(input, isTime = true) {
  const row = input.closest("tr");
  let startTimeInput = '';
  let endTimeInput = '';
  
  if(isTime) {
    startTimeInput = row.querySelector('input[name="start_time"]');
    endTimeInput = row.querySelector('input[name="end_time"]');
    
    if (startTimeInput.value && endTimeInput.value && startTimeInput.value >= endTimeInput.value) {
      showScheduleToastMessage("Start time cannot be greater than or equal to End time!");
      input.value = "";
      return false;
    }
  } else {
    startTimeInput = row.querySelector('input[name="dayStartDate"]');
    endTimeInput = row.querySelector('input[name="dayEndDate"]');
    
    if (startTimeInput.value && endTimeInput.value) {
      const startDate = new Date(startTimeInput.value);
      const endDate = new Date(endTimeInput.value);
      if (startDate > endDate) {
        showScheduleToastMessage("Start date cannot be greater than End date!");
        input.value = "";
        return false;
      }
    }
  }
  // const checkboxes = row.querySelectorAll('input[type="checkbox"]');
  // checkboxes.forEach(checkbox => {
  //   checkbox.checked = false;
  //   console.log("is it unchcecking it ");
    
  // });
  return true;
}

// Delete Row
function deleteScheduleRow(button) {
  const tbody = document.querySelector("#Schedule_table tbody");
  const rows = tbody.querySelectorAll("tr");
  if (rows.length === 1) {
    showScheduleToastMessage(
      "At least one period is required. You cannot delete the last period."
    );
    return;
  }
  const row = button.closest("tr");
  row.remove();
  updatePeriodNumbers();
}

function updatePeriodNumbers() {
  const rows = document.querySelectorAll("#Schedule_table tbody tr");
  rows.forEach((row, index) => {
    const periodNumber = index + 1;
    row.querySelector("td[data-period]").textContent = `Period ${periodNumber}`;
    row
      .querySelector("td[data-period]")
      .setAttribute("data-period", periodNumber);

    // Update checkbox IDs to keep them unique
    ["sun", "mon", "tue", "wed", "thu", "fri", "sat"].forEach((day) => {
      const checkbox = row.querySelector(`input[id^="${day}_check_period_"]`);
      if (checkbox) {
        checkbox.id = `${day}_check_period_${periodNumber}`;
      }
    });
  });
}

function editCalendarSchedule(id, schedule_uuid = null) {
  if (schedule_uuid) {
    editCustomSchedule(schedule_uuid);
    return;
  }
  addSwitchForWeeklyCalendarView(true);
  changeWeeklyView();

  const schedule = allCalendarEvents.find((ele) => ele?.schedule_id == id);
  document.getElementById("isWeeklyViewEle").checked = true;
  document.getElementById("schedule_title").value = schedule.title;
  document.getElementById("schedule_type").value = schedule.schedule_type;
  document.getElementById("schedule_priority").value = schedule.backgroundColor;
  document.getElementById("schedule_id").value = schedule.schedule_id;

  const periodsTableBody = document.querySelector("#Schedule_table tbody");
  periodsTableBody.innerHTML = "";

  schedule.periods.forEach((period, index) => {
    const periodNumber = index + 1;
    
    const localStartDate = period.start_date ? new Date(period.start_date).toLocaleDateString('en-CA') : '';
    const localEndDate = period.end_date ? new Date(period.end_date).toLocaleDateString('en-CA') : '';
    const rowContent = `
      <tr>
        <td data-period="${periodNumber}">Period ${periodNumber}</td>
        <td><input type="date" name="dayStartDate" class="form-control" value="${localStartDate}" /></td>
        <td><input type="date" name="dayEndDate" class="form-control" value="${localEndDate}" /></td>
        <td><input type="time" name="start_time" class="form-control" value="${period.start_time}" /></td>
        <td><input type="time" name="end_time" class="form-control" value="${period.end_time}" /></td>
        ${["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
          .map((day) => {
            const isActive = period.days[day]?.is_active;
            const dayId = period.days[day]?.day_id || "";
            return `
              <td>
                <input 
                  type="checkbox" 
                  id="${day}_check_period_${periodNumber}" 
                  ${isActive ? "checked" : ""} 
                  data-day-id="${dayId}"
                  onchange="checkDayIsInGivenDates(this)"
                />
              </td>
            `;
          })
          .join("")}
        <td><button type="button" class="btn btn-danger btn-sm delete-schedule-row-btn">Delete</button></td>
      </tr>
    `;

    // Wrap the row in a table structure for proper sanitization
    const wrappedRow = `<table><tbody>${rowContent}</tbody></table>`;

    // Sanitize with specific configuration
    const cleanWrapped = DOMPurify.sanitize(wrappedRow, {
      ADD_ATTR: ['data-period', 'data-day-id', 'onchange', 'type', 'name', 'id', 'class', 'value', 'checked'],
      ADD_TAGS: ['input', 'button', 'td', 'tr', 'table', 'tbody'],
      ALLOW_DATA_ATTR: true
    });

    // Extract the sanitized row content
    const sanitizedRow = $(cleanWrapped).find("tbody").html();

    // Append to the table
    periodsTableBody.innerHTML += sanitizedRow;
  });
  bindScheduleTableEvents();

  openCreateCalendarEventModal(false, false);
}

function bindScheduleTableEvents() {
  const $table = $("#Schedule_table tbody");
  $table.off("input", 'input[type="time"]');
  $table.off("click", ".delete-schedule-row-btn");
  $table.on("input", 'input[type="time"]', function () {
    validateTime(this);
  });
  $table.on("click", ".delete-schedule-row-btn", function () {
    deleteScheduleRow(this);
  });
}

function showScheduleToastMessage(errorMessage) {
  document.getElementById("scheduleToastMessage").style.display = "block";
  document.getElementById("scheduleToastErrorMessage").textContent =
    errorMessage;
  var toastEl = document.getElementById("scheduleToast");
  var toast = new bootstrap.Toast(toastEl, {
    delay: 3000,
    autohide: false,
  });
  toast.show();

  setTimeout(() => {
    closeScheduleToastMessage();
  }, 3000);
}

function closeScheduleToastMessage() {
  const toastEl = document.getElementById("scheduleToastMessage");
  toastEl.style.display = "none";
}

function submitCustomScheduleData() {
  const title = document.getElementById("schedule_title").value;
  const type = document.getElementById("schedule_type").value;
  const priority = document.getElementById("schedule_priority").value;
  const schedule_id = document.getElementById("schedule_id").value;
  dateValue = $("#reservationtime").val();
  if (!title || !type || !priority || !dateValue) {
    showScheduleToastMessage(
      "Please fill in all the required fields in the General section."
    );
    return;
  }

  var dates = dateValue.split(" - ");
  var startDate = dates[0] ? new Date(dates[0]).toISOString() : null;
  var endDate = dates[1] ? new Date(dates[1]).toISOString() : null;
  const payload = {
    title: title,
    schedule_type: type,
    backgroundColor: priority,
    borderColor: priority,
    start: startDate,
    end: endDate,
    property_id: sessionStorage.getItem("propertyId"),
  };
  if (schedule_id) {
    const weeklyRecord=allCalendarEvents.find(ele=>ele?.schedule_id==schedule_id);
    if(weeklyRecord){
      payload["add_custom_calendar_schedule_request"] = true;
      payload["id"] = schedule_id;
    }else {
      payload["edit_custom_calendar_schedule_request"] = true;
      payload["id"] = schedule_id;
    }
  } else {
    payload["add_custom_calendar_schedule_request"] = true;
  }
  scheduleDataRequest(payload);
}

function editCustomSchedule(uuid) {
  addSwitchForWeeklyCalendarView(false);
  changeWeeklyView();
  const schedule = allCalendarEvents.find((ele) => ele?.uuid == uuid);
  document.getElementById("schedule_title").value = schedule?.title;
  document.getElementById("schedule_type").value = schedule?.schedule_type;
  document.getElementById("schedule_priority").value =
    schedule?.backgroundColor;
  document.getElementById("schedule_id").value = schedule?.uuid;
  document.getElementById("isWeeklyViewEle").checked = false;
  setTimeout(() => {
    let startDate = new Date(schedule.start);
    let endDate = new Date(schedule.end);
    let formattedStartDate = moment(startDate).format("MM/DD/YYYY hh:mm A");
    let formattedEndDate = moment(endDate).format("MM/DD/YYYY hh:mm A");
    $("#reservationtime").val(`${formattedStartDate} - ${formattedEndDate}`);
  }, 1000);
  openCreateCalendarEventModal(false, false);
  changeWeeklyView();
}

function addSwitchForWeeklyCalendarView(isActive) {
  const switchContainer = document.getElementById("changeCalendarTypeViewEleContainer");
  switchContainer.innerHTML = "";
  if (isActive) {
    switchContainer.innerHTML = `<label for="isWeeklyViewEle">Weekly:</label>
        <input type="checkbox" checked id="isWeeklyViewEle" onchange="changeWeeklyView()" data-on-text="On" data-off-text="Off" data-on-color="success" data-off-color="danger">`;
  } else {
    switchContainer.innerHTML = `<label for="isWeeklyViewEle">Weekly:</label>
        <input type="checkbox" id="isWeeklyViewEle" onchange="changeWeeklyView()" data-on-text="On" data-off-text="Off" data-on-color="success" data-off-color="danger">`;
  }
  $("#isWeeklyViewEle").bootstrapSwitch();
}

function changeWeeklyView() {
  const custom_date_schedule_view = document.getElementById(
    "custom_date_schedule_view"
  );
  const weekly_schedule = document.getElementById("weekly_schedule");
  const isWeeklyViewEle = document.getElementById("isWeeklyViewEle").checked;
  if (isWeeklyViewEle) {
    weekly_schedule.style.display = "block";
    custom_date_schedule_view.style.display = "none";
  } else {
    weekly_schedule.style.display = "none";
    custom_date_schedule_view.style.display = "block";
  }
}

function checkDayIsInGivenDates(checkbox) {
  const row = checkbox.closest('tr');
  const startTimeInput = row.querySelector('input[name="dayStartDate"]');
  const endTimeInput = row.querySelector('input[name="dayEndDate"]');
  
  // if (!startTimeInput.value || !endTimeInput.value) {
  if (!startTimeInput.value) {
    showScheduleToastMessage("Please select both start and end dates first");
    checkbox.checked = false;
    return false;
  }

  const startDate = new Date(startTimeInput.value);
  let endDate = null;
  if(!endTimeInput.value) {
    // endTimeInput.value = startTimeInput.value;
    endDate = new Date(startDate);
    endDate.setDate(startDate.getDate() + 7); // Add 7 days
  }else endDate = new Date(endTimeInput.value);
  const dayMap = {
    'sun': 0,
    'mon': 1,
    'tue': 2,
    'wed': 3,
    'thu': 4,
    'fri': 5,
    'sat': 6
  };

  const day = checkbox.id.split('_')[0];
  const dayNumber = dayMap[day];

  let currentDate = new Date(startDate);
  let dayExists = false;
  
  while (currentDate <= endDate) {
    if (currentDate.getDay() === dayNumber) {
      dayExists = true;
      break;
    }
    currentDate.setDate(currentDate.getDate() + 1);
  }
  
  if (!dayExists) {
    showScheduleToastMessage(`Selected day (${day}) is outside the date range`);
    checkbox.checked = false;
    return false;
  }

  return true;
}