let allVendorsData = {
  flag: { type: null },
  data: [],
};
let allVisitorsData = [];
let isCardViewForVendors = false;

$(document).ready(async function () {
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData = await parseJSONData(sessionPreferences);
    preferencesData?.is_card_view==1? isCardViewForVendors = true:isCardViewForVendors = 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) isCardViewForVendors = true;
  }
  fetchDataForVisistorsCards();
});

function fetchDataForVisistorsCards(){
  getAllPropertiesVendors({ getVisitors: "yes" });
  // addSwitchVendorView();
  const session_layer_name =
    document.getElementById("session_layer_name")?.value;
  if (
    session_layer_name === "super_admin" ||
    session_layer_name === "admin" ||
    session_layer_name === "dealer" ||
    session_layer_name === "property admin"
  ) {
    getAllPropertiesVendors({ getVendors: "yes" });
  }  
}

function getAllPropertiesVendors(data) {
  $.ajax({
    url: "/include/visitors/visitors.php",
    type: "post",
    data,
    success: function (response) {
      if (data?.getVendors) {
        allVisitorsData = parseData(response);       
        changeVendorsView();
      } else {
        allVendorsData = parseData(response);
        changeVendorsView();
      }
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function changeVendorsView() {
  var session_user = document.getElementById("session_layer_name")?.value;
  const visitors_table_container = document?.getElementById(
    "visitors_table_container"
  );
  const visitors_card_container = document?.getElementById(
    "visitors_card_container"
  );
  const vendors_card_container = document?.getElementById(
    "vendors_card_container"
  );
  const vendors_table_container = document?.getElementById(
    "vendors_table_container"
  );
  // const changeOrgViewEle = document.getElementById(
  //   "changeVendorViewEle"
  // ).checked;
  
  if(window.innerWidth <= 600 || isCardViewForVendors){
    visitors_table_container.style.display = "none";
    visitors_card_container.style.display = "block";
    createVisitorsCardView(allVendorsData?.data, allVendorsData?.flag?.type);
    if(session_user !== "user"){
      vendors_table_container.style.display = "none";
      vendors_card_container.style.display = "block";
      createVendorsCardView(allVisitorsData);
    }
  }else{
    visitors_table_container.style.display = "block";
    visitors_card_container.style.display = "none";
    if(session_user !== "user"){
      vendors_table_container.style.display = "block";
      vendors_card_container.style.display = "none";
    }
  }
}

function createVisitorsCardView(data, flag) {
  const container = document.getElementById("visitors_card_view");
  container.innerHTML = "";

  if (!data || data?.length === 0) {
    container.innerHTML = `
        <div class="card my-2 text-center">
          <div class="card-body">
            <h5 class="text-muted">No Users Found</h5>
            <p>Please add users or try refreshing the data.</p>
          </div>
        </div>
      `;
    return;
  }

  data?.forEach((item) => {
    let uStatus = "";
    if (item.status === "registered" || item.status === "Active") {
      uStatus =
        '<i style="color: green;display: flex; justify-content: center; align-items: center;" class="fas fa-check-circle text-success"></i>';
    } else {
      uStatus =
        '<i style="color: black;display: flex; justify-content: center; align-items: center;" class="fas fa-circle-xmark"></i>';
    }

    const cardHTML = `
            <div class="card my-2 property_users_card mx-2 edit-visitor-btn cursor_pointer" data-id="${item?.id}">
              <div class="card-header d-flex align-items-center">
                <div class="d-flex align-items-center">
                  <div class="property_image">
                    <img style="width: 100%; height: 100%;"
                         src="${
                           item?.image || "/include/images/user_dummy.png"
                         }"
                         alt="user" />
                  </div>
                  <h6 class="m-0 p-0">
                    ${item?.name}
                    <i 
                      class="fas fa-trash-alt text-danger mx-1 delete-visitor-btn"
                      style="cursor: pointer;"
                      title="Delete Visitor"
                      data-id="${item?.id}"
                      data-name="${item?.name}"
                      data-property="${item?.property_id}"></i>
                  </h6>
                </div>
              </div>

              <div class="card-body">
                <div class="d-flex flex-wrap">

                  <div class="d-flex pr-4 pt-2 align-items-center">
                    <i class="fa-solid fa-unlock-keyhole mx-1"></i>
                    <p class="m-0 p-0 text-bold">Key type:</p>
                    <p class="m-0 px-2">${item?.key_type}</p>
                  </div>

                  <div class="d-flex pr-4 pt-2 align-items-center">
                    <i class="fa-solid fa-square-poll-vertical mx-1"></i>
                    <p class="m-0 p-0 text-bold">Status:</p>
                    <p class="m-0 px-2">${uStatus || "N/A"}</p>
                  </div>
                  ${
                    flag == "admin"
                      ? `<div class="d-flex pr-4 pt-2 align-items-center">
                    <i class="fa-solid fa-address-card mx-1"></i>
                    <p class="m-0 p-0 text-bold">Created by:</p>
                    <p class="m-0 px-2">${item?.user_assoc || "N/A"}</p>
                  </div>

                  <div class="d-flex pr-4 pt-2 align-items-center">
                    <i class="fa-regular fa-building mx-1"></i>
                    <p class="m-0 p-0 text-bold">Property:</p>
                    <p class="m-0 px-2">${item?.property_id || "N/A"}</p>
                  </div>`
                      : ""
                  }
                </div>
              </div>
            </div>
          `;
    container.innerHTML += DOMPurify.sanitize(cardHTML);
  });
  bindVisitorCardEvents();
}

function bindVisitorCardEvents() {
  const $container = $("#visitors_card_view");

  $container.off("click", ".delete-visitor-btn");
  $container.off("click", ".edit-visitor-btn");

  $container.on("click", ".delete-visitor-btn", function (event) {
    event.stopPropagation();
    const id = $(this).data("id");
    const name = $(this).data("name");
    const propertyId = $(this).data("property");
    deleteVisitorCard(name, id, propertyId);
  });
  $container.on("click", ".edit-visitor-btn", function () {
    const id = $(this).data("id");
    editVisitor(id);
  });
}

function deleteVisitorCard(name, userId, propertyId) {
  showConfirmModal(
      'Are you sure you want to delete this Visitor: ' + name + ' (UserID: ' + userId + ') and property = ' + propertyId + '?',
      function () {
          $.ajax({
              url: 'include/visitors/visitors.php',
              type: 'post',
              data: { deleteVisitor: 'yes', userid: userId, property: propertyId }
          }).done(function (data) {
              if (data === 'Success') {
                  showAlertModal("The Visitor " + name + " has been successfully deleted!");
                  fetchDataForVisistorsCards();
              } else {
                  showAlertModal("Something went wrong. Please try again.");
              }
          });
      }
  );
}

function parseData(stringifyData) {
  try {
    return JSON.parse(stringifyData);
  } catch (error) {
    return [];
  }
}

function createVendorsCardView(data) {
  const container = document.getElementById("vendors_card_view");
  container.innerHTML = "";

  if (!data || data?.length === 0) {
    container.innerHTML = `
          <div class="card my-2 text-center">
            <div class="card-body">
              <h5 class="text-muted">No Vendors Found</h5>
              <p>Please add vendor or try refreshing the data.</p>
            </div>
          </div>
        `;
    return;
  }

  data?.forEach((item) => {
    let uStatus = "";
    if (item.status === "registered" || item.status === "Active") {
      uStatus =
        '<i style="color: green;display: flex; justify-content: center; align-items: center;" class="fas fa-check-circle text-success"></i>';
    } else {
      uStatus =
        '<i style="color: black;display: flex; justify-content: center; align-items: center;" class="fas fa-circle-xmark"></i>';
    }

    const cardHTML = `
              <div class="card my-2 property_users_card mx-2 edit-vendor-btn cursor_pointer" data-id="${item?.id}">
                <div class="card-header d-flex align-items-center">
                  <div class="d-flex align-items-center">
                    <div class="property_image">
                      <img style="width: 100%; height: 100%;"
                           src="${
                             item?.image || "/include/images/user_dummy.png"
                           }"
                           alt="user" />
                    </div>
                    <h6 class="m-0 p-0">
                      ${item?.name}
                      <i 
                        class="fas fa-trash-alt text-danger mx-1 delete-vendor-btn"
                        style="cursor: pointer;" 
                        title="Delete Vendor"
                        data-company="${item?.company}" 
                        data-name="${item?.name}" 
                        data-id="${item?.id}" 
                        data-property="${item?.property_id}"></i>
                    </h6>
                  </div>
                </div>
  
                <div class="card-body">
                  <div class="d-flex flex-wrap">
  
                    <div class="d-flex pr-4 pt-2 align-items-center">
                      <i class="fa-solid fa-unlock-keyhole mx-1"></i>
                      <p class="m-0 p-0 text-bold">Company:</p>
                      <p class="m-0 px-2">${item?.company}</p>
                    </div>
  
                    <div class="d-flex pr-4 pt-2 align-items-center">
                      <i class="fa-solid fa-unlock-keyhole mx-1"></i>
                      <p class="m-0 p-0 text-bold">Key type:</p>
                      <p class="m-0 px-2">${item?.key_type}</p>
                    </div>
  
                    <div class="d-flex pr-4 pt-2 align-items-center">
                      <i class="fa-solid fa-square-poll-vertical mx-1"></i>
                      <p class="m-0 p-0 text-bold">Status:</p>
                      <p class="m-0 px-2">${uStatus || "N/A"}</p>
                    </div>
                    <div class="d-flex pr-4 pt-2 align-items-center">
                      <i class="fa-solid fa-address-card mx-1"></i>
                      <p class="m-0 p-0 text-bold">Created by:</p>
                      <p class="m-0 px-2">${item?.user_assoc || "N/A"}</p>
                    </div>
  
                    <div class="d-flex pr-4 pt-2 align-items-center">
                      <i class="fa-regular fa-building mx-1"></i>
                      <p class="m-0 p-0 text-bold">Property:</p>
                      <p class="m-0 px-2">${item?.property_id || "N/A"}</p>
                    </div>
                  </div>
                </div>
              </div>
            `;
    container.innerHTML += DOMPurify.sanitize(cardHTML);
  });

  bindVendorCardEvents();
}

function bindVendorCardEvents() {
  const $container = $("#vendors_card_view");
  $container.off("click", ".delete-vendor-btn");
  $container.off("click", ".edit-vendor-btn");

  $container.on("click", ".delete-vendor-btn", function (event) {
    event.stopPropagation();
    const name = $(this).data("name");
    const id = $(this).data("id");
    const propertyId = $(this).data("property");
    deleteVendorCard(name, id, propertyId);
  });

  $container.on("click", ".edit-vendor-btn", function () {
    const id = $(this).data("id");
    editVendor(id);
  });
}

function deleteVendorCard(name, userId, propertyId) {
  showConfirmModal(
      'Are you sure you want to delete this Vendor: ' + name + ' (UserID: ' + userId + ') and property = ' + propertyId + '?',
      function () {
          $.ajax({
              url: 'include/visitors/visitors.php',
              type: 'post',
              data: { deleteVendor: 'yes', userid: userId, property: propertyId }
          }).done(function (data) {
              if (data === 'Success') {
                  showAlertModal("The Vendor " + name + " has been successfully deleted!");
                  fetchDataForVisistorsCards();
              } else {

                  showAlertModal("Something went wrong. Please try again.");
              }
          });
      }
  );
}

function searchVendorsCard() {
  let searchValue = document
    .getElementById("searchCardsVendorsInput")
    ?.value.trim()
    .toLowerCase();

  if (!searchValue) {
    createVendorsCardView(allVisitorsData);
    return;
  }

  let filteredEvents = allVisitorsData.filter((event) => {
    return Object.values(event).some(
      (field) => field && field.toString().toLowerCase().includes(searchValue)
    );
  });
  createVendorsCardView(filteredEvents);
}

function searchVisitorsCard() {
  let searchValue = document
    .getElementById("searchVisitorsUsersInput")
    ?.value.trim()
    .toLowerCase();

  if (!searchValue) {
    createVisitorsCardView(allVendorsData?.data, allVendorsData?.flag?.type);
    return;
  }

  let filteredEvents = allVendorsData?.data?.filter((event) => {
    return Object.values(event).some(
      (field) => field && field.toString().toLowerCase().includes(searchValue)
    );
  });
  createVisitorsCardView(filteredEvents, allVendorsData?.flag?.type);
}
