let selectedDoorImage = "";
let selectedDoorFile = null;
let all_doors = [];
let allHardwareDoorSettings = [];
let allSchedulesData = [];
let DoorIdOfCommandCenter = undefined;
let isCardView = false;

$(document).ready(async function () {
  $('#AddGroupModal').on('hidden.bs.modal', function () {
    if ($('.modal.show').length > 0) {
        $('body').addClass('modal-open');
    }
  });
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData =await parseJSONData(sessionPreferences);
    preferencesData?.is_card_view==1? isCardView = true:isCardView = false;
  }else {
    const preferences = await asyncGetPreferencesRequestForView({
      get_preferences_for_property_user: true,
      property_id: sessionStorage.getItem("propertyId"),
    });
    if(preferences?.length>0) sessionStorage.setItem("preferences",JSON.stringify(preferences[0])); 
    if(preferences?.length>0 && preferences[0]?.is_card_view==1) isCardView = true;
  }
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
  const property_id = sessionStorage.getItem("propertyId");
  sendDoorsRequest({
    getDoorsRequest: true,
    property_id: property_id,
  });
  sendDoorsRequest({
    GetDoorsGroupRequest: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
  sendDoorsRequest({
    get_camera_request: true,
    property_id,
  });
  sendHardwareSettingsRequest({
    get_signal_wire_credentials: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
});

function sendHardwareSettingsRequest(data) {
  $.ajax({
    url: "/include/property_builder/hardwares/hardwares_request.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.EditHardwareSettingsRequest) {
        if (DoorIdOfCommandCenter)
          openDoorCommandCenterDialog(DoorIdOfCommandCenter);
        else window.location.reload();
      }else if (data?.get_signal_wire_credentials) {
        if (resp?.data?.length) {
          signalWireCredentials = resp?.data[0];
          sendHardwareSettingsRequest({
            get_signal_wire_numbers: true,
            signalWireId: signalWireCredentials?.id
          });
        } else allSignalWireNumbers = [];
      }else if (data?.get_signal_wire_numbers) {
        allSignalWireNumbers = resp?.data;
        populateNumbersInDoors(allSignalWireNumbers);
      }
    },
    error: function (xhr, status, error) {
      isLoadingNow(false);
    },
  });
}

function sendDoorsRequest(data) {
  $.ajax({
    url: "/include/property_builder/doors/doors_requests.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.getDoorsRequest) {
        all_doors = resp.data;
        if (window.innerWidth <= 600){
          createDoorCardPreview(all_doors);
          return;
        }else if(isCardView) createDoorCardPreview(all_doors);
        else createDoorTablePreview(all_doors);
      }
      if (data?.getDoorByIdRequest) {
        addNewDoorForm(resp.data);
      }
      if (
        data?.deleteDoorByIdRequest ||
        data?.update_Gate_door_request ||
        data?.add_Gate_door_request
      ) {
        CancelDoorForm();
        window.location.reload();
        // sendDoorsRequest({
        //   getDoorsRequest: true,
        //   property_id: sessionStorage.getItem("propertyId"),
        // });
      }
      if (data?.addGroupRequest) {
        $("#AddGroupModal").modal("hide");
        showSuccessGlobalToastMessage(resp?.message||"Added");
        sendDoorsRequest({
          GetDoorsGroupRequest: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
      if (data?.GetDoorsGroupRequest) {
        addGroupsOptions(resp.data);
      }else if (data?.deleteGroupRequest || data?.editDoorGroup) {
        showSuccessGlobalToastMessage(resp?.message||"Deleted");
        sendDoorsRequest({
          getDoorsRequest: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
        sendDoorsRequest({
          GetDoorsGroupRequest: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
      if (data?.get_camera_request) {
        populateCameraSelect(resp.data);
      }
      if (data?.add_camera_to_door_request) {
        $("#add_camera_to_door_modal").modal("hide");
        showSuccessGlobalToastMessage("Door updated with camera successfully");
        sendDoorsRequest({
          getDoorsRequest: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
      if (data?.removeDoorFromGroupRequest) {
        showSuccessGlobalToastMessage("Door removed from group.");
        sendDoorsRequest({
          getDoorsRequest: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
      if (data?.quick_change_group_by_request) {
        showSuccessGlobalToastMessage(resp?.message || "Request completed");
        $("#AddQuickGroupModalToDoor").modal("hide");
        sendDoorsRequest({
          getDoorsRequest: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error?.includes("FOREIGN KEY (`assigned_door`)")) {
        showErrorGlobalToastMessage(
          "This is being controlled by hardware. please first delete the hardware. Go to hardware tab and delete this door"
        );
        return;
      }
      if (xhr?.responseJSON?.error)
        showErrorGlobalToastMessage(xhr?.responseJSON?.error);
      else showErrorGlobalToastMessage(error);
    },
  });
}

function removeDoorFromGroup(doorId) {
  if (!doorId) return;

  showConfirmModal("Are you sure you want to remove this door from its group?", () => {
    sendDoorsRequest({
      removeDoorFromGroupRequest: true,
      property_id:sessionStorage.getItem('propertyId'),
      door_id: doorId
    });
  });
}

function createDoorCardPreview(dataArray) {
  let data = dataArray;

  let groupedData = data.reduce((acc, item) => {
    let group = item.group_by || "Ungrouped";
    if (!acc[group]) acc[group] = [];
    acc[group].push(item);
    return acc;
  }, {});

  $("#Door_Table").empty();

  if (!dataArray || dataArray.length === 0) {
    const searchValue = document.getElementById("search_door_value")?.value;
    let noDataHtml = "";
    
    if (searchValue && searchValue.trim() !== "") {
      noDataHtml = `
        <div class="no-data-card" style="text-align: center; margin: 20px;">
          <div class="card">
            <div class="card-body">
              <h5 class="card-text">No Doors Found</h5>
              <p class="card-text">No doors found matching "${searchValue}".</p>
            </div>
          </div>
        </div>`;
    } else {
      noDataHtml = `
        <div style="display:flex; justify-content:center; align-items:center; width:100%;">
          <div class="text-center p-4">
            <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
            <h5 class="text-muted">No Doors Found</h5>
            <p class="text-muted">There are no doors to display.</p>
          </div>
        </div>`;
    }

    $("#Door_Table").html(DOMPurify.sanitize(noDataHtml));
    return;
  }

  Object.keys(groupedData).forEach((groupName) => {
    let groupHtml = `
      <div class="group-card-container">
        <h3 class="pt-4 text-bold">${groupName}</h3>
        <div class="row can_ban_view">
    `;

    let groupItems = groupedData[groupName];

    if (groupItems.length === 0) {
      groupHtml += `
        <div class="col-12 text-center">
          <p>No data available</p>
        </div>
      `;
    } else {
      groupItems.forEach((item) => {
        let door_image = "/include/images/door_image.png";
        if(item?.type == "Gate") door_image = "/include/images/gate_image.png";
        if(item?.door_image) door_image  = `/shared/serve_image.php?path=${item?.door_image}&type=all_images`;
        groupHtml += `
          <div class="col-lg-6 col-md-12 col-sm-12">
            <div class="card mb-3">
              <div class="card-header d-flex align-items-center">
                <div class="door_image_container">
                  <img src="${door_image}" alt="Door Image" class="img-thumbnail door-image-clickable" style="width: 60px; height: 60px; margin-right: 10px; cursor: pointer;" title="Click to view larger image" data-image='${door_image}' data-name='${item?.door_name || 'Door'}'>
                </div>
                <h5 class="mb-0">${item?.door_name || "Unknown Door"}</h5>
                <div class="ml-auto">
                  <i class='fas fa-edit text-primary mx-1 edit-door-btn cursor_pointer' data-id='${item.id}' title='Edit Door'></i>
                  <i class='fas fa-trash-alt text-danger mx-1 delete-door-btn cursor_pointer' data-id='${item.id}' title='Delete Door'></i>
                  <i class='fas fa-video text-info mx-1 add-camera-btn cursor_pointer' data-id='${item.id}' title='Add Camera'></i>
                  ${
                    groupName !== 'Ungrouped'
                      ? `<i class='fas fa-unlink text-warning mx-1 remove-from-group-btn cursor_pointer' data-id='${item.id}' title='Remove from Group'></i>`
                      : `<i class="fa-solid fa-link text-success add-group-btn cursor_pointer" data-id='${item.id}' title='Add Group'></i>`
                  }
                </div>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6">
                    <p><strong>Door Key:</strong> ${item?.door_key || "N/A"}</p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>Location:</strong> ${item?.location || "N/A"}</p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>Camera Name:</strong> ${
                      item?.cameraName || "N/A"
                    }</p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>Phone Number:</strong> ${
                      item?.iiNumber || "N/A"
                    }</p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>Type:</strong> ${item?.type || "N/A"}</p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>Primary:</strong> ${
                      item?.is_primary == 1
                        ? "<i class='fas fa-check-circle text-success' title='Primary'></i>"
                        : "<i class='fas fa-times-circle text-danger' title='Not Primary'></i>"
                    }</p>
                  </div>
                  <div class="col-md-12">
                    <p><strong>Description:</strong> ${
                      item?.description || "No description provided."
                    }</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        `;
      });
    }

    groupHtml += `
        </div> <!-- End of row -->
      </div> <!-- End of group-card-container -->
    `;

    $("#Door_Table").append(DOMPurify.sanitize(groupHtml));
  });
  bindDoorTableEvents();
}

function createDoorTablePreview(dataArray) {
  let data = dataArray;
  let groupedData = data.reduce((acc, item) => {
    let group = item.group_by || "Ungrouped"; // Handle empty group_by as "Ungrouped"
    if (!acc[group]) acc[group] = [];
    acc[group].push(item);
    return acc;
  }, {});

  if (!dataArray || dataArray.length === 0) {
    const searchValue = document.getElementById("search_door_value")?.value;
    let noDataHtml = "";
    
    if (searchValue && searchValue.trim() !== "") {
      noDataHtml = `
        <div style="display:flex; justify-content:center; align-items:center; width:100%;">
          <div class="text-center p-4">
            <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
            <h5 class="text-muted">No Doors Found</h5>
            <p class="text-muted">No doors found matching "${searchValue}"</p>
          </div>
        </div>`;
    } else {
      noDataHtml = `
        <div style="display:flex; justify-content:center; align-items:center; width:100%;">
          <div class="text-center p-4">
            <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
            <h5 class="text-muted">No Doors Found</h5>
            <p class="text-muted">There are no doors to display.</p>
          </div>
        </div>`;
    }
    
    $("#Door_Table").html(DOMPurify.sanitize(noDataHtml));
    return;
  }

  // Clear the main container
  $("#Door_Table").empty();

  // Loop through each group and generate a table for that group
  Object.keys(groupedData).forEach((groupName) => {
    let groupHtml = `
    <div class="card" style="width:100%;">
      <div class="card-header">
        <h3 class="card-title">${groupName}</h3>
      </div>
      <div class="card-body">
      <div class="group-table-container">
        <h3 class="pt-4 text-bold"></h3>
        <div class="table-responsive doors_table">
          <table class="doors_data_table table table-bordered table-head-fixed text-nowrap table-hover" id="my_doors_gates_tab">
            <thead>
              <tr>
                <th>Door Image</th>
                <th>Door Name</th>
                <th>Key</th>
                <th>Location</th>
                <th>Camera</th>
                <th>Number</th>
                <th>Type</th>
                <th>Primary</th>
                <th>Description</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
    `;

    let groupItems = groupedData[groupName];

    if (groupItems.length === 0) {
      groupHtml +=
        "<tr><td colspan='10' class='text-center'>No data available</td></tr>";
    } else {
      groupItems.forEach(function (item) {
        let door_image = "/include/images/door_image.png";
        if(item?.type == "Gate") door_image = "/include/images/gate_image.png";
        if(item?.door_image) door_image  = `/shared/serve_image.php?path=${item?.door_image}&type=all_images`;
        groupHtml += `
          <tr>
            <td style="vertical-align: middle;">
              <div class="door_image_container"> 
                <img src="${ door_image }" alt="door image" class="img-thumbnail door-image-clickable " style="cursor: pointer;" title="Click to view larger image"  data-image='${door_image}' data-name='${item?.door_name || 'Door'}'>
              </div>
            </td>
            <td style="vertical-align: middle;">${item?.door_name || ""}</td>
            <td style="vertical-align: middle;">${item?.door_key ?? ""}</td>
            <td style="vertical-align: middle;">${item?.location || ""}</td>
            <td style="vertical-align: middle;">${item?.cameraName || ""}</td> 
            <td style="vertical-align: middle;">${item?.iiNumber || ""}</td>
            <td style="vertical-align: middle;">${item?.type || ""}</td>
            <td style="vertical-align: middle; text-align:center">
              ${
                item?.is_primary == 1
                  ? "<i class='fas fa-check-circle text-success' title='Primary'></i>"
                  : "<i class='fas fa-times-circle text-danger' title='Not Primary'></i>"
              }
            </td>

            <td style="vertical-align: middle;">${item?.description || ""}</td>
            <td style="vertical-align: middle;">
              <i class='fas fa-edit text-primary mx-1 edit-door-btn cursor_pointer' data-id='${item.id}' title='Edit Door'></i>
              <i class='fas fa-trash-alt text-danger mx-1 delete-door-btn cursor_pointer' data-id='${item.id}' title='Delete Door'></i>
              <i class='fas fa-video text-info mx-1 add-camera-btn cursor_pointer' data-id='${item.id}' title='Add Camera'></i>
              ${
                groupName !== 'Ungrouped'
                  ? `<i class='fas fa-unlink text-warning mx-1 remove-from-group-btn cursor_pointer' data-id='${item.id}' title='Remove from Group'></i>`
                  : `<i class="fa-solid fa-link text-success add-group-btn cursor_pointer" data-id='${item.id}' title='Add Group'></i>`
              }
            </td>
          </tr>
        `;
      });
    }

    groupHtml += `
            </tbody>
          </table>
        </div>
      </div>
      </div>
      </div>
    `;

    // Append each group table to the container
    $("#Door_Table").append(DOMPurify.sanitize(groupHtml));
    $("#my_doors_gates_tab").each(function () {
      if (!$.fn.DataTable.isDataTable(this)) {
        $(this).DataTable({
          responsive: true,
          scrollCollapse: true,
          ordering: true,
          order: [],
          columnDefs: [
            { orderable: false, targets: -1 }, // Make last column not sortable
          ],
          paging: false,
          searching: false,
        });
      } else if (data?.length > 0) {
        $(this).DataTable().order([]).draw();
      }
    });
  });

  bindDoorTableEvents();
}

function bindDoorTableEvents() {
  // Unbind delegated events on #Door_Table
  $('#Door_Table')
    .off('click', '.edit-door-btn')
    .off('click', '.delete-door-btn')
    .off('click', '.add-camera-btn')
    .off('click', '.remove-from-group-btn')
    .off('click', '.add-group-btn')
    .off('click', '.door-image-clickable');

  // Unbind non-delegated/static events
  // $('#changeDoorViewEle').off('change');
  $('#search_door_value').off('keyup');
  $('#door_number').off('change');
  $('#fileInput').off('change');
  $('#cancelButton').off('click');
  $('[data-action="addNewDoorForm"]').off('click');

  // Re-bind events
  // $('#changeDoorViewEle').on('change', changeDoorView);
  $('#search_door_value').on('keyup', searchDoor);
  $('#door_number').on('change', handle_change_add_number_door);
  $('#fileInput').on('change', onDoorFileChange);
  $('#cancelButton').on('click', CancelDoorForm);
  $('[data-action="addNewDoorForm"]').on('click', addNewDoorForm);

  $('#Door_Table').on('click', '.edit-door-btn', function () {
    const id = $(this).data('id');
    editDoor(id);
  });

  $('#Door_Table').on('click', '.delete-door-btn', function () {
    const id = $(this).data('id');
    deleteDoorById(id);
  });

  $('#Door_Table').on('click', '.add-camera-btn', function () {
    const id = $(this).data('id');
    add_camera_to_door(id);
  });

  $('#Door_Table').on('click', '.remove-from-group-btn', function () {
    const id = $(this).data('id');
    removeDoorFromGroup(id);
  });

  $('#Door_Table').on('click', '.add-group-btn', function () {
    const id = $(this).data('id');
    openAddQuickGroupModalToDoor(id);
  });

  $('#Door_Table').on('click', '.door-image-clickable', function () {
    const image = $(this).data('image');
    const name = $(this).data('name');
    showEnlargedDoorImage(image, name);
  });
}

async function add_camera_to_door(door_id) {
  let selected_door = all_doors.find((ele) => ele.id == door_id);
  const selectedCameras = await sendDoorPromiseRequest({
    get_selected_cameras_request: true,
    door_id,
  });
  document.getElementById("door_id_for_camera").value = selected_door?.id || "";
  let selectedCameraIds = selectedCameras.map((camera) =>
    String(camera.camera_id)
  );
  $("#add_camera_to_door_modal").modal("show");
  $("#camera_select").val(selectedCameraIds).trigger("change");
}

async function sendDoorPromiseRequest(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/property_builder/doors/doors_requests.php",
      type: "POST",
      data,
      success: function (resp) {
        resolve(resp.data);
      },
      error: function (xhr, status, error) {
        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
        else reject(error);
      },
    });
  });
}

function populateCameraSelect(cameras) {
  const cameraSelect = document.getElementById("camera_select");
  cameraSelect.innerHTML = "";
  // '<option value="" disabled >Select camera</option>';

  // Populate options
  cameras.forEach((camera) => {
    const option = document.createElement("option");
    option.value = camera.id;
    option.textContent = `${camera.cameraName} (${camera.cameraModel})`;
    cameraSelect.appendChild(option);
  });

  $(`#camera_select`).select2({
    theme: "bootstrap4",
    placeholder: "Select cameras",
    allowClear: true,
  });
}

function add_camera_to_door_submit(event) {
  event.preventDefault();
  const door_id = document.getElementById("door_id_for_camera").value;
  const cameraSelect = document.getElementById("camera_select");
  const camera_ids = Array.from(cameraSelect.selectedOptions).map(
    (option) => option.value
  );
  let payload = {
    camera_id: camera_ids?.length > 0 ? camera_ids[0] : "",
    id: door_id,
    add_camera_to_door_request: true,
    all_cameras: JSON.stringify(camera_ids),
  };
  sendDoorsRequest(payload);
}

function editDoor(id) {
  sendDoorsRequest({ getDoorByIdRequest: true, id });
}

function deleteDoorById(id) {
  showConfirmModal("Are you sure you want to delete?", function () {
    sendDoorsRequest({
      deleteDoorByIdRequest: true,
      id,
      property_id: sessionStorage.getItem("propertyId"),
    });
  });
}

function addGroupsOptions(data) {
  const selectEle = document.getElementById("group_by");
  selectEle.innerHTML = "<option value=''>Please Select group</option>";
  if (data?.length > 0) {
    data.forEach((option) => {
      const Option = document.createElement("option");
      Option.value = option.groupName;
      Option.textContent = option.groupName;
      selectEle.appendChild(Option);
    });
  }
  // ======== adding the groups for quick change=====
  const quick_change_group_by = document.getElementById("quick_change_group_by");
  quick_change_group_by.innerHTML = "<option value=''>Please Select</option>";
  if (data?.length > 0) {
    data.forEach((option) => {
      const Option = document.createElement("option");
      Option.value = option.groupName;
      Option.textContent = option.groupName;
      quick_change_group_by.appendChild(Option);
    });
  }
  updateDoorGroupList(data);
}

function addNewDoorForm(data = {}) {
  // const form_container = document.getElementById("doors_form_view");
  // const view_container = document.getElementById("doors_view");
  $("#add_door_modal").modal("show");
  
  document.getElementById("is_primary").checked = data?.is_primary || false;
  document.getElementById("doorId").value = data?.id || "";
  document.getElementById("group_by").value = data?.group_by || "";
  document.getElementById("door_name").value = data?.door_name || "";
  document.getElementById("location_door").value = data?.location || "";
  document.getElementById("door_number").value = data?.iiNumber || "";
  document.getElementById("doorType").value = data?.type || "";
  document.getElementById("door_key").value = data?.door_key || "";
  document.getElementById("description").value = data?.description || "";
  let door_image="/include/images/door_image.png";
  if(data?.door_image) door_image  = `/shared/serve_image.php?path=${data?.door_image}&type=all_images`;
  document.getElementById("selectedImage").src = door_image;
  selectedDoorImage = null;
}
let debounceTimer;

function searchDoor() {
  if(!isCardView){
    searchTable('my_doors_gates_tab', 'search_door_value');
    return;
  }
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    const searchInput = document.getElementById("search_door_value");
    if (!searchInput) {
      console.warn("Search input not found: search_door_value");
      return;
    }
    
    const searchValue = searchInput.value.toLowerCase();
    let matchedDoors = all_doors.filter(
      (event) =>
        !searchValue ||
        Object.values(event).some(
          (field) =>
            field && field.toString().toLowerCase().includes(searchValue)
        )
    );
    
    // Re-render based on current view
    if (window.innerWidth <= 600 || isCardView) {
      createDoorCardPreview(matchedDoors);
    } else {
      createDoorTablePreview(matchedDoors);
    }
  }, 300);
}

function CancelDoorForm() {
  $("#add_door_modal").modal("hide");
  const form_container = document.getElementById("doors_form_view");
  const view_container = document.getElementById("doors_view");
  view_container.style.display = "block";
  form_container.style.display = "none";
}

function openDoorGroupManagementModal() {
    // Remove any existing modal-open class and backdrop
    $('body').removeClass('modal-open');
    $('.modal-backdrop').remove();
    
    // Show the management modal
    $("#DoorGroupManagementModal").modal({
        backdrop: 'static',
        keyboard: false
    });
}

function openAddGroupModal(groupName = '', groupId = '') {
    // First hide the group management modal
    $("#DoorGroupManagementModal").modal("hide");
    
    // Then show the add group modal
    const modal = $("#AddGroupModal");
    const title = modal.find('.modal-title');
    const groupNameInput = document.getElementById("groupName");
    const doorGroupIdInput = document.getElementById("doorGroupId");
    
    if (groupName) {
        title.text("Edit Group");
        groupNameInput.value = groupName;
        // doorGroupIdInput.value = groupId;
    } else {
        title.text("Add Group");
        groupNameInput.value = '';
        doorGroupIdInput.value = '';
    }
    
    modal.modal({
        backdrop: 'static',
        keyboard: false
    });
}

// Add event listener for when AddGroupModal is hidden
$('#AddGroupModal').on('hidden.bs.modal', function () {
    // Show the group management modal again
    $("#DoorGroupManagementModal").modal({
        backdrop: 'static',
        keyboard: false
    });
});

// Add event listener for when DoorGroupManagementModal is hidden
$('#DoorGroupManagementModal').on('hidden.bs.modal', function () {
    // Ensure the parent modal is still scrollable
    $('body').addClass('modal-open');
    if ($('.modal.show').length > 0) {
        $('body').addClass('modal-open');
    }
});

function AddGroup(event) {
    event.preventDefault(); // Prevent page refresh
    let groupName = document.getElementById("groupName").value;
    let doorGroupId = document.getElementById("doorGroupId").value;
    
    if (!groupName) {
        showErrorGlobalToastMessage("Group name is required");
        return;
    }
    
    if(doorGroupId) {
        sendDoorsRequest({
            newGroupName: groupName,
            editDoorGroup: true,
            id: doorGroupId,
            property_id: sessionStorage.getItem("propertyId"),
        });
    } else {
        sendDoorsRequest({
            groupName,
            addGroupRequest: true,
            property_id: sessionStorage.getItem("propertyId"),
        });
    }
    
    // Close the modal after sending request
    $("#AddGroupModal").modal("hide");
}

function AddDoorGroupToDatabase(event) {
  event.preventDefault();
  let doorId = document.getElementById("doorId").value;
  const propertyId = sessionStorage.getItem("propertyId");
  if (!propertyId) {
    showErrorGlobalToastMessage("Please select the property from sidebar");
    return;
  }
  const formData = new FormData();
  formData.append("group_by", document.getElementById("group_by").value);
  formData.append("door_name", document.getElementById("door_name").value);
  formData.append("location", document.getElementById("location_door").value);
  formData.append("door_key", document.getElementById("door_key").value);
  formData.append("type", document.getElementById("doorType").value);
  formData.append("iiNumber", document.getElementById("door_number").value);
  formData.append("property_id", propertyId);
  formData.append("description", document.getElementById("description").value);
  const is_primary = document.getElementById("is_primary").checked;
  formData.append("is_primary", is_primary ? 1 : 0);
  if (selectedDoorFile) {
    formData.append("door_image", selectedDoorFile);
  }
  if (doorId) {
    formData.append("is_primary", is_primary ? 1 : 0);
    formData.append("update_Gate_door_request", "true");
    formData.append("id", doorId);
  } else {
    formData.append("add_Gate_door_request", "true");
  }
  sendDoorsRequestForAddUpdate(formData);

}


function sendDoorsRequestForAddUpdate(data) {
  $.ajax({
    url: "/include/property_builder/doors/doors_requests.php",
    type: "post",
    data,
    processData: false,
    contentType: false,
    success: function (resp) {
      CancelDoorForm();
      window.location.reload();
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error)
        showErrorGlobalToastMessage(xhr?.responseJSON?.error);
      else showErrorGlobalToastMessage(error);
    },
  });
}

function onDoorFileChange(event) {
  const file = event.target.files[0]; // Get the selected file
  if (file) {
    const reader = new FileReader();
    reader.onload = function (e) {
      const image = document.getElementById("selectedImage");
      selectedDoorImage = e.target.result;
      image.src = selectedDoorImage; // Set the image src to the loaded file
    };
    selectedDoorFile=file;
    reader.readAsDataURL(file); // Read the file as a data URL
  }
}

function parseString(stringifyData) {
  try {
    const decodedData = stringifyData.replace(/&quot;/g, '"');
    return JSON.parse(decodedData);
  } catch (error) {
    return "";
  }
}

async function fetchChangedDataForItem(deviceUrl, statusChange = false) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/property_builder/hardwares/hardwares_request.php",
      type: "POST",
      data: { checkHardwareStatusRequest: true, request_url: deviceUrl }, // Send the itemId in the request
      success: function (resp) {
        try {
          if (!statusChange) {
            const parsedData = JSON.parse(resp.data);
            const filteredData = {
              inputs: [],
              outputs: [],
            };
            for (const key in parsedData) {
              if (parsedData.hasOwnProperty(key) && key.includes("relay")) {
                filteredData.outputs.push({ value: parsedData[key], key });
              }
            }
            for (const key in parsedData) {
              if (
                parsedData.hasOwnProperty(key) &&
                key.includes("digitalInput")
              ) {
                filteredData.inputs.push({ value: parsedData[key], key });
              }
            }
            resolve(filteredData);
          } else {
            resolve(resp.data);
          }
        } catch (error) {
          console.error("Error parsing response data: ", error);
          reject(error);
        }
      },
      error: function (xhr, status, error) {
        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
        else reject(error);
      },
    });
  });
}

function isLoadingNow(isLoading) {
  const ele = document.getElementById("hardwareLoadingIndicator");
  if (isLoading) {
    ele.style.display = "flex";
  } else {
    ele.style.display = "none";
  }
}

function openAddQuickGroupModalToDoor(doorId) {
  $("#AddQuickGroupModalToDoor").modal("show");
  document.getElementById("door_id_for_grouping").value=doorId;
}

function quickUpdateDoorGroup(){
    const id = document.getElementById("door_id_for_grouping").value;
    const quick_change_group_by = document.getElementById("quick_change_group_by").value;
    sendDoorsRequest({
      quick_change_group_by_request:true,
      id,
      group_by:quick_change_group_by,
      property_id:sessionStorage.getItem("propertyId")
    })
}

async function RedirectToCameraForAddingNew(){
  await update_property_builder_tab_to_door({
      set_active_property_tab: true,
      active_tab: 2,
  });
  window.location.href="/dashboard.php?tab=property_builder&active=2&sub_tab=cam"
}

async function handle_change_add_number_door() {
  const selectEle = document.getElementById("door_number");
  if (selectEle.value === "add_new") window.location.href="/dashboard.php?tab=my_numbers"
}

function populateNumbersInDoors(numbers) {
  let selectBox = document.getElementById("door_number");
  selectBox.innerHTML = '<option value="">Select a number</option><option style="color: blue;font-weight: 700;cursor: pointer;" value="add_new">Add new</option>';
  numbers.forEach((num) => {
    let option = document.createElement("option");
    option.value = num?.phone_number;
    option.textContent = num?.phone_number;
    selectBox.appendChild(option);
  });
}

function updateDoorGroupList(data) {
    const groupList = document.getElementById("doorGroupList");
    if (!groupList) return;
    groupList.innerHTML = '';
    if (data?.length > 0) {
        data.forEach((group) => {
            const listItem = document.createElement("div");
            listItem.className = "list-group-item d-flex justify-content-between align-items-center";
            listItem.innerHTML = `
                <span>${group.groupName}</span>
                <div>
                    <button class="btn btn-sm btn-primary mr-2" onclick="editDoorGroup('${group.groupName}','${group.id}')">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteDoorGroup('${group.groupName}','${group.id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            groupList.appendChild(listItem);
        });
    }
}

function editDoorGroup(groupName,id) {
  console.log("id",id);
  console.log("groupName",groupName);
  
  document.getElementById("doorGroupId").value=id;
  setTimeout(() => {
    console.log("value",document.getElementById("doorGroupId").value);
  }, 1000);
  
  openAddGroupModal(groupName,id);
}

function deleteDoorGroup(groupName, id) {
  console.log("editDoorGroup",groupName,id);
  showConfirmModal("Are you sure you want to remove this door from its group?", () => {
    sendDoorsRequest({
      groupName: groupName,
      id,
      deleteGroupRequest: true,
      property_id: sessionStorage.getItem("propertyId")
    });
  });
}

// Function to show enlarged door image
function showEnlargedDoorImage(imageSrc, doorName) {
  document.getElementById('enlargedDoorImage').src = imageSrc;
  document.getElementById('doorImageModalTitle').textContent = `${doorName} Image`;
  // Show the modal
  $('#doorImageModal').modal('show');
}