// Matheel for Google Sheets: every new row in the "Invoices" sheet becomes a ZATCA invoice, its PDF saved to Drive.
// Setup (once): Extensions → Apps Script → paste this file → Project Settings → Script properties:
//   MATHEEL_KEY   = your Matheel key (mtl_…), leave empty to try the sandbox
//   DEVICE_TOKEN  = the device_token from your activation link (mdt1.…)
// Sheet "Invoices", row 1 is headers: A item name | B quantity | C unit price before VAT | D status | E PDF | F error
// Then reload the sheet: a "ماثل" menu appears. Optional: Triggers → fileNewRows → time-driven, every minute.

const MATHEEL_URL = "https://matheel.app/api/v1/invoices";

/** Adds the ماثل menu to the sheet. */
function onOpen() {
  SpreadsheetApp.getUi().createMenu("ماثل").addItem("أصدر الفواتير الجديدة", "fileNewRows").addToUi();
}

/** Files every row that has an item name and no status yet, one at a time, and writes the result back. */
function fileNewRows() {
  // The invoice chain must advance one invoice at a time: the script lock makes a menu click and a trigger wait for each other.
  const lock = LockService.getScriptLock();
  lock.waitLock(60000);
  try {
    const sheet = SpreadsheetApp.getActive().getSheetByName("Invoices");
    const rows = sheet.getDataRange().getValues();
    for (let i = 1; i < rows.length; i++) {
      const [name, quantity, price, status] = rows[i];
      if (!name || status) continue;
      const result = fileOne_(String(name), Number(quantity) || 1, String(price));
      sheet.getRange(i + 1, 4, 1, 3).setValues([[result.status, result.pdfUrl || "", result.error || ""]]);
      SpreadsheetApp.flush();
      if (result.stop) break; // a bad key or token fails every row the same way: stop instead of repeating it
    }
  } finally {
    lock.releaseLock();
  }
}

function fileOne_(name, quantity, price) {
  const props = PropertiesService.getScriptProperties();
  const key = props.getProperty("MATHEEL_KEY");
  const token = props.getProperty("DEVICE_TOKEN");
  const res = UrlFetchApp.fetch(MATHEEL_URL, {
    method: "post",
    contentType: "application/json",
    muteHttpExceptions: true,
    headers: key ? { Authorization: "Bearer " + key } : {},
    payload: JSON.stringify({
      device_token: token,
      pdf: true,
      invoice: { type: "simplified", line_items: [{ name: name, quantity: quantity, price: price }] }
    })
  });
  const code = res.getResponseCode();
  const body = JSON.parse(res.getContentText() || "{}");
  if (code !== 200) {
    return { status: "error " + code, error: JSON.stringify(body.error || body.errors || body), stop: !(code === 422 && body.errors) };
  }
  props.setProperty("DEVICE_TOKEN", body.device_token); // the next invoice must use the new token
  const file = DriveApp.createFile(
    Utilities.newBlob(Utilities.base64Decode(body.pdf), "application/pdf", "invoice-" + body.counter + ".pdf")
  );
  return { status: body.status, pdfUrl: file.getUrl() };
}
