var SITE_URL = ""
var LIST_NAME = ""

async function loadSharePointItem(siteUrl, listName) {
  showLoader();

  try {

    SITE_URL = siteUrl;
    LIST_NAME = listName;

    const params = new URLSearchParams(window.location.search);
    const itemId = params.get("ItemID");
    if (!itemId) throw new Error("ItemID parameter not found.");
    if (itemId == "NewItem") {
      hideLoader();
      return;
    }

    const endpoint = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items(${itemId})`;

    const response = await fetch(endpoint, {
      method: "GET",
      headers: { Accept: "application/json;odata=verbose" },
    });

    if (!response.ok) throw new Error("Failed to fetch item.");

    const data = await response.json();
    const item = data.d;

    // populate the K_ fields
    debugger;
    populateFieldsFromItem(item);

    hideLoader();
  } catch (err) {
    hideLoader();
  }
}

async function loadSharePointItemForOneField(siteUrl, listName, id) {
  try {
    const params = new URLSearchParams(window.location.search);
    const itemId = params.get("ItemID");
    if (!itemId) throw new Error("ItemID parameter not found.");
    if (itemId == "NewItem") {
      hideLoader();
      return;
    }

    const endpoint = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items(${itemId})`;

    const response = await fetch(endpoint, {
      method: "GET",
      headers: { Accept: "application/json;odata=verbose" },
    });

    if (!response.ok) throw new Error("Failed to fetch item.");

    const data = await response.json();
    const item = data.d;

    // populate the K_ fields
    debugger;
    populateFieldsFromItem(item, id);
  } catch (err) {}
}

async function getItemFromList(siteUrl, listName, itemId) {
  try {
    const endpoint = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items(${itemId})`;

    const response = await fetch(endpoint, {
      method: "GET",
      headers: { Accept: "application/json;odata=verbose" },
    });

    if (!response.ok) throw new Error("Failed to fetch item.");

    const data = await response.json();
    const item = data.d;

    return item;
  } catch (err) {}
}

function populateFieldsFromItem(item, field) {
  // find all elements whose id starts with K_
  debugger;
  const elements = field == undefined ? document.querySelectorAll("[id^='K_']") : [document.getElementById(field)];

  elements.forEach(async (el) => {
    const parts = el.id.split("_");

    // only accept IDs with exactly 2 parts: ["K", "Name"]
    if (parts.length !== 2) return;

    const fieldName = parts[1];

    // check if SharePoint item has that field
    if (
      item[fieldName] !== undefined &&
      item[fieldName] != "" &&
      item[fieldName] != null ||
      (el.classList.contains("kform-lookup-select") &&
        el.getAttribute("saveId") == "false")
    ) {
      if (el.classList.contains("kform-radio-group")) {
        var allOptions = document.querySelectorAll("[id^='" + el.id + "_']");
        allOptions.forEach((opt) => {
          if (opt.value == item[fieldName]) opt.checked = "checked";
        });
      } else if (el.classList.contains("kform-multilookup") || el.classList.contains("kform-multiuserpicker")) {
        el.setValue(item[fieldName].results);
      } else if (el.classList.contains("kform-lookup-select")) {
        if (el.getAttribute("saveId") == "true") {
          el.value = item[fieldName];
        } else if (el.getAttribute("saveId") == "false") {
          el.value = item[fieldName.replace("Id", "")];
        }
      } else if (
        el.getAttribute("type") == "text" &&
        el.getAttribute("data-original-type") == "number"
      ) {
        let raw = item[fieldName].toString().replace(/[^\d]/g, "");
        if (raw) {
          el.value = raw.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        } else el.value = "";
        el.setSelectionRange(el.value.length, el.value.length);
      } else if (el.getAttribute("data-jdp") == "true") {
        debugger;
        el.value = new Date(item[fieldName]).toLocaleDateString(
          "fa-IR-u-nu-latn"
        );
      } else if(el.getAttribute("input-type") == "userpicker") {
        await fetch(
            `${SITE_URL}/_api/web/getuserbyid(${item[fieldName]})`,
            {
              method: "POST",
              headers: {
                Accept: "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest":
                  document.getElementById("__REQUESTDIGEST").value,
              },
            }
          )
            .then((res) => res.json())
            .then((data) => {
              debugger;
              const user = data.d;
                el.value = user.Title;
                el.dataset.login = user.LoginName;
            })
            .catch((err) => {
              console.error("User picker failed:", err);
            });
      } else {
        el.value = item[fieldName];
      }

      el.dispatchEvent(new Event("change", { bubbles: true }));
    }
  });
}
