// Функция для динамической загрузки скрипта
function loadScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

// Основной код
document.addEventListener("DOMContentLoaded", async () => {
  console.log("test.js загружен");

  if (
    window.location.href.includes("dealInvoice?id")
  ) {
      try {
        const el = document.querySelector(".p7.ft9");
        el.innerHTML = el.innerHTML.replace("СЧЕТ ", "");
        document.querySelector(".p6.ft8").style.color = "red";
        document.querySelector(".p6.ft8").style.fontWeight = "bold";
        const style = document.createElement("style");
        style.innerHTML = `
          @media print {
            .p6.ft8 {
              color: red !important;
            }
          }
        `;
document.head.appendChild(style);
        await loadScript("https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.js");

        console.log("Скрипт QRCode.js загружен, формируем QR");

        generateQRCode();
      } catch (error) {
        console.error("Ошибка при загрузке скрипта:", error);
      }
    }
});

// Генерация QR-кода с новыми данными
function generateQRCode() {
    const orderElement = document.querySelector(".tr3.td21 .p4.ft5");
    const orderNumberElement = document.querySelector(".p7.ft9");

    if (!orderElement || !orderNumberElement) {
      console.warn("Элемент с номером заказа или описанием не найден");
      return;
    }

    const orderText = orderElement.innerHTML.trim();
    const orderNumberText = orderNumberElement.innerHTML;

    const match = orderNumberText.match(/\/(\d+)/);
    let number = match ? match[1] : "";

    if (!number) {
      console.warn("Номер заказа не найден");
    } else {
      console.log("Номер заказа:", number);
    }

    let purpose = `№${number}. ${orderText}. Без НДС`;
    purpose = purpose.trim().replace(/\s+/g, " ");

    const sumElement = document.querySelectorAll('.tr9.td22 .p15.ft0')[1];

    if (!sumElement) {
      console.warn("Элемент с суммой не найден");
      return;
    }

    const sum = sumElement.innerHTML.replace(/\D/g, "");
    if (!sum) {
      console.warn("Сумма не найдена или невалидна");
      return;
    }

    const innElement = document.querySelector(".p8.ft1");
    if (!innElement) {
      console.warn("Элемент с ИНН не найден");
      return;
    }

    const innText = innElement.innerHTML;
    const innMatch = innText.match(/ИНН\s+(\d{10})/);
    const inn = innMatch ? innMatch[1] : "";

    if (!inn) {
      console.warn("ИНН не найден");
    } else {
      console.log("ИНН покупателя:", inn);
    }

    const qrData = [
      'ST00012',
      'Name=БФ "Выход Есть Всегда"',
      'PersonalAcc=40703810362000002852',
      'BankName="Банк Татарстан" №8610 ПАО Сбербанк',
      'BIC=049205603',
      'CorrespAcc=30101810600000000603',
      'PayeeINN=1655414967',
      `PayerINN=${inn}`,
      'KPP=165701001',
      `Purpose=${purpose}`,
      `Sum=${sum}`
    ].join('|');

    console.log("QR DATA:", qrData);

    const qrContainer = document.querySelector(".t0 td img").parentElement;
    qrContainer.querySelector("img").remove();
    const qr = qrcode(0, "M");
    qr.addData(toUtf8Bytes(qrData));
    qr.make();
    qrContainer.innerHTML = qr.createImgTag(6, 0, 130);
    qrContainer.querySelector("img").style.width = "130px";
    qrContainer.querySelector("img").style.height = "130px";

    function toUtf8Bytes(str) {
      return unescape(encodeURIComponent(str));
    }
  
}
