let allQrTemplates = [];
// Constants
const DEFAULT_PHONE_NUMBER = "(123) 456-7890";

$(document).ready(function () {
  sendQrCodeTemplateRequest({ getQRTemplates: true,property_id:sessionStorage.getItem("propertyId") });
});

function sendQrCodeTemplateRequest(data) {
  $.ajax({
    url: "/include/property_builder/qr_code/qr_code_requests.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.getQRTemplates) {
        allQrTemplates = resp?.data;
      }
      if (data?.deleteTemplateById) {
        window.location.href = `/qrCodeTemplates.php`;
      }
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error)
        showToastMessageForTemplate(xhr?.responseJSON?.error);
      else showToastMessageForTemplate(error);
    },
  });
}

function showToastMessageForTemplate(errorMessage) {
  document.getElementById("qr_template_toastMessage").style.display = "block";
  document.getElementById("qr_template_Message").textContent = errorMessage;
  var toastEl = document.getElementById("qr_template_Toast");
  var toast = new bootstrap.Toast(toastEl, {
    delay: 3000, // Delay in milliseconds (5000ms = 5 seconds)
    autohide: false,
  });
  toast.show();

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

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

async function changeTemplateModeToEdit(id){
 window.location.href = `/qrCodeTemplates.php?template_id=${id}`;
}

function ChangeTemplateModeToView(){
  document.getElementById("editor_view").style.display="none";
  document.getElementById("viewTemplate").style.display="block";
}

async function saveEditedTemplate(id,templateName) {
  console.log("id", id);
  console.log("templateName", templateName);
  const editContainer = document.getElementById("Template_edit_mode_container");
  let layout_class = "";
  if(templateName=="Default 1" || templateName=="Default 2" || templateName=="Default 3"){
    layout_class = "letter_layout_portrait";
  }else if(templateName=="Default 4"){
    layout_class = "letter_layout_landscape";
  }

  const innerContent = editContainer.innerHTML;
  if (editContainer) {   
    // Remove all edit icons from the HTML content
    const cleanedHtml = removeEditIconsFromHtml(innerContent);
    const templateEdited = document.getElementById("Template_edit_mode_container");
    templateEdited.className = layout_class;
    templateEdited.innerHTML = cleanedHtml;
    setTimeout(async () => {
      // const imageData = await htmlToImage.toPng(templateEdited, {
      //   skipFonts: true
      // });
      const imageData = await htmlToImage.toPng(templateEdited);
      const actualImage=base64ToBlob(imageData);
      const formData = new FormData();
      formData.append("position_ring_color", "#000000");
      formData.append("position_center_color", "#000000");
      formData.append("position_module_color", "#000000");
      formData.append("templateName", templateName);
      formData.append("frameType", 0);
      formData.append("templateHtml", encodeURIComponent(cleanedHtml));
      formData.append("page_size", " ");
      formData.append("property_id", sessionStorage.getItem("propertyId"));
      formData.append("save_edited_template", true);
      if(actualImage){
        formData.append("template_image", actualImage);
      }else {
        formData.append("template_image", "");
      }
      
      // Send the cleaned HTML to backend for saving
      sendQRTemplatesRequestForAddUpdate(formData);
    }, 100);
  } else {
    console.log("Container not found!");
  }

}

function sendQRTemplatesRequestForAddUpdate(data) {
  $.ajax({
    url: "/include/property_builder/qr_code/qr_code_requests.php",
    type: "post",
    data,
    processData: false,
    contentType: false,
    success: function (resp) {
      window.location.href = `/qrCodeTemplates.php`;
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error)
        showErrorGlobalToastMessage(xhr?.responseJSON?.error);
      else showErrorGlobalToastMessage(error);
    },
  });
}


function removeEditIconsFromHtml(htmlString) {
  // Create a temporary container to parse the HTML string
  const container = document.createElement('div');
  container.innerHTML = htmlString;
  
  // Remove all edit icons (svg elements with edit-icon class)
  const editIcons = container.querySelectorAll('.edit-icon');
  editIcons.forEach(icon => {
    icon.remove();
  });
  
  // Remove the wrapper spans that were created for edit functionality
  // Find all spans with IDs starting with 'edit-'
  const editSpans = container.querySelectorAll('span[id^="edit-"]');
  editSpans.forEach(span => {
    // Move the content inside the span to replace the span itself
    while (span.firstChild) {
      span.parentNode.insertBefore(span.firstChild, span);
    }
    span.remove();
  });
  
  // Remove the wrapper divs that were created for image edit functionality
  // Find all divs with IDs starting with 'edit-'
  const editDivs = container.querySelectorAll('div[id^="edit-"]');
  editDivs.forEach(div => {
    // Move the content inside the div to replace the div itself
    while (div.firstChild) {
      div.parentNode.insertBefore(div.firstChild, div);
    }
    div.remove();
  });
  
  // Return the cleaned HTML as a string
  return container.innerHTML;
}

// Convert base64 to a Blob
function base64ToBlob(base64, mime = 'image/png') {
  const byteString = atob(base64.split(',')[1]);
  const arrayBuffer = new ArrayBuffer(byteString.length);
  const intArray = new Uint8Array(arrayBuffer);
  for (let i = 0; i < byteString.length; i++) {
    intArray[i] = byteString.charCodeAt(i);
  }
  return new Blob([intArray], { type: mime });
}

function revertTemplateChanges(id){
  showConfirmModal(
    "Are you sure you want to revert the template changes?",
    function () {
      sendQrCodeTemplateRequest({ deleteTemplateById: "yes", id });
    }
  );
}

function getDataForTemplatePreview(id) {
  const template=allQrTemplates.find(ele=>ele?.id==id);
  let template_image = undefined;
  if(template?.template_image.includes("/include")){
    template_image = template?.template_image;
  }else {
    template_image  = `/shared/serve_image.php?path=${template?.template_image}&type=all_images`;
  }

  const previewContainer = document.getElementById("TemplatePreviewContainer");
  previewContainer.innerHTML = ""; // Clear previous content if any
  // Create the image element
  const img = document.createElement("img");
  img.src = template_image;
  img.alt = "QR Code Template Preview";
  img.style.width = "100%";
  img.style.height = "100%";
  img.style.objectFit = "contain";
  previewContainer.appendChild(img);
  $("#TemplatePreviewModal").modal({
    backdrop: "static",
    keyboard: false,
  });
}

