let isCardViewForProperties = false;

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

let allOrgsProperties = undefined;

function getAllPropertiesOrganizations() {
  $.ajax({
    url: "/include/properties/property.php",
    type: "post",
    data: { getdata: "yes" },
    success: function (response) {
      let data = JSON.parse(response);
      allOrgsProperties = data;
      changeOrganizationView();
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function createCardViewOfOrganization(organizations, properties) {
  const organizationCardView = document.getElementById(
    "organization_card_view"
  );

  let htmlContent = "";

  organizations.forEach((organization) => {
    // Start building the HTML string for the card
    htmlContent += `
        <div class=" mt-3">
            <div class="card">
                <div class="card-header d-flex align-items-center">
                    <div class="d-flex">
                        <h5 class="m-0 p-0">${
                          organization.name || "Organization Name"
                        }</h5>
                        <div class="px-3">
                           <i class="fas fa-edit text-primary mx-1 org-edit-btn"
                            style="cursor: pointer;"
                            title="Edit Organization"
                            data-id="${organization.id}"></i>
                        </div>
                    </div>
                </div>

                <div class="card-body">
                    <div class="d-flex flex-wrap" style="width: 100%;">
                    
                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-location-dot text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">Address:</p>
                            <p class="m-0 px-2">${
                              organization.address || "N/A"
                            }</p>
                        </div>

                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-location-dot text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">City:</p>
                            <p class="m-0 px-2">${
                              organization.city || "N/A"
                            }</p>
                        </div>
                        
                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-earth-africa text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">State:</p>
                            <p class="m-0 px-2">${
                              organization.state || "N/A"
                            }</p>
                        </div>

                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-location-dot text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">Zip:</p>
                            <p class="m-0 px-2">${
                              organization.zipcode || "N/A"
                            }</p>
                        </div>

                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-address-book text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">Contact:</p>
                            <p class="m-0 px-2">${
                              organization.contact || "N/A"
                            }</p>
                        </div>

                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-phone-volume text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">Contact Phone:</p>
                            <p class="m-0 px-2">${
                              organization.contact_phone_number || "N/A"
                            }</p>
                        </div>

                        <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                            <i class="fa-solid fa-calendar-days text-primary mx-1"></i>
                            <p class="m-0 p-0 text-bold">Created Date:</p>
                            <p class="m-0 px-2">${
                              organization.created_at || "N/A"
                            }</p>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end align-items-center mt-3" style="gap: 10px;">
                        <button class="btn btn-outline-primary btn-sm properties-toggle-btn d-flex" 
                                data-id="${organization.id}"
                                data-expanded="false">
                                <span class="pr-2">Show Properties</span>
                                <span id="show-properties-icon-${organization.id}" style="display: none;"> <i class="fas fa-chevron-down me-1"></i></span>
                                <span id="hide-properties-icon-${organization.id}"> <i class="fas fa-chevron-right me-1"></i></span>
                        </button>
                    </div>

                    <div id="properties_${
                      organization?.id
                    }" class="d-flex flex-wrap mt-3"> </div>
                </div>
            </div>
        </div>
        `;
  });

  organizationCardView.innerHTML = DOMPurify.sanitize(htmlContent);
  $(".bootstrap_switch_properties").bootstrapSwitch();
  bindOrganizationCardEvents();
}

function bindOrganizationCardEvents() {
  const $container = $("#organization_card_view");
  $container.off("click", ".org-edit-btn");
  $container.off("click", ".properties-toggle-btn");
  $container.on("click", ".org-edit-btn", function () {
    const id = $(this).data("id");
    editOrg(id);
  });
  $container.on("click", ".properties-toggle-btn", function () {
    const id = $(this).data("id");
    toggleProperties(id);
    togglePropertiesIcon(id);
  });
}

function togglePropertiesIcon(id){
  const showPropertiesIcon = document.getElementById(`show-properties-icon-${id}`);
  const hidePropertiesIcon = document.getElementById(`hide-properties-icon-${id}`);
  const properties = document.getElementById(`properties_${id}`);
  if(properties.innerHTML.trim() !== ""){
    showPropertiesIcon.style.display = "block";
    hidePropertiesIcon.style.display = "none";
  }else{
    showPropertiesIcon.style.display = "none";
    hidePropertiesIcon.style.display = "block";
  }
}

function toggleProperties(orgId) {
  const property = document.getElementById(`properties_${orgId}`);
  const properties = allOrgsProperties?.properties.filter(
    (ele) => ele.organization_id == orgId
  );

  if (property.innerHTML.trim() !== "") {
    property.innerHTML = "";
    return;
  }

  htmlContent = "";

  properties.forEach((property) => {
    // Start building the HTML string for the card

    let imagePath=null
    if(property?.image_path){
      imagePath = `<div class="property_image" onclick="show_property_image('property_image_modal', 'property_image', '/shared/serve_image.php?path=${property.image_path}&type=property')"><img style="width:100%;height:100%; cursor:pointer;" src="/shared/serve_image.php?path=${property.image_path}&type=property" alt="property image" ></div>`;
    }
    htmlContent += `
            <div class="px-3">
                <div class="card mb-3">
                    <div class="card-header d-flex align-items-center">
                        <div class="d-flex align-items-center">
                            ${
                              imagePath
                                ? `${imagePath}`
                                : ` <div class="property_image">
                                        <img src="/include/images/building_icon.png" alt="">
                                    </div>`
                            }
                            <h5 class="m-0 p-0">${
                              property.name || "Property Name"
                            }</h5>
                            <div class="px-3">
                               <i class="fas fa-edit text-primary mx-1 property-edit-btn"
                                  style="cursor: pointer;"
                                  title="Edit Property"
                                  data-id="${property.id}"></i>
                                
                              ${
                                property?.check_voip === 0
                                  ? `<a class="fas fa-plus text-primary property-voip-btn"
                                      style="cursor: pointer; font-size:25px;"
                                      title="Add VOIP Setting"
                                      data-id="${property.id}"
                                      data-name="${property.name}"></a>`
                                  : ``
                              }

                            </div>
                        </div>
                    </div>
    
                    <div class="card-body">
                        <div class="d-flex flex-wrap" style="width: 100%;">    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-location-dot text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">Address:</p>
                                <p class="m-0 px-2">${
                                  property.address || "N/A"
                                }</p>
                            </div>
    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-location-dot text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">City:</p>
                                <p class="m-0 px-2">${
                                  property.city || "N/A"
                                }</p>
                            </div>
                            
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-earth-africa text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">State:</p>
                                <p class="m-0 px-2">${
                                  property.state || "N/A"
                                }</p>
                            </div>
    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-location-dot text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">Zip:</p>
                                <p class="m-0 px-2">${
                                  property.zipcode || "N/A"
                                }</p>
                            </div>
    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-address-book text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">Contact:</p>
                                <p class="m-0 px-2">${
                                  property.contact || "N/A"
                                }</p>
                            </div>
    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-phone-volume text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">Contact Phone:</p>
                                <p class="m-0 px-2">${
                                  property.contact_phone_number || "N/A"
                                }</p>
                            </div>
    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-phone-volume text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">Property type:</p>
                                <p class="m-0 px-2">${
                                  property.contact_phone_number || "N/A"
                                }</p>
                            </div>
    
                            <div class="d-flex pr-4 pt-2 align-items-center" style="width: 33%;">
                                <i class="fa-solid fa-calendar-days text-primary mx-1"></i>
                                <p class="m-0 p-0 text-bold">Created Date:</p>
                                <p class="m-0 px-2">${
                                  property.created_at || "N/A"
                                }</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            `;
  });

  property.innerHTML = htmlContent;
  bindPropertyCardEvents();
}

function bindPropertyCardEvents() {
  const $container = $("#organization_card_view");
  $container.off("click", ".property-edit-btn");
  $container.off("click", ".property-voip-btn");
  $container.on("click", ".property-edit-btn", function () {
    const id = $(this).data("id");
    editProp(id);
  });
  $container.on("click", ".property-voip-btn", function () {
    const id = $(this).data("id");
    const name = $(this).data("name");
    add_voip_setting(id, name);
  });
}

function changeOrganizationView() {

  console.log("is it working in changeOrganizationView", isCardViewForProperties);
  
  const organization_table_view = document?.getElementById(
    "organization_table_view"
  );
  const organization_card_view = document?.getElementById(
    "organization_card_view"
  );
  if (window.innerWidth <= 600){
    organization_table_view.style.display = "none";
    organization_card_view.style.display = "block";
    createCardViewOfOrganization(
      allOrgsProperties?.organizations,
      allOrgsProperties?.properties
    );
  }else if(isCardViewForProperties){
    organization_table_view.style.display = "none";
    organization_card_view.style.display = "block";
    createCardViewOfOrganization(
      allOrgsProperties?.organizations,
      allOrgsProperties?.properties
    );
  }else{
    organization_table_view.style.display = "block";
    organization_card_view.style.display = "none";
  }
}
