let isCardViewForUsersTab = false;

$(document).ready(async function () {
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData = await parseJSONData(sessionPreferences);
    preferencesData?.is_card_view==1? isCardViewForUsersTab = true:isCardViewForUsersTab = 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) isCardViewForUsersTab = true;
  }
  getAllPropertiesUsers({ getUsers: "yes" });
  getAllPropertiesOPerators({ getOperators: "yes" });
  getAllPropertiesAdmins({getdealeradmins: "yes"});
  getAllDeletedOperators({getDeleted: "yes"});
  getAllDeletedUsers({getDeleted: "yes"});

});

let allPropertyUsers = [];
let allPropertyOperators = [];

function getAllPropertiesUsers(data) {
  $.ajax({
    url: "/include/users/users_db.php",
    type: "post",
    data,
    success: function (response) {
      if (data?.getOperators) {
        changePropertyOperatorsView();
      } else if (data?.getUsers) {
          const property_users_table_view = document?.getElementById(
            "property_users_table_view"
          );
          const property_users_card_container = document?.getElementById(
            "property_users_card_container"
          );
          allPropertyUsers = parseData(response);
          if (window.innerWidth <= 600){
            property_users_table_view.style.display = "none";
            property_users_card_container.style.display = "block";
            createPropertyUsersCardView(allPropertyUsers);
            return;
          }else if(isCardViewForUsersTab){
            property_users_table_view.style.display = "none";
            property_users_card_container.style.display = "block";
            createPropertyUsersCardView(allPropertyUsers);
          } 
          else{
            property_users_table_view.style.display = "block";
            property_users_card_container.style.display = "none";
          } 
        // changePropertyUsersView();
      }
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

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

function createPropertyUsersCardView(data) {
  const container = document.getElementById("property_users_card_view");
  container.innerHTML = "";

  if (!data || data?.length === 0) {
    container.innerHTML = `
      <div class="text-center p-4">
        <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
        <h5 class="text-muted">No Users Found</h5>
        <p class="text-muted">There are no users to display.</p>
      </div>
    `;
    return;
  }

  container.style.display = "flex";
  container.style.flexWrap = "wrap";
  
  data?.forEach((item) => {
    let uStatus = "";
    let inviteSend = "";
    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>';
      inviteSend = `<a class='fa-regular fa-paper-plane cursor_pointer resend_invite_button' data-id="${item.id}" title='Resend Invitation'></a>`;
    }

    var mNum = item?.mobile_number?.replace(
      /(\d{3})(\d{3})(\d{4})/,
      "$1-$2-$3"
    );
    var hNum = item?.home_number?.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
    let phone_numbers = `
        <div>
            <div> <i class='fas fa-mobile-button'></i> ${mNum}</div>
            <div><i class='fas fa-phone'></i> ${hNum}</div>
        </div>
    `;
    var profileLocation = item.photo_loc && typeof item.photo_loc === 'string' ? item.photo_loc : "";
    var fileExtension = profileLocation ? profileLocation.substring(profileLocation.lastIndexOf('.') + 1).toLowerCase() : '';
    var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    var profileHTML = '';
    if (imageExtensions.includes(fileExtension)) {
        var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(profileLocation) + "&type=profile";
        profileHTML = '<img src="' + imagePath + '" alt="User" tyle="width: 100%; height: 100%;">';
    } else{
        profileHTML = '<img src="/include/images/user_dummy.png" alt="User" tyle="width: 100%; height: 100%;">';
    }
    const userName = `${item.firstname} ${item.lastname}`;
    const cardHTML = `
        <div class="card my-2 property_users_card mx-2">
          <div class="card-header d-flex align-items-center">
            <div class="d-flex align-items-center">
              <div class="property_image">
                `+ profileHTML +`
              </div>
              <h6 class="m-0 p-0">
                ${userName} 
                <span>
                  <i class="fas fa-edit text-primary mx-1 cursor_pointer edit_property_user_button" title="Edit User" data-id="${item.id}"></i>
                  <i class='fas fa-trash-alt text-danger mx-1 cursor_pointer delete_property_user_button' 
                    title='Delete Operator'
                    data-id="${item.id}"
                    data-property="${item?.property_id} 
                    data-userName="${userName}> </i>
                 ${inviteSend} 
                </span>
              </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-list-check mx-1"></i>
                <p class="m-0 p-0 text-bold">Registered:</p>
                <p class="m-0 px-2">${uStatus}</p>
              </div>
  
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-location-dot mx-1"></i>
                <p class="m-0 p-0 text-bold">Address:</p>
                <p class="m-0 px-2">${
                  item.unit + " " + item.street || "N/A"
                }</p>
              </div>
    
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-address-book mx-1"></i>
                <p class="m-0 p-0 text-bold">Contacts:</p>
                <p class="m-0 px-2">${phone_numbers || "N/A"}</p>
              </div>
            </div>
          </div>
        </div>
      `;
    container.innerHTML += DOMPurify.sanitize(cardHTML);
  });

  bindUsersCardEvents();
}

function bindUsersCardEvents() {
  const $container = $("#property_users_card_view");
  $container.off("click", ".edit_property_user_button");
  $container.off("click", ".delete_property_user_button");
  $container.off("click", ".resend_invite_button");

  $container.on("click", ".edit_property_user_button", function () {
    const id = $(this).data("id");
    editUser(id);
  });

  $container.on("click", ".resend_invite_button", function () {
    const inviteemail = $(this).data("email");
    resendInvite(inviteemail);
  });
  $container.on("click", ".delete_property_user_button", function () {
    const id = $(this).data("id");
    const property = $(this).data("property");
    const userName = $(this).data("userName");
    deleteUser(userName,id,property);
  });
}

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

  if (!searchValue) {
    createPropertyUsersCardView(allPropertyUsers);
    return;
  }

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

// operators cards to the table

function getAllPropertiesOPerators(data) {
  $.ajax({
    url: "/include/users/operators_db.php",
    type: "post",
    data,
    success: function (response) {
      if (data?.getOperators && response) {
        const userArray = Object.values(parseData(response));
        allPropertyOperators = userArray;
        changePropertyOperatorsView();
        // createPropertyOperatorsCardView(allPropertyOperators);
      } else {
        allPropertyOperators = [];
        createPropertyOperatorsCardView(allPropertyOperators);
      }
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function changePropertyOperatorsView() {
  const property_table_view = document?.getElementById(
    "operators_table_container"
  );
  const property_card_container = document?.getElementById(
    "property_operators_card_container"
  );
  if (window.innerWidth <= 600){
    property_table_view.style.display = "none";
    property_card_container.style.display = "block";
    createPropertyOperatorsCardView(allPropertyOperators);
    return;
  }else if(isCardViewForUsersTab){
    property_table_view.style.display = "none";
    property_card_container.style.display = "block";
    createPropertyOperatorsCardView(allPropertyOperators);
  }else{
    property_table_view.style.display = "block";
    property_card_container.style.display = "none";
  }
}

function createPropertyOperatorsCardView(data) {
  const container = document.getElementById("property_operators_card_view");
  container.innerHTML = "";

  if (!data || data?.length === 0) {
    container.innerHTML = DOMPurify.sanitize(`
        <div class="d-flex justify-content-center align-items-center my-2 text-center w-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 Operators Found</h5>
            <p class="text-muted">There are no operators to display.</p>
          </div>
        </div>
      `);
    return;
  }

  data?.forEach((item) => {
    let uStatus = "";
    let inviteSend = "";
    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>';
      inviteSend = `<a class='fa-regular fa-paper-plane' style='cursor: pointer;' title='Resend Invitation' onclick='resendInvite(${item.email})'></a>`;
    }

    const operatorName = `${item.firstname} ${item.lastname}`;

    const cardHTML = `
          <div class="card my-2 property_users_card mx-2">
            <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">
                  ${operatorName}
                  <span>
                    <i class="fas fa-edit text-primary mx-1 edit-operator-btn"
                      style="cursor: pointer;" 
                      title="Edit Operator" 
                      data-id="${item?.id}"></i>
  
                    <i class="fas fa-trash-alt text-danger mx-1 delete-operator-btn" 
                      style="cursor: pointer;" 
                      title="Delete Operator" 
                      data-id="${item?.id}" 
                      data-name="${operatorName}" 
                      data-property="${item?.property_id}"></i>

                   ${
                      item.status === "registered" || item.status === "Active"
                        ? ""
                        : `<i class='fa-regular fa-paper-plane resend-invite-btn cursor_pointer' 
                              title='Resend Invitation' 
                              data-id='${item.id}'></i>`
                    } 
                  </span>
                </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-list-check mx-1"></i>
                  <p class="m-0 p-0 text-bold">Role:</p>
                  <p class="m-0 px-2">${item?.role_name}</p>
                </div>
    
                <div class="d-flex pr-4 pt-2 align-items-center">
                  <span class="fa-solid fa-address-card mx-1" title="Name"></span>
                  <p class="m-0 p-0 text-bold">Email:</p>
                  <p class="m-0 px-2">${item?.email || "N/A"}</p>
                </div>
      
                <div class="d-flex pr-4 pt-2 align-items-center">
                  <i class="fa-solid fa-address-book mx-1"></i>
                  <p class="m-0 p-0 text-bold">Registered:</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-book mx-1"></i>
                  <p class="m-0 p-0 text-bold">Created by:</p>
                  <p class="m-0 px-2">${item?.created_by || "N/A"}</p>
                </div>
                
                <div class="d-flex pr-4 pt-2 align-items-center">
                  <i class="fa-solid fa-address-book mx-1"></i>
                  <p class="m-0 p-0 text-bold">Last login:</p>
                  <p class="m-0 px-2">${item?.logged_time || "N/A"}</p>
                </div>
              </div>
            </div>
          </div>
        `;
    container.innerHTML += DOMPurify.sanitize(cardHTML);
  });

  bindPropertyOperatorEvents();
}

function bindPropertyOperatorEvents() {
  const $container = $("#property_operators_card_view");

  $container.off("click", ".edit-operator-btn");
  $container.off("click", ".delete-operator-btn");
  $container.off("click", ".resend-invite-btn");

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

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

  $container.on("click", ".resend-invite-btn", function () {
    const inviteemail = $(this).data("email");
    resendInvite(inviteemail);
  });
}

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

  if (!searchValue) {
    createPropertyOperatorsCardView(allPropertyOperators);
    return;
  }

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

// Admins card view functions
let all_admins_data = [];

function getAllPropertiesAdmins(data) {
  $.ajax({
    url: "include/users/admins_db.php",
    type: "POST",
    data, 
}).done(function(data){
    var combined = JSON.parse(data);
    all_admins_data = combined;
    console.log("all_admins_data",all_admins_data);
    try {
      changeDealerAdminsView(all_admins_data?.dealeradmins);
      changeOrgAdminsView(all_admins_data?.orgadmins);
    } catch (error) {
      console.log("error in asdf",error);
    }
});
}

function changeDealerAdminsView(data) {
  const dealer_admins_table_container = document?.getElementById(
    "dealer_admins_table_container"
  );
  const dealer_admins_card_container = document?.getElementById(
    "dealer_admins_card_container"
  );
  if (window.innerWidth <= 600 || isCardViewForUsersTab){
    dealer_admins_table_container.style.display = "none";
    dealer_admins_card_container.style.display = "block";
    createDealerAdminsCardView(data);
    return;
  }else{
    dealer_admins_table_container.style.display = "block";
    dealer_admins_card_container.style.display = "none";
  }
}

function createDealerAdminsCardView(data) {
  const container = document.getElementById("dealer_admins_card_view");
  container.innerHTML = "";

  if (!data || data?.length === 0) {
    container.innerHTML = DOMPurify.sanitize(`
        <div class="text-center p-4">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Dealer Admins Found</h5>
          <p class="text-muted">There are no dealer admins to display.</p>
        </div>
      `);
    return;
  }

  data?.forEach((item) => {
    let uStatus = "";
    let inviteSend = "";
    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>';
      inviteSend = `<a class='fa-regular fa-paper-plane' style='cursor: pointer;' title='Resend Invitation' onclick='resendInvite(${item.email})'></a>`;
    }

    const adminName = `${item.firstname} ${item.lastname}`;
    const logTime = item.last_logged_in || 'Not Logged In Yet';

    const cardHTML = `
          <div class="card my-2 property_users_card mx-2">
            <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="admin" />
                </div>
                <h6 class="m-0 p-0">
                  ${adminName}
                  <span>
                    <i class="fas fa-edit text-primary mx-1 edit-dealer-admin-btn"
                      style="cursor: pointer;" 
                      title="Edit Dealer Admin" 
                      data-id="${item?.id}"></i>
  
                    <i class="fas fa-trash-alt text-danger mx-1 delete-dealer-admin-btn" 
                      style="cursor: pointer;" 
                      title="Delete Dealer Admin" 
                      data-id="${item?.id}" 
                      data-name="${adminName}"></i>

                   ${
                      item.status === "registered" || item.status === "Active"
                        ? ""
                        : `<i class='fa-regular fa-paper-plane resend-invite-dealer-admin-btn cursor_pointer' 
                              title='Resend Invitation' 
                              data-id='${item.id}'></i>`
                    } 
                  </span>
                </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-user-tie mx-1"></i>
                  <p class="m-0 p-0 text-bold">Role:</p>
                  <p class="m-0 px-2">${item?.layer || "N/A"}</p>
                </div>
    
                <div class="d-flex pr-4 pt-2 align-items-center">
                  <span class="fa-solid fa-envelope mx-1" title="Email"></span>
                  <p class="m-0 p-0 text-bold">Email:</p>
                  <p class="m-0 px-2">${item?.email || "N/A"}</p>
                </div>
      
                <div class="d-flex pr-4 pt-2 align-items-center">
                  <i class="fa-solid fa-check-circle 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-clock mx-1"></i>
                  <p class="m-0 p-0 text-bold">Last login:</p>
                  <p class="m-0 px-2">${logTime}</p>
                </div>
              </div>
            </div>
          </div>
        `;
    container.innerHTML += DOMPurify.sanitize(cardHTML);
  });

  bindDealerAdminEvents();
}

function bindDealerAdminEvents() {
  const $container = $("#dealer_admins_card_view");

  $container.off("click", ".edit-dealer-admin-btn");
  $container.off("click", ".delete-dealer-admin-btn");
  $container.off("click", ".resend-invite-dealer-admin-btn");

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

  $container.on("click", ".delete-dealer-admin-btn", function () {
    const id = $(this).data("id");
    const name = $(this).data("name");
    deletedealeradmins(name, id);
  });

  $container.on("click", ".resend-invite-dealer-admin-btn", function () {
    const inviteemail = $(this).data("email");
    resendInvite(inviteemail);
  });
}

// Org admins card view functions
function changeOrgAdminsView(data) {
  const orgadmins_table_container = document?.getElementById(
    "orgadmins_table_container"
  );
  const orgadmins_card_container = document?.getElementById(
    "orgadmins_card_container"
  );
  
  if (window.innerWidth <= 600 || isCardViewForUsersTab){
    orgadmins_table_container.style.display = "none";
    orgadmins_card_container.style.display = "block";
    createOrgAdminsCardView(data);
    return;
  }else{
    orgadmins_table_container.style.display = "block";
    orgadmins_card_container.style.display = "none";
  }
}

function createOrgAdminsCardView(data) {
  const container = document.getElementById("orgadmins_card_view");
  container.innerHTML = ""; 

  if (!data || data?.length === 0) {
    container.innerHTML = DOMPurify.sanitize(`
        <div class="text-center p-4">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Organization Admins Found</h5>
          <p class="text-muted">There are no organization admins to display.</p>
        </div>
      `);
    return;
  }else{
    data?.forEach((item) => {
      let uStatus = "";
      let inviteSend = "";
      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>';
        inviteSend = `<a class='fa-regular fa-paper-plane' style='cursor: pointer;' title='Resend Invitation' onclick='resendInvite(${item.email})'></a>`;
      }
  
      const adminName = `${item.firstname} ${item.lastname}`;
      const logTime = item.last_logged_in || 'Never';
  
      const cardHTML = `
            <div class="card my-2 property_users_card mx-2">
              <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="admin" />
                  </div>
                  <h6 class="m-0 p-0">
                    ${adminName}
                    <span>
                      <i class="fas fa-edit text-primary mx-1 edit-org-admin-btn"
                        style="cursor: pointer;" 
                        title="Edit Organization Admin" 
                        data-id="${item?.id}"></i>
    
                      <i class="fas fa-trash-alt text-danger mx-1 delete-org-admin-btn" 
                        style="cursor: pointer;" 
                        title="Delete Organization Admin" 
                        data-id="${item?.id}" 
                        data-name="${adminName}"></i>
  
                     ${
                        item.status === "registered" || item.status === "Active"
                          ? ""
                          : `<i class='fa-regular fa-paper-plane resend-invite-org-admin-btn cursor_pointer' 
                                title='Resend Invitation' 
                                data-id='${item.id}'></i>`
                      } 
                    </span>
                  </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-user-tie mx-1"></i>
                    <p class="m-0 p-0 text-bold">Role:</p>
                    <p class="m-0 px-2">${item?.layer || "N/A"}</p>
                  </div>
      
                  <div class="d-flex pr-4 pt-2 align-items-center">
                    <span class="fa-solid fa-envelope mx-1" title="Email"></span>
                    <p class="m-0 p-0 text-bold">Email:</p>
                    <p class="m-0 px-2">${item?.email || "N/A"}</p>
                  </div>
        
                  <div class="d-flex pr-4 pt-2 align-items-center">
                    <i class="fa-solid fa-check-circle 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-clock mx-1"></i>
                    <p class="m-0 p-0 text-bold">Last login:</p>
                    <p class="m-0 px-2">${logTime}</p>
                  </div>
                </div>
              </div>
            </div>
          `;
      container.innerHTML += DOMPurify.sanitize(cardHTML);
    });
  }
  bindOrgAdminEvents();
}

function bindOrgAdminEvents() {
  const $container = $("#orgadmins_card_view");

  $container.off("click", ".edit-org-admin-btn");
  $container.off("click", ".delete-org-admin-btn");
  $container.off("click", ".resend-invite-org-admin-btn");

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

  $container.on("click", ".delete-org-admin-btn", function () {
    const id = $(this).data("id");
    const name = $(this).data("name");
    deletedealeradmins(name, id);
  });

  $container.on("click", ".resend-invite-org-admin-btn", function () {
    const inviteemail = $(this).data("email");
    resendInvite(inviteemail);
  });
}

function searchOrgAdminsCard() {
  const searchInput = document.getElementById("searchCardsOrgAdminsInput");
  const searchTerm = searchInput.value.toLowerCase();
  const cards = document.querySelectorAll("#orgadmins_card_view .property_users_card");
  cards.forEach(card => {
    const cardText = card.textContent.toLowerCase();
    if (cardText.includes(searchTerm)) {
      card.style.display = "block";
    } else {
      card.style.display = "none";
    }
  });
}

function searchDealerAdminsCard() {
  const searchInput = document.getElementById("searchCardsDealerAdminsInput");
  const searchTerm = searchInput.value.toLowerCase();
  const cards = document.querySelectorAll("#dealer_admins_card_view .property_users_card");
  
  cards.forEach(card => {
    const cardText = card.textContent.toLowerCase();
    if (cardText.includes(searchTerm)) {
      card.style.display = "block";
    } else {
      card.style.display = "none";
    }
  });
}

//#region Manage tab
// ***********************************==== Manage tab ====********************************

//#region Deleted operators
// ============Deleted operators ===================

function getAllDeletedOperators(data) {
  $.ajax({
    url: "/include/users/operators_db.php",
    type: "post",
    data,
    success: function (response) {
      const deletedOperatorsArray = Object.values(parseData(response));
      console.log("deletedOperatorsArray",deletedOperatorsArray);
      changeDeletedOperatorsView(deletedOperatorsArray);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function changeDeletedOperatorsView(data) {
  const deleted_operators_table_view = document?.getElementById(
    "deleted_operators_table_container"
  );
  const deleted_operators_card_container = document?.getElementById(
    "deleted_operators_card_container"
  );
  if(!deleted_operators_card_container && !deleted_operators_table_view) return;
  if (window.innerWidth <= 600 || isCardViewForUsersTab){
    deleted_operators_table_view.style.display = "none";
    deleted_operators_card_container.style.display = "block";
    createDeletedOperatorsCardView(data);
    return;
  }else{
    deleted_operators_table_view.style.display = "block";
    deleted_operators_card_container.style.display = "none";
  }
}

function createDeletedOperatorsCardView(data) {
  const container = document.getElementById("deleted_operators_card_view");
  container.innerHTML = "";
  
  if (!data || data.length === 0) {
    container.innerHTML = `
      <div class="text-center p-4">
        <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
        <h5 class="text-muted">No Deleted Operators Found</h5>
        <p class="text-muted">There are no deleted operators to display.</p>
      </div>
    `;
    return;
  }

  let html = '<div class="row">';
  
  data.forEach((item) => {
    // Status logic
    let uStatus = '';
    if (item.status === 'registered' || item.status === 'Active') {
      uStatus = '<i style="color: green;" class="fas fa-check-circle text-success"></i>';
    } else {
      uStatus = '<i style="color: black;" class="fas fa-circle-xmark"></i>';
    }

    // Profile image logic
    let profileHTML = '';
    if (item.photo_loc && typeof item.photo_loc === 'string') {
      const fileExtension = item.photo_loc.substring(item.photo_loc.lastIndexOf('.') + 1).toLowerCase();
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      
      if (imageExtensions.includes(fileExtension)) {
        const imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(item.photo_loc) + "&type=profile";
        profileHTML = `<img src="${imagePath}" alt="Profile Image" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff;">`;
      } else if (item.photo_loc) {
        profileHTML = `<i class="${item.photo_loc} fa-2x" style="padding: 3px 4px;font-size: 41px;"></i>`;
      } else {
        profileHTML = '<i class="fas fa-user-circle fa-2x" style="padding: 3px 4px;font-size: 41px;"></i>';
      }
    } else {
      profileHTML = '<i class="fas fa-user-circle fa-2x" style="padding: 3px 4px;font-size: 41px;"></i>';
    }

    const operatorName = `${item.firstname} ${item.lastname}`;
    const logTime = item.logged_time || 'Not Logged In Yet';
    const deletedDate = item.deleted_at ? new Date(item.deleted_at).toLocaleDateString() : 'Unknown';

    html += `
      <div class="col-lg-4 col-md-6 col-sm-12 mb-3">
        <div class="card h-100 shadow-sm">
          <div class="card-header d-flex align-items-center">
            <div class="d-flex align-items-center">
              <div class="property_image me-3">
                ${profileHTML}
              </div>
              <div>
                <h6 class="m-0 p-0">
                  ${operatorName}
                  <span class="ms-2">
                    <i class="fas fa-toolbox text-info recover-deleted-operator-btn cursor_pointer" title="Recover Deleted Operator" data-id="${item.id}" data-name="${operatorName}" data-property-id="${item.property_id}"></i>
                  </span>
                </h6>
                <small class="text-muted">Deleted on ${deletedDate}</small>
              </div>
            </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-user-tie mx-1"></i>
                <p class="m-0 p-0 text-bold">Role:</p>
                <p class="m-0 px-2">${item.role_name || "N/A"}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <span class="fa-solid fa-envelope mx-1" title="Email"></span>
                <p class="m-0 p-0 text-bold">Email:</p>
                <p class="m-0 px-2">${item.email || "N/A"}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-check-circle mx-1"></i>
                <p class="m-0 p-0 text-bold">Status:</p>
                <p class="m-0 px-2">${uStatus}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-clock mx-1"></i>
                <p class="m-0 p-0 text-bold">Last login:</p>
                <p class="m-0 px-2">${logTime}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-mobile-button mx-1"></i>
                <p class="m-0 p-0 text-bold">Mobile:</p>
                <p class="m-0 px-2">${item.mobile_number || "N/A"}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-user-plus mx-1"></i>
                <p class="m-0 p-0 text-bold">Created by:</p>
                <p class="m-0 px-2">${item.created_by || "N/A"}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
  });
  
  html += '</div>';
  container.innerHTML = DOMPurify.sanitize(html);
  bindDeletedOperatorEvents();
}

function bindDeletedOperatorEvents() {
  const $container = $("#deleted_operators_card_view");
  $container.off("click", ".recover-deleted-operator-btn");
  $container.on("click", ".recover-deleted-operator-btn", function () {
    const id = $(this).data("id");
    const name = $(this).data("name");
    const propertyId = $(this).data("property-id");
    // Use the same recover function as the table view
    recover(name, id, propertyId);
  });
}

function searchDeletedOperatorsCard() {
  const searchInput = document.getElementById("searchCardsDeletedOperatorsInput");
  const searchTerm = searchInput.value.toLowerCase();
  const cards = document.querySelectorAll("#deleted_operators_card_view .col-lg-4");
  
  cards.forEach(card => {
    const cardText = card.textContent.toLowerCase();
    if (cardText.includes(searchTerm)) {
      card.style.display = "block";
    } else {
      card.style.display = "none";
    }
  });
}

//#endregion

//#region Deleted users
// ============Deleted users ===================

function getAllDeletedUsers(data) {
  $.ajax({
    url: "/include/users/users_db.php",
    type: "post",
    data,
    success: function (response) {
      const deletedOperatorsArray = Object.values(parseData(response));
      changeDeletedUsersView(deletedOperatorsArray);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function changeDeletedUsersView(data) {
  const deleted_users_table_container = document?.getElementById(
    "deleted_users_table_container"
  );
  const deleted_users_card_container = document?.getElementById(
    "deleted_users_card_container"
  );
  if(!deleted_users_card_container && !deleted_users_table_container) return;
  if (window.innerWidth <= 600 || isCardViewForUsersTab){
    deleted_users_table_container.style.display = "none";
    deleted_users_card_container.style.display = "block";
    createDeletedUsersCardView(data);
    return;
  }else{
    deleted_users_table_container.style.display = "block";
    deleted_users_card_container.style.display = "none";
  }
}

function createDeletedUsersCardView(data) {
  const container = document.getElementById("deleted_users_card_view");
  container.innerHTML = "";
  
  if (!data || data.length === 0) {
    container.innerHTML = `
      <div class="text-center p-4">
        <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
        <h5 class="text-muted">No Deleted Users Found</h5>
        <p class="text-muted">There are no deleted users to display.</p>
      </div>
    `;
    return;
  }

  let html = '<div class="row">';
  
  data.forEach((item) => {
    // Status logic (same as fetchAndDisplayData)
    let uStatus = '';
    if (item.status === 'registered' || item.status === 'Active') {
      uStatus = '<i style="color: green;" class="fas fa-check-circle text-success"></i>';
    } else {
      uStatus = '<i style="color: black;" class="fas fa-circle-xmark"></i>';
    }

    // Phone number formatting (same as fetchAndDisplayData)
    const mNum = item.mobile_number ? item.mobile_number.replace(/\D/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3') : 'N/A';
    const hNum = item.home_number ? item.home_number.replace(/\D/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3') : 'N/A';

    // Profile image logic (same as fetchAndDisplayData)
    let profileHTML = '';
    if (item.photo_loc && typeof item.photo_loc === 'string') {
      const fileExtension = item.photo_loc.substring(item.photo_loc.lastIndexOf('.') + 1).toLowerCase();
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      
      if (imageExtensions.includes(fileExtension)) {
        const imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(item.photo_loc) + "&type=profile";
        profileHTML = `<img src="${imagePath}" alt="Profile Image" class="img-fluid rounded-circle" style="width: 50px; height: 50px; border: 1px solid #007bff;">`;
      } else if (item.photo_loc) {
        profileHTML = `<i class="${item.photo_loc} fa-2x" style="padding: 3px 4px;font-size: 41px;"></i>`;
      } else {
        profileHTML = '<i class="fas fa-user-circle fa-2x" style="padding: 3px 4px;font-size: 41px;"></i>';
      }
    } else {
      profileHTML = '<i class="fas fa-user-circle fa-2x" style="padding: 3px 4px;font-size: 41px;"></i>';
    }

    const userName = `${item.firstname} ${item.lastname}`;
    const address = `${item.unit} ${item.street}`;
    const deletedDate = item.deleted_at ? new Date(item.deleted_at).toLocaleDateString() : 'Unknown';

    html += `
      <div class="col-lg-4 col-md-6 col-sm-12 mb-3">
        <div class="card h-100 shadow-sm">
          <div class="card-header d-flex align-items-center">
            <div class="d-flex align-items-center">
              <div class="property_image me-3">
                ${profileHTML}
              </div>
              <div>
                <h6 class="m-0 p-0">
                  ${userName}
                  <span class="ms-2">
                    <i class="fas fa-toolbox text-info recover-deleted-user-btn cursor_pointer" title="Recover Deleted User" data-id="${item.id}" data-name="${userName}" data-property-id="${item.property_id}"></i>
                  </span>
                </h6>
                <small class="text-muted">User ID: ${item.id} | Deleted on ${deletedDate}</small>
              </div>
            </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-map-marker-alt mx-1"></i>
                <p class="m-0 p-0 text-bold">Address:</p>
                <p class="m-0 px-2">${address}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-check-circle mx-1"></i>
                <p class="m-0 p-0 text-bold">Status:</p>
                <p class="m-0 px-2">${uStatus}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-mobile-button mx-1"></i>
                <p class="m-0 p-0 text-bold">Mobile:</p>
                <p class="m-0 px-2">${mNum}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-phone mx-1"></i>
                <p class="m-0 p-0 text-bold">Home:</p>
                <p class="m-0 px-2">${hNum}</p>
              </div>
              <div class="d-flex pr-4 pt-2 align-items-center">
                <i class="fa-solid fa-car mx-1"></i>
                <p class="m-0 p-0 text-bold">License Plate:</p>
                <p class="m-0 px-2">${item.license_plate || "N/A"}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
  });
  
  html += '</div>';
  container.innerHTML = DOMPurify.sanitize(html);
  bindDeletedUserEvents();
}

function bindDeletedUserEvents() {
  const $container = $("#deleted_users_card_view");
  $container.off("click", ".recover-deleted-user-btn");
  $container.on("click", ".recover-deleted-user-btn", function () {
    const id = $(this).data("id");
    const name = $(this).data("name");
    const propertyId = $(this).data("property-id");
    // Use the same recover function as the table view
    recover(name, id, propertyId);
  });
}

function searchDeletedUsersCard() {
  const searchInput = document.getElementById("searchCardsDeletedUsersInput");
  const searchTerm = searchInput.value.toLowerCase();
  const cards = document.querySelectorAll("#deleted_users_card_view .col-lg-4");
  
  cards.forEach(card => {
    const cardText = card.textContent.toLowerCase();
    if (cardText.includes(searchTerm)) {
      card.style.display = "block";
    } else {
      card.style.display = "none";
    }
  });
}

//#endregion
//#endregion
