if (typeof window.AllQrCodesData === "undefined") {
  window.AllQrCodesData = [];
}
let AllVinylOrderData = [];
let selectedQrCodeImage = "";
let selectedQrCodeFile = null;
let isQrCodeCardView = false;

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

  qrCodeLoader(true);
  sendQrCodeRequest({
    getQRCodeData: "yes",
    property_id: sessionStorage.getItem("propertyId"),
  });

  sendHardwareSettingsRequestForQrCode({
    get_signal_wire_credentials: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
});

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

$(window).on("resize", function () {
  if ($.fn.DataTable.isDataTable("#qrCodesDataTable")) {
    $("#qrCodesDataTable").DataTable().columns.adjust().draw();
  }
});
function populateNumbersInQrCode(numbers) {
  let selectBox = document.getElementById("qr_phone_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 = formatUSPhoneNumber(num?.phone_number);
    selectBox.appendChild(option);
  });
}


function sendQrCodeRequest(data) {
  $.ajax({
    url: "/include/property_builder/qr_code/qr_code_requests.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.getQRCodeData) {
        AllQrCodesData = resp?.data;
        qrCodeLoader(false);
        if (window.innerWidth <= 600){
          createQrCodesCardsPreview(AllQrCodesData);
        }else if(isQrCodeCardView) createQrCodesCardsPreview(AllQrCodesData);
        else createQrCodesTablePreview(AllQrCodesData);
        // changeCanBanView();
      }
      if (data?.DataGetById) bindDataForEdit(resp.data);
      if (data?.addQrCode || data?.editQrCode || data?.deleteQrCodeById) {
        $("#addQrCode").modal("hide");
        sendQrCodeRequest({
          getQRCodeData: "yes",
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
      //Vinyl
      if (data?.addVinylOrder) {
        $("#addVinylOrder").modal("hide");
        sendQrCodeRequest({
          getQRCodeData: "yes",
          property_id: sessionStorage.getItem("propertyId"),
        });
      }
      if (data?.deleteVinylOrder) {
        sendQrCodeRequest({
          getVinylOrders: true,
        });
      }
      if (data?.getVinylOrders) {
        AllVinylOrderData = resp?.data;
        if (window.innerWidth <= 600){
          createdVinylCardView(AllVinylOrderData);
        }else if(isQrCodeCardView) createdVinylCardView(AllVinylOrderData);
        else createdVinylTable(AllVinylOrderData);
      }
    },
    error: function (xhr, status, error) {
      qrCodeLoader(false);
      if (xhr?.responseJSON?.error.includes("SQLSTATE[23000]")) {
        showToastMessage(
          "You have placed order of that qr design. If you still want to delete the qr code please delete the order first"
        );
        return;
      }
      if (xhr?.responseJSON?.error) showToastMessage(xhr?.responseJSON?.error);
      else showToastMessage(error);
    },
  });
}

function updateTemplateSelectOptions(response) {
  var $select = $("#templateId");
  $select.find("option:not(:first)").remove();
  $.each(response, function (index, template) {
    var option = $("<option>", {
      value: template.id,
      text: template.templateName,
    });
    $select.append(option);
  });
}

function createQrCodesCardsPreview(dataArray) {
  $("#QR_Code_table").empty();

  if (!dataArray || dataArray.length === 0) {
    const noDataHtml = `
      <div class="text-center p-4">
        <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
        <h5 class="text-muted">No Qr Codes Found</h5>
        <p class="text-muted">There are no qr codes to display.</p>
      </div>
    `;
    document.getElementById("QR_Code_table").innerHTML =
      DOMPurify.sanitize(noDataHtml);
    return;
  }

  let html = ' <div class="row">';
  dataArray.forEach(function (item) {
    const qr_image = `/shared/serve_image.php?path=${item?.qr_image}&type=all_images`;
    let already_downloaded=undefined;
    if(item?.imageData)already_downloaded=`/shared/serve_image.php?path=${item?.imageData}&type=all_images`;
    html += `<div class="col-lg-6 col-md-6 col-sm-12">
      <div class="card mb-3">
        <div class="card-header d-flex align-items-center">
           <div style="width:100px;height:120px">
              <img src="${qr_image}" alt="Qr Image" class="img-thumbnail" style="width: 100%; height: 100%; object-fit: contain;">
            </div>
          <h5 class="mb-0 px-2">${formatUSPhoneNumber(item?.phone_number) || "N/A"}</h5>
          <div class="ml-auto">
          
            <i class='fas fa-eye text-info mx-1 view-btn cursor_pointer' data-id="${
              item.id
            }" title='View Qr Design'></i>
            <i class='fas fa-edit text-primary mx-1 edit-btn cursor_pointer' data-id="${
              item.id
            }" title='Edit Qr'></i>
            <i class='fas fa-trash-alt text-danger mx-1 delete-btn cursor_pointer' data-id="${
              item.id
            }" title='Delete qr'></i>
            <i class='fas fa-download text-success mx-1 download-btn cursor_pointer' data-id="${
              item.id
            }" title='Download the Qr After editing'></i>
            ${
              already_downloaded
                ? `<i class='fas fa-download text-warning mx-1 download-old-btn cursor_pointer' data-id="${item.id}" title='Download previous edited image'></i>`
                : ""
            }
          </div>
        </div>
        <div class="card-body">
          <div class="d-flex flex-wrap align-items-center">
            <div class="qrSingle_info">
              <p class="m-0 p-0"><strong class="pr-1">Template name:</strong> ${
                item?.templateName
              }</p>
            </div>
            <div class="qrSingle_info">
              <p class="m-0 p-0"><strong class="pr-1">Vinyl Print:</strong>${
                !item?.hasOrdered
                  ? `<button class="btn btn-success order-btn" data-id="${item.id}">Order Now</button>`
                  : `<span>OrderId: ${item.hasOrdered}</span>`
              }</p>
            </div>
            <div class="qrSingle_info">
              <p class="m-0 p-0"><strong class="pr-1">Edited image:</strong>${
                already_downloaded
                  ? `<div style="width:100px;height:120px">
                      <img src="${already_downloaded}" alt="Edited image" style="width: 100%; height: 100%; object-fit: contain;" />
                    </div>`
                  : `<div class="edit-image-btn" data-id="${item.id}" style="display: flex; align-items: center;">
                      <i class='fas fa-edit text-primary mx-1' style='cursor: pointer;' title='Edit Image'></i>
                      <span style="cursor: pointer;" title='Edit Image'>Edit Image</span>
                    </div>`
              }</p>
            </div>
          </div>
        </div>
      </div>
    </div>`;
  });
  html += `</div>`;
  document.getElementById("QR_Code_table").innerHTML = DOMPurify.sanitize(html);
  bindQrCodeCardEvents();
}

function bindQrCodeCardEvents() {
  const $container = $("#QR_Code_table");
  $container.off("click", ".view-btn");
  $container.off("click", ".edit-btn");
  $container.off("click", ".delete-btn");
  $container.off("click", ".download-btn");
  $container.off("click", ".download-old-btn");
  $container.off("click", ".order-btn");
  $container.off("click", ".edit-image-btn");
  $container.off("click", ".print-qr-btn");

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

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

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

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

  $container.on("click", ".download-old-btn", function () {
    const id = $(this).data("id");
    downloadLastEditedQrImage(id);
  });

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

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

  $container.on("click", ".print-qr-btn", function () {
    const image = $(this).data("image");
    printImage(image);
  });
}

function createQrCodesTablePreview(dataArray) {
  AllQrCodesData = dataArray;
  let data = dataArray;
  document.getElementById("QR_Code_table").innerHTML = "";
  let html = `
    <div class="table-responsive p-0">
      <table id="qrCodesDataTable" class="table table-bordered table-head-fixed text-nowrap table-hover">
        <thead>
          <tr>
            <th>Phone number</th>
            <th>Template Name</th>
            <th>QR Image</th>
            <th>Edited Image</th>
            <th>Vinyl Print</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
  `;

  if (data.length === 0) {
    html +=
      "<tr><td colspan='6' class='text-center'>No data available</td></tr>";
  } else {
    data.forEach(function (item) {
      const qr_image = `/shared/serve_image.php?path=${item?.qr_image}&type=all_images`;
      let already_downloaded=undefined;
      if(item?.imageData)already_downloaded=`/shared/serve_image.php?path=${item?.imageData}&type=all_images`;
      html += `
        <tr>
          <td style="vertical-align: middle;">${formatUSPhoneNumber(item?.phone_number) || ""}</td>
          <td style="vertical-align: middle;">${item?.templateName || ""}</td>
          <td style="vertical-align: middle;">
            <div style="width:100px;height:120px">
              <img src="${qr_image}" alt="Qr Image" class="img-thumbnail" style="width: 100%; height: 100%; object-fit: contain;">
            </div>
          </td>
         <td style="vertical-align: middle;">
            ${
              already_downloaded
                ? `<div style="width:100px;height:120px">
                    <img src="${already_downloaded}" alt="Edited image" style="width: 100%; height: 100%; object-fit: contain;" />
                  </div>`
                : `<div class="edit-image-btn" data-id="${item.id}" style="display: flex; align-items: center;">
                      <i class='fas fa-edit text-primary mx-1' style='cursor: pointer;' title='Edit Image'></i>
                      <span style="cursor: pointer;" title='Edit Image'>Edit Image</span>
                    </div>`
            }
          </td>
         <td style="vertical-align: middle;">
          ${
            !item?.hasOrdered
              ? `<button class="btn btn-success order-btn" data-id="${item.id}">Order Now</button>`
              : `<span>OrderId: ${item.hasOrdered}</span>`
          }
         </td>
          <td style="vertical-align: middle;">
           <i class='fas fa-eye text-info mx-1 view-btn cursor_pointer' data-id="${
             item.id
           }" title='View Qr Design'></i>
            <i class='fas fa-edit text-primary mx-1 edit-btn cursor_pointer' data-id="${
              item.id
            }" title='Edit Qr'></i>
            <i class='fas fa-trash-alt text-danger mx-1 delete-btn cursor_pointer' data-id="${
              item.id
            }" title='Delete qr'></i>
            <i class='fas fa-download text-success mx-1 download-btn cursor_pointer' data-id="${
              item.id
            }" title='Download the Qr After editing'></i>
             <i class="fas fa-print text-success cursor_pointer print-qr-btn" data-image="${
              item.qr_image
            }"></i>
            ${
              already_downloaded
                ? `<i class='fas fa-download text-warning mx-1 download-old-btn cursor_pointer' data-id="${item.id}" title='Download previous edited image'></i>`
                : ""
            }
          </td>
        </tr>
      `;
    });
  }
  html += `
        </tbody>
      </table>
    </div>
  `;

  document.getElementById("QR_Code_table").innerHTML = DOMPurify.sanitize(html);

  if (!$.fn.DataTable.isDataTable("#qrCodesDataTable") && data?.length) {
    $("#qrCodesDataTable").DataTable({
      responsive: true,
      order: [],
      paging: false,
      pageLength: -1,
      searching: false, // Disable sorting on image and action columns
    });
  } else if (data?.length > 0) {
    $("#qrCodesDataTable").DataTable().order([]).draw();
  }

  bindQrCodeCardEvents();
}

function downloadLastEditedQrImage(image) {
  const qrCodeData = AllQrCodesData.find((ele) => ele.id == image);
  if(qrCodeData?.imageData){
    const previous_edit_download = `/shared/serve_image.php?path=${qrCodeData?.imageData}&type=all_images`;
    const link = document.createElement("a");
    link.href = previous_edit_download;
    link.download = "Qr_Code.png";
    link.click();
  }else{
    showToastMessage("No previous edited image found");
  }
}

function getTemplatePreviewModal(id) {
  let data = AllQrCodesData.find((ele) => ele.id == id);
  const qr_image = `/shared/serve_image.php?path=${data?.qr_image}&type=all_images`;
  const previewContainer = document.getElementById(
    "QrCodeDesignPreviewContainer"
  );
  previewContainer.innerHTML = "";
  const img = document.createElement("img");
  img.src = qr_image;
  img.alt = "QR Code desing Preview";
  img.style.width = "100%";
  img.style.height = "100%";
  img.style.objectFit = "contain";
  img.style.border = "1px solid";
  img.style.borderRadius = "10px";
  previewContainer.appendChild(img);
  $("#QrCodePreviewModal").modal({
    backdrop: "static",
    keyboard: false,
  });
}

function DownloadQrCodeModal(qrId) {
  let found = AllQrCodesData.find((ele) => ele.id == qrId);
  console.log("found", found);
  if (found) window.location.href = `/qrCodeDownload.php?id=${found.id}`;
  else {
    showToastMessage("Something went wrong");
  }
}

function openQRCodeInNewTab(id) {
  const node = document.querySelector(`#qr${id}`);
  htmlToImage
    .toPng(node, {
      skipFonts: true
    })
    .then(function (dataUrl) {
      const link = document.createElement("a");
      link.href = dataUrl;
      link.download = "example-image.png";
      link.click();
    })
    .catch(function (error) {
      console.error("Error generating image:", error);
    });
}

function bindDataForEdit(data) {
  document.getElementById("qr_id").value = data.id; // Set the hidden input value
  document.getElementById("addEditQrCode").textContent = "Edit Qr Code"; // Set the hidden input value
  document.getElementById("submitQrCodeButton").textContent = "Update";
  document.getElementById("qr_phone_number").value = data?.phone_number;
  document.getElementById("templateId").value = data?.templateId;
  const qrCode_preview = document.getElementById("qr_code_design_preview");
  if (!data?.qr_image && qrCode_preview) {
    qrCode_preview.innerHTML = "";
    qrCode_preview.style.display = "none";
    
  }else if (qrCode_preview) {
      const qr_image = `/shared/serve_image.php?path=${data?.qr_image}&type=all_images`;
      qrCode_preview.innerHTML = DOMPurify.sanitize(`<img src="${qr_image}" alt="Qr Image" class="img-thumbnail" style="width: 100%; height: 100%; object-fit: contain;" />`);
      qrCode_preview.classList.add("qrCode_design_preview");
      qrCode_preview.style.display = "block";
  }
  selectedQrCodeImage = "";
  selectedQrCodeFile = null;

  $("#addQrCode").modal("show");
}

function dataGetById(id) {
  sendQrCodeRequest({ DataGetById: "yes", id });
}

function addNewQrCode() {
  document.getElementById("qr_id").value = null; // Set the hidden input value
  document.getElementById("addEditQrCode").textContent = "Add Qr Code"; // Set the hidden input value
  document.getElementById("submitQrCodeButton").textContent = "Save";
  document.getElementById("qr_phone_number").value = "";
  document.getElementById("templateId").value = "";
  // Clear the QR code area
  const qrCode_preview = document.getElementById("qr_code_design_preview");
  if (qrCode_preview) {
    qrCode_preview.innerHTML = "";
    qrCode_preview.style.display = "none";
  }

  selectedQrCodeImage = "";
  selectedQrCodeFile = null;
}

function deleteQrCode(id) {
  showConfirmModal("Are you sure you want to delete?", function () {
    sendQrCodeRequest({ deleteQrCodeById: "yes", id });
  });
}

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

  setTimeout(() => {
    closeQR_ToastMessage();
  }, 4000);
}

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

function viewAllTemplates() {
  window.location = "/qrCodeTemplates.php";
}

function viewAllOrders() {
  document.getElementById("order_view").style.display = "block";
  document.getElementById("qrCode_view").style.display = "none";

  sendQrCodeRequest({ getVinylOrders: true });
}

function OrderForVinylPrint(id, hasOrdered) {
  if (hasOrdered) {
    console.log("hasOrdered", hasOrdered);
    return;
  }
  document.getElementById("vinylType").value = "";
  document.getElementById("QRCodeCodeId").value = id;
  document.getElementById("shippingAddress").value = "";
  document.getElementById("printQuantity").value = 1;
  $("#addVinylOrder").modal("show");
}

function goBackToQrView() {
  document.getElementById("order_view").style.display = "none";
  document.getElementById("qrCode_view").style.display = "block";
  sendQrCodeRequest({
    getQRCodeData: "yes",
    property_id: sessionStorage.getItem("propertyId"),
  });
}

function generateOrderId() {
  const prefix = "ODR";
  const length = 12;
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let randomString = "";
  for (let i = 0; i < length; i++) {
    randomString += characters.charAt(
      Math.floor(Math.random() * characters.length)
    );
  }
  return prefix + randomString;
}

function addVinylOrder() {
  const quantity = document.getElementById("printQuantity").value;
  const shippingAddress = document.getElementById("shippingAddress").value;
  const qrCodeId = document.getElementById("QRCodeCodeId").value;
  // const qrWidth = document.getElementById("qrWidth").value;
  // const qrHeight = document.getElementById("qrHeight").value;

  const size = document.getElementById("vinylSize").value;
  const type = document.getElementById("vinylType").value;
  if (quantity < 1 || !shippingAddress || !size || !type) {
    showToastMessage("Fill all fields");
    return;
  }
  const orderId = generateOrderId();
  // const size = `${qrWidth}x${qrHeight}`;
  const property_id = sessionStorage.getItem("propertyId");
  let payload = {
    qrCodeId,
    quantity,
    shippingAddress,
    size,
    type,
    orderId,
    property_id,
    addVinylOrder: true,
  };
  sendQrCodeRequest(payload);
}

function createdVinylCardView(dataArray) {
  AllQrCodesData = dataArray;
  let data = dataArray;
  $("#vinylOrderTable").empty();

  if (!dataArray || dataArray.length === 0) {
    const noDataHtml = `
      <div class="text-center p-4">
        <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
        <h5 class="text-muted">No Vinyl Orders Found</h5>
        <p class="text-muted">There are no vinyl orders to display.</p>
      </div>
    `;
    document.getElementById("vinylOrderTable").innerHTML =
      DOMPurify.sanitize(noDataHtml);
    return;
  }

  let html = "";
  html += `<div class="row">`;
  data.forEach(function (item) {
    html += `<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">
                        <h5 class="mb-0">${item?.orderId}</h5>
                        <div class="ml-auto">
                           <i class='fas fa-trash-alt text-danger mx-1 deleteOrderNowButton cursor_pointer' data-id="${
                             item.id
                           }" data-qr-id="${item.qrCodeId}"></i>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="d-flex flex-wrap">
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Number:</strong> ${
                                  item?.phone_number || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">QTY:</strong>${
                                  item?.quantity || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Type:</strong>${
                                  item?.size || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Size:</strong> ${
                                  item?.size || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Status:</strong> ${
                                  item?.status || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Address:</strong> ${
                                  item?.shippingAddress || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Ordered at:</strong> ${
                                  new Date(item?.orderedAt).toDateString() || ""
                                }</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>`;
  });
  html += `</div>`;
  document.getElementById("vinylOrderTable").innerHTML =
    DOMPurify.sanitize(html);
  bindVinylOrderEvents();
}

function bindVinylOrderEvents() {
  const $container = $("#vinylOrderTable");
  $container.off("click", ".edit-street-btn");
  $container.off("click", ".delete-street-btn");

  $container.on("click", ".deleteOrderNowButton", function () {
    const id = $(this).data("id");
    const qrCodeId = $(this).data("qr-id");
    deleteOrderNow(id, qrCodeId);
  });

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

function createdVinylTable(dataArray) {
  AllQrCodesData = dataArray;
  let data = dataArray;
  document.getElementById("vinylOrderTable").innerHTML = "";
  let html = `
    <div class="table-responsive p-0">
      <table id="vinylOrderDataTable" class="table table-bordered table-head-fixed text-nowrap table-hover">
        <thead>
          <tr>
            <th>OrderID</th>
            <th>Number</th>
            <th>QTY</th>
            <th>Type</th>
            <th>Size</th>
            <th>Status</th>
            <th>Address</th>
            <th>Ordered at</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
  `;

  if (data.length === 0) {
    html +=
      "<tr><td colspan='9' class='text-center'>No data available</td></tr>";
  } else {
    data.forEach(function (item) {
      html += `
        <tr>
          <td>${item?.orderId || ""}</td>
          <td>${item?.phone_number || ""}</td>
          <td>${item?.quantity || ""}</td>
          <td>${item?.type || ""}</td>
          <td>${item?.size || ""}</td>
          <td>${item?.status || ""}</td>
          <td>${item?.shippingAddress || ""}</td>
          <td>${new Date(item?.orderedAt).toDateString() || ""}</td>
          <td>
            <i class='fas fa-trash-alt text-danger mx-1 deleteOrderNowButton cursor_pointer' data-id="${
              item.id
            }" data-qr-id="${item.qrCodeId}"></i>
          </td>
        </tr>
      `;
    });
  }
  html += `
        </tbody>
      </table>
    </div>
  `;

  // Insert the entire table structure into the specified element
  document.getElementById("vinylOrderTable").innerHTML =
    DOMPurify.sanitize(html);
  // vinylOrderDataTable

  if (!$.fn.DataTable.isDataTable("#vinylOrderDataTable") && data?.length) {
    $("#vinylOrderDataTable").DataTable({
      responsive: true,
      order: [],
      paging: true,
      pageLength: 10,
      searching: false, // Disable sorting on image and action columns
    });
  } else if (data?.length > 0) {
    $("#vinylOrderDataTable").DataTable().order([]).draw();
  }
  bindVinylOrderEvents();
}

function deleteOrderNow(id, qrCodeId) {
  showConfirmModal("Are you sure you want to delete?", function () {
    let payload = {
      id,
      qrCodeId,
      deleteVinylOrder: true,
    };
    sendQrCodeRequest(payload);
  });
}

let QrDebounceTimer = null;
function searchQrCodes() {
  if(!isQrCodeCardView){
    searchTable('qrCodesDataTable', 'search_qr_code_value');
    return;
  }
  clearTimeout(QrDebounceTimer);
  QrDebounceTimer = setTimeout(() => {
    const searchInput = document.getElementById("search_qr_code_value");
    if (!searchInput) {
      console.warn("Search input not found: search_qr_code_value");
      return;
    }
    
    const searchValue = searchInput.value.toLowerCase();
    
    // Filter QR codes data
    let MatchedQrCodes = AllQrCodesData.filter(
      (event) =>
        !searchValue ||
        Object.values(event).some(
          (field) =>
            field && field.toString().toLowerCase().includes(searchValue)
        )
    );
    
    // Re-render based on current view
    if (window.innerWidth <= 600 || isQrCodeCardView) {
      createQrCodesCardsPreview(MatchedQrCodes);
    } else {
      createQrCodesTablePreview(MatchedQrCodes);
    }
  }, 200);
}

function searchQrOrders() {
  clearTimeout(QrDebounceTimer);
  QrDebounceTimer = setTimeout(() => {
    const searchValue = document.getElementById("search_qr_order_value").value;
    let MatchedQrOrders = AllVinylOrderData.filter(
      (event) =>
        !searchValue ||
        Object.values(event).some(
          (field) =>
            field && field.toString().toLowerCase().includes(searchValue)
        )
    );
    createdVinylCardView(MatchedQrOrders);
  }, 200);
}

function qrCodeLoader(isLoader = false) {
  const qrCodeLoader = document.getElementById("qrCodeLoader");
  const QR_Code_table = document.getElementById("QR_Code_table");
  if (isLoader) {
    qrCodeLoader.style.display = "flex";
    QR_Code_table.style.display = "none";
  } else {
    qrCodeLoader.style.display = "none";
    QR_Code_table.style.display = "block";
  }
}

let isCreatingPreview = false;
async function generatePreviewForQrCode(templateId) {
  let templateIdForPreview = document.getElementById("templateId").value;
  let phone_numberForPreview = document.getElementById("qr_phone_number").value;
  if (!templateIdForPreview || !phone_numberForPreview) {
    showToastMessage("Please select template and enter phone number");
    return;
  }
  
  // i dont want to call this event again and again on the click if the promise is not resilved yet. after resolving the promise i can call this event again.
  if(isCreatingPreview){
    console.log("Already creating preview");
    return;
  }
  try {
    isCreatingPreview=true;
    await new Promise((resolve) => setTimeout(resolve, 500));
    await new Promise((resolve) => requestAnimationFrame(resolve));
  
    const template= await sendQrTemplatePromiseRequest(templateIdForPreview);
    createdViewForEditorInQrCode(template, phone_numberForPreview);
    isCreatingPreview=false; 
    console.log("Created");
  } catch (error) {
    isCreatingPreview=false;
    console.log("Error creating preview");
  }
}

async function sendQrTemplatePromiseRequest(templateId) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/property_builder/qr_code/qr_code_requests.php",
      type: "post",
      data: { getTemplateById: "yes", id: templateId },
      success: function (resp) {
        resolve(resp.data);
      },
      error: function (xhr, status, error) {
        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
        else reject(error);
      },
    });
  });
}

async function createdViewForEditorInQrCode(template, phone_number) {
  let layout_class = "";
  if (template?.templateName == "Default 4") {
    layout_class = "letter_layout_landscape";
  } else {
    layout_class = "letter_layout_portrait";
  }

  const qrCodeWrap = document.getElementById("downloadAreaQrCode");
  qrCodeWrap.className = layout_class;
  qrCodeWrap.style.display = "block";
  qrCodeWrap.innerHTML = "";

  const qrCodeContainer = document.createElement("div");
  qrCodeContainer.className = "";
  qrCodeContainer.id = "QrCodeCompleteContainer";

  let decodedTemplateHtml = decodeURIComponent(template?.templateHtml);
  let decodedHtml = "";
  if (decodedTemplateHtml?.includes("&lt")) {
    let parser = new DOMParser();
    var doc = parser.parseFromString(decodedTemplateHtml, "text/html");
    decodedHtml = doc.documentElement.textContent; // Use textContent to get the decoded HTML
  } else decodedHtml = decodedTemplateHtml;

  const targetText = "(123) 456-7890";
  const replacementText = formatUSPhoneNumber(phone_number);
  if (decodedHtml.includes(targetText)) {
    decodedHtml = decodedHtml.replace(targetText, replacementText);
  } else if (decodedHtml.includes("(571) 350-0755")) {
    decodedHtml = decodedHtml.replace("(571) 350-0755", replacementText);
  }

  if(decodedHtml.includes("(123) 456-7890")){
    decodedHtml = decodedHtml.replace("(123) 456-7890", replacementText);
  }

  qrCodeContainer.innerHTML = decodedHtml;
  qrCodeWrap.appendChild(qrCodeContainer);
  // Use MutationObserver to ensure all DOM changes are applied
  await new Promise((resolve) => setTimeout(resolve, 500));
  await new Promise((resolve) => requestAnimationFrame(() => resolve()));
  createPreviewInModalForQrCode(qrCodeWrap);
  return;
}

function createPreviewInModalForQrCode(node) {
  htmlToImage
    .toPng(node, {
      skipFonts: true
    })
    .then(function (dataUrl) {
      const imageData = dataUrl;
      // Store the data URL
      selectedQrCodeImage = dataUrl;

      // Convert data URL to File object
      fetch(dataUrl)
        .then((res) => res.blob())
        .then((blob) => {
          selectedQrCodeFile = new File([blob], "qrcode.png", {
            type: "image/png",
          });
        });

      node.style.display = "none";
      const previewContainer = document.getElementById(
        "qr_code_design_preview"
      );
      previewContainer.innerHTML = "";
      previewContainer.classList.add("qrCode_design_preview");
      previewContainer.style.display = "block";
      const img = document.createElement("img");
      img.src = dataUrl;
      img.alt = "QR Code Template Preview";
      previewContainer.appendChild(img);
      $("#TemplatePreviewModal").modal({
        backdrop: "static",
        keyboard: false,
      });
    })
    .catch(function (error) {
      node.style.display = "none";
      console.error("Error generating image:", error);
    });
}

function formatUSPhoneNumber(phoneNumber) {
  let cleaned = phoneNumber.replace('+1', '').replace(/\D/g, '');
  if (cleaned.length === 10) {
    return `(${cleaned.slice(0,3)}) ${cleaned.slice(3,6)}-${cleaned.slice(6)}`;
  } else {
    return phoneNumber;
  }
}

function addQrCode() {
  if (!selectedQrCodeFile) {
    showToastMessage("Please generate QR code preview first");
    return;
  }
  const phone_number = document.getElementById("qr_phone_number").value;
  const templateId = document.getElementById("templateId").value;
  const qr_id = document.getElementById("qr_id").value;

  if(!phone_number){
    showToastMessage("Please select phone number");
    return;
  }
  const formData = new FormData();
  formData.append("qr_code_image", selectedQrCodeFile);
  formData.append("phone_number", phone_number);
  formData.append("templateId", templateId);

  // Check if this is an edit or add operation
  if (qr_id) {
    formData.append("editQrCode", true);
    formData.append("id", qr_id);
  } else {
    formData.append("saveQrCode", true);
  }

  // Send to server using similar pattern as doors.js
  $.ajax({
    url: "/include/property_builder/qr_code/qr_code_requests.php",
    type: "post",
    data: formData,
    processData: false,
    contentType: false,
    success: function (resp) {
      showSuccessGlobalToastMessage(
        resp.message || "QR Code saved successfully"
      );
      // Reset the stored image
      selectedQrCodeImage = "";
      selectedQrCodeFile = null;
      $("#addQrCode").modal("hide");
      // Refresh the QR codes list
      sendQrCodeRequest({
        getQRCodeData: "yes",
        property_id: sessionStorage.getItem("propertyId"),
      });
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error) showToastMessage(xhr?.responseJSON?.error);
      else showToastMessage(error);
    },
  });
}


function printImage(image_url) {

  console.log("image_url", image_url);
  const print_image=`/shared/serve_image.php?path=${image_url}&type=all_images`
  
  const printWindow = window.open("", "_blank");

  printWindow.document.write(`
    <html>
      <head>
        <title>Print</title>
        <style>
          @page {
            size: A4 portrait; /* or landscape */
            margin: 0;
          }

          html, body {
            margin: 0;
            padding: 0;
            height: 100%;
          }
          img {
            display: block;
            width: 100%;
            height: auto;
          }
        </style>
      </head>
      <body>
        <img src="${print_image}" onload="window.print(); window.close();" />
      </body>
    </html>
  `);

  printWindow.document.close();
}