/** @OnlyCurrentDoc */
/**
 * The Circuit Edit | Invoice Reminder Lab v1.2 (2026-11-15)
 * Google Sheets + MailApp. Bound script; no third-party services.
 * @OnlyCurrentDoc limits Sheets file access to this bound document where supported.
 * SAFE BY DEFAULT: live sending is OFF, demo addresses use .invalid.
 * This is an educational project, not a payment processor.
 */
const IR = {
  invoices: 'Invoices', settings: 'Settings', log: 'Send Log', firstDataRow: 2,
  headers: ['Invoice ID','Customer Name','Customer Email','Amount','Currency','Due Date','Payment Status','Invoice Link','Reminder Count','Last Reminder Sent','Delivery State','Last Error']
};

function onOpen() {
  SpreadsheetApp.getUi().createMenu('Invoice Reminders')
    .addItem('1. Preview due reminders (no email)', 'previewDueReminders')
    .addItem('2. Send a TEST to my inbox', 'sendTestReminder')
    .addSeparator()
    .addItem('3. Send LIVE reminders (opt-in only)', 'sendDueReminders')
    .addItem('4. Install daily trigger (opt-in only)', 'installDailyTrigger')
    .addItem('5. Remove daily trigger', 'removeDailyTrigger')
    .addToUi();
}

function getSettings_() {
  const sh = requireSheet_(IR.settings);
  const values = sh.getDataRange().getValues();
  const raw = {};
  for (let i = 1; i < values.length; i++) raw[String(values[i][0]).trim()] = values[i][1];
  const number = (key, fallback, min, max) => {
    const v = String(raw[key] == null ? '' : raw[key]).trim();
    if (!/^\d+$/.test(v)) return fallback;
    return Math.min(max, Math.max(min, Number(v)));
  };
  return {
    business: String(raw.BusinessName || 'Your Business').trim().slice(0, 100),
    liveEnabled: String(raw.LiveSendingEnabled).trim().toUpperCase() === 'TRUE',
    testRecipient: String(raw.TestRecipient || '').trim(),
    replyTo: String(raw.ReplyTo || '').trim(),
    graceDays: number('GraceDays', 1, 1, 60),
    intervalDays: number('IntervalDays', 7, 1, 90),
    maxReminders: number('MaxReminders', 2, 1, 5),
    maxPerRun: number('MaxEmailsPerRun', 5, 1, 25)
  };
}
function requireSheet_(name) {
  const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
  if (!sh) throw new Error('Missing sheet "' + name + '". Import the provided template and keep sheet names unchanged.');
  return sh;
}
function emailIsValid_(email, allowPlaceholder) {
  const value = String(email || '').trim();
  if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(value)) return false;
  if (!allowPlaceholder && /\.(invalid|example|test)$/i.test(value)) return false;
  return true;
}
function localDateKey_(value, tz) {
  if (Object.prototype.toString.call(value) === '[object Date]' && !isNaN(value.getTime())) {
    return Utilities.formatDate(value, tz, 'yyyy-MM-dd');
  }
  if (/^\d{4}-\d{2}-\d{2}$/.test(String(value).trim())) return String(value).trim();
  return '';
}
function dayNumber_(key) {
  const parts = key.split('-').map(Number);
  return Date.UTC(parts[0], parts[1] - 1, parts[2]) / 86400000;
}
function dueReason_(row, nowKey, tz, cfg) {
  const invoiceId = String(row[0] || '').trim();
  const status = String(row[6] || '').trim().toUpperCase();
  const delivery = String(row[10] || '').trim().toUpperCase();
  if (!invoiceId || status !== 'UNPAID' || delivery === 'SENDING' || delivery === 'ERROR') return '';
  const due = localDateKey_(row[5], tz);
  if (!due || dayNumber_(nowKey) - dayNumber_(due) < cfg.graceDays) return '';
  const sentCount = Number(row[8]) || 0;
  if (sentCount >= cfg.maxReminders) return '';
  const lastSent = localDateKey_(row[9], tz);
  if (lastSent && dayNumber_(nowKey) - dayNumber_(lastSent) < cfg.intervalDays) return '';
  return 'Invoice is overdue and eligible';
}
/**
 * Resolve a nonempty time zone string for Utilities.formatDate.
 * Some imported spreadsheets may return an unavailable/empty time zone.
 * We fall back to the script time zone, then to UTC (never pass null/undefined).
 */
function getTimeZone_() {
  let tz = '';
  try {
    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    if (spreadsheet) tz = spreadsheet.getSpreadsheetTimeZone();
  } catch (err) {
    Logger.log('Spreadsheet time zone unavailable; trying script time zone.');
  }
  if (typeof tz !== 'string' || !tz.trim()) {
    try { tz = Session.getScriptTimeZone(); } catch (err) { tz = ''; }
  }
  return (typeof tz === 'string' && tz.trim()) ? tz.trim() : 'Etc/UTC';
}

function getCandidates_(cfg) {
  const sh = requireSheet_(IR.invoices);
  const data = sh.getDataRange().getValues();
  const headers = data[0] || [];
  if (IR.headers.some((h, i) => headers[i] !== h)) throw new Error('Invoice columns changed. Restore the provided header row.');
  const tz = getTimeZone_();
  const nowKey = Utilities.formatDate(new Date(), tz, 'yyyy-MM-dd');
  const ids = {};
  data.slice(1).forEach(r => {const id=String(r[0]||'').trim(); if (id) ids[id]=(ids[id]||0)+1;});
  const rows = [];
  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const id = String(row[0] || '').trim();
    if (!id || ids[id] > 1) continue; // no sends when an invoice ID is duplicated
    if (dueReason_(row, nowKey, tz, cfg)) rows.push({sheetRow:i+1, data:row, nowKey:nowKey, tz:tz});
  }
  return rows;
}
function alertMessage_(msg) {
  SpreadsheetApp.getActiveSpreadsheet().toast(msg, 'Invoice Reminders', 8);
  Logger.log(msg);
}
function previewDueReminders() {
  const cfg = getSettings_();
  const candidates = getCandidates_(cfg);
  alertMessage_(candidates.length + ' eligible invoice(s). PREVIEW ONLY — no email sent.');
  return candidates.map(x => x.data[0]);
}
function escapeHtml_(s) {
  return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
function makeMessage_(row, business, tz, test) {
  const id = String(row[0]).trim();
  const customer = String(row[1] || 'there').trim().slice(0,120);
  const amount = Number(row[3]);
  const currency = String(row[4] || 'USD').trim().toUpperCase().slice(0,3);
  const sum = Number.isFinite(amount) && amount >= 0 ? currency + ' ' + amount.toFixed(2) : 'See your invoice';
  const due = localDateKey_(row[5], tz);
  const url = String(row[7] || '').trim();
  const safeUrl = /^https:\/\/[a-z0-9.-]+(?::\d+)?(?:\/[^\s<>"']*)?$/i.test(url) ? url : '';
  const subject = (test ? '[TEST — NO CUSTOMER SENT] ' : '') + 'Friendly reminder: invoice ' + id;
  const intro = 'Hi ' + customer + ',\n\nOur records show that invoice ' + id + ' (' + sum + ') was due on ' + due + ' and is still marked unpaid. If you have already paid, please disregard this message or reply so we can update our records.\n\n';
  const body = intro + (safeUrl ? 'Invoice: ' + safeUrl + '\n\n' : '') + 'Thank you,\n' + business;
  const html = '<div style="font:15px/1.65 Arial,sans-serif;color:#173E38;max-width:600px">'
    + '<p>Hi ' + escapeHtml_(customer) + ',</p>'
    + '<p>Our records show invoice <strong>' + escapeHtml_(id) + '</strong> (' + escapeHtml_(sum)
    + ') was due on <strong>' + escapeHtml_(due) + '</strong> and is still marked unpaid.</p>'
    + (safeUrl ? '<p><a href="' + escapeHtml_(safeUrl) + '">View invoice</a></p>' : '')
    + '<p>If you have already paid, please disregard this reminder or reply so we can update our records.</p>'
    + '<p>Thank you,<br>' + escapeHtml_(business) + '</p>'
    + (test ? '<p style="padding:10px;background:#FFF2DF"><strong>TEST ONLY:</strong> Customer was not contacted. No reminder counters were changed.</p>' : '')
    + '</div>';
  return {subject:subject, body:body, html:html};
}
function writeLog_(invoiceId, recipient, action, details) {
  requireSheet_(IR.log).appendRow([new Date(), invoiceId, recipient, action, details]);
}
function sendTestReminder() {
  const cfg = getSettings_();
  if (!emailIsValid_(cfg.testRecipient, false)) throw new Error('Enter your OWN real email address in Settings > TestRecipient before testing.');
  const candidates = getCandidates_(cfg);
  if (!candidates.length) throw new Error('No eligible UNPAID invoices. Check Due Date and GraceDays.');
  if (MailApp.getRemainingDailyQuota() < 1) throw new Error('Google MailApp daily recipient quota is exhausted.');
  const candidate = candidates[0];
  const msg = makeMessage_(candidate.data, cfg.business, candidate.tz, true);
  const options = {name:cfg.business, htmlBody:msg.html};
  if (emailIsValid_(cfg.replyTo, false)) options.replyTo = cfg.replyTo;
  MailApp.sendEmail(cfg.testRecipient, msg.subject, msg.body, options);
  writeLog_(candidate.data[0], cfg.testRecipient, 'TEST', 'Test inbox only; customer not contacted, counts unchanged');
  alertMessage_('TEST SENT to ' + cfg.testRecipient + '. Check inbox and spam folder.');
}
function sendDueReminders() {
  const cfg = getSettings_();
  if (!cfg.liveEnabled) {
    alertMessage_('SAFE MODE: LiveSendingEnabled is FALSE. No customer emails were sent.');
    return;
  }
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(15000)) throw new Error('A reminder run is already active. Try again later.');
  let sent = 0;
  try {
    const candidates = getCandidates_(cfg);
    const quota = MailApp.getRemainingDailyQuota();
    const limit = Math.min(cfg.maxPerRun, quota);
    const sh = requireSheet_(IR.invoices);
    for (let i=0;i<candidates.length && sent<limit;i++) {
      const entry = candidates[i], row = entry.data;
      const recipient = String(row[2]||'').trim();
      if (!emailIsValid_(recipient, false)) {writeLog_(row[0], recipient, 'SKIPPED', 'Missing, invalid, or reserved demo email'); continue;}
      // Re-check current values in case someone edited the invoice since scanning it.
      const latest = sh.getRange(entry.sheetRow,1,1,12).getValues()[0];
      if (String(latest[0]).trim() !== String(row[0]).trim() || !dueReason_(latest, entry.nowKey, entry.tz, cfg)) continue;
      sh.getRange(entry.sheetRow,11).setValue('SENDING');
      sh.getRange(entry.sheetRow,12).setValue('');
      SpreadsheetApp.flush(); // write claim BEFORE any email; a crash requires manual review, not duplicate send
      const msg = makeMessage_(latest,cfg.business,entry.tz,false);
      try {
        const options = {name:cfg.business,htmlBody:msg.html};
        if (emailIsValid_(cfg.replyTo, false)) options.replyTo = cfg.replyTo;
        MailApp.sendEmail(recipient,msg.subject,msg.body,options);
        // Count only after sendEmail returns successfully.
        sh.getRange(entry.sheetRow,9,1,4).setValues([[Number(latest[8]||0)+1,new Date(),'SENT','']]);
        SpreadsheetApp.flush();
        sent++;
        writeLog_(latest[0],recipient,'SENT','Live reminder sent; count incremented');
      } catch(err) {
        sh.getRange(entry.sheetRow,11).setValue('ERROR');
        sh.getRange(entry.sheetRow,12).setValue('Review Sent Mail before resetting to READY: ' + String(err).slice(0,180));
        SpreadsheetApp.flush();
        writeLog_(latest[0],recipient,'ERROR','Manual verification required before retry');
      }
    }
    alertMessage_(sent+' live reminder(s) sent; '+candidates.length+' eligible candidates scanned.');
  } finally {
    SpreadsheetApp.flush();
    lock.releaseLock();
  }
}
function installDailyTrigger() {
  const cfg=getSettings_();
  if(!cfg.liveEnabled) throw new Error('LiveSendingEnabled must be TRUE before installing a daily sending trigger. First run a TEST.');
  const existing=ScriptApp.getProjectTriggers().filter(t=>t.getHandlerFunction()==='sendDueReminders');
  if(existing.length) {alertMessage_('Daily trigger already exists.'); return;}
  ScriptApp.newTrigger('sendDueReminders').timeBased().everyDays(1).atHour(9).create();
  alertMessage_('Daily reminder trigger installed. Approx. 9–10 AM in script time zone.');
}
function removeDailyTrigger() {
  ScriptApp.getProjectTriggers().filter(t=>t.getHandlerFunction()==='sendDueReminders').forEach(t=>ScriptApp.deleteTrigger(t));
  alertMessage_('Daily reminder triggers removed.');
}

