/**
 * Menu entry to run from the sheet
 */
function onOpen() {
  SpreadsheetApp.getUi().createMenu('Send leads')
    .addItem('Post all rows', 'postAllRows')
    .addToUi();
}

/**
 * Lead Capture Campaign Configuration
 */
const ENDPOINT_URL = 'https://www.encoreform.com/forms/xxx/yyy';  // change me
const SHEET_NAME = 'Sheet1';                              // change if needed
const FIRST_DATA_ROW = 2;                                 // 1 for headers, 2 for first record
const STATUS_COL =  lastCol => lastCol + 1;               // writes status in the next free column

/**
 * Main runner, posts each row as a form payload
 */
function postAllRows() {
  const sheet = SpreadsheetApp.getActive().getSheetByName(SHEET_NAME);
  const range = sheet.getDataRange();
  const values = range.getValues();
  if (values.length < FIRST_DATA_ROW) {
    Logger.log('No data rows found');
    return;
  }

  const headers = values[0].map(h => String(h).trim());
  const lastColIndex = headers.length;                    // 1 based when writing
  sheet.getRange(1, STATUS_COL(lastColIndex), 1, 1).setValue('Post Status');

  for (let r = FIRST_DATA_ROW - 1; r < values.length; r++) {
    const row = values[r];
    if (row.every(cell => String(cell).trim() === '')) {
      continue; // skip empty row
    }

    const payload = {};
    headers.forEach((key, i) => {
      if (!key) return;
      payload[key] = row[i] == null ? '' : row[i];
    });

    const result = tryPost(payload);
    const status = result.ok
      ? `OK ${result.code}`
      : `ERR ${result.code} ${(result.body || '').toString().slice(0, 120)}`;

    // write status
    sheet.getRange(r + 1, STATUS_COL(lastColIndex), 1, 1).setValue(status);
    Utilities.sleep(200); // gentle pacing
  }
}

/**
 * POST with simple retry and backoff
 */
function tryPost(payload) {
  const options = {
    method: 'post',
    payload,                          // form encoded by default
    followRedirects: true,
    muteHttpExceptions: true,
  };

  let attempt = 0;
  let waitMs = 500;
  while (attempt < 3) {
    attempt++;
    try {
      const res = UrlFetchApp.fetch(ENDPOINT_URL, options);
      const code = res.getResponseCode();
      if (code >= 200 && code < 300) {
        return { ok: true, code, body: res.getContentText() };
      }
      if (code >= 500) {
        Utilities.sleep(waitMs);
        waitMs *= 2;
        continue;
      }
      return { ok: false, code, body: res.getContentText() };
    } catch (e) {
      if (attempt >= 3) return { ok: false, code: 'NET', body: String(e) };
      Utilities.sleep(waitMs);
      waitMs *= 2;
    }
  }
  return { ok: false, code: 'UNK', body: '' };
}
