function GetElement(id) {
  if (document.getElementById(id).classList.contains("kform-radio-group")) {
    const allOptions = document.querySelectorAll("[id^='" + id + "_']");
    let checkedOption = "";
    allOptions.forEach((opt) => {
      if (opt.checked) checkedOption = opt.value;
    });
    return checkedOption;
  } else if (
    document.getElementById(id).getAttribute("type") == "FileUploader"
  ) {
    var ul = document.getElementById(id + "-items");
    var items = ul.querySelectorAll("li");
    var allItems = [];
    for (var l = 0; l < items.length; l++) {
      allItems.push({ FileURL: items[l].getAttribute("item-url") });
    }
    return allItems;
  } else {
    return document.getElementById(id).value;
  }
}

function GetGridItems(gridName) {
  const gridWrapper = document.getElementById(gridName);
  if (!gridWrapper) return [];

  const rows = gridWrapper.querySelectorAll("table > tbody > tr");

  const result = [];

  rows.forEach((tr) => {
    const rowObj = {};

    const itemId = tr.getAttribute("K_Item_ID");
    rowObj["ID"] = itemId === "NewItem" ? null : itemId;

    // For each input/select inside the row
    tr.querySelectorAll("input, select").forEach((input) => {
      // ID format: K_Grid_Input_<gridName>_<columnName>_<itemID>
      const idParts = input.id.split("_");
      const colName = idParts[4]; // After grid name

      let value = input.value;

      // Convert numbers automatically
      if (input.type === "number") {
        value = value !== "" ? Number(value) : null;
      }

      rowObj[colName] = value;
    });

    result.push(rowObj);
  });

  return result;
}

async function GetGridListAllItems(gridName) {
  const grid = document.getElementById(gridName);
  var site = grid.getAttribute("siteurl");
  var listName = grid.getAttribute("listname");
  let url = `${site}/_api/web/lists/getbytitle('${listName}')/items?`;

  url += `&$orderby=Id`;

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

  if (!response.ok) {
    const txt = await response.text();
    throw new Error("SharePoint REST query failed:\n" + txt);
  }

  const json = await response.json();
  return json.d.results;
}
