/**
 * Google Sheets business automation - Apps Script (sample project built to show the approach).
 * Next invoice number by tax type, PDF export to the client's Drive folder, Gmail DRAFT (never sent),
 * and a payables intake that holds low-confidence extractions for a human check.
 */
const SS = SpreadsheetApp.getActive();
const DEFAULT_FOLDER_ID = 'YOUR_DRIVE_FOLDER_ID';
const CONFIDENCE_MIN = 0.8;

/** TAX-YYYY-0001 for domestic customers, INV-YYYY-0001 for everyone else. */
function nextInvoiceNumber(taxType, year) {
  const prefix = taxType === 'Domestic' ? 'TAX' : 'INV';
  year = year || new Date().getFullYear();
  const stem = `${prefix}-${year}-`;
  const nums = SS.getSheetByName('Invoices').getRange('A5:A').getDisplayValues().flat()
    .filter(n => n.startsWith(stem)).map(n => Number(n.slice(stem.length)));
  return stem + String((nums.length ? Math.max(...nums) : 0) + 1).padStart(4, '0');
}

/** Domestic 10%, cross-border B2B reverse charge 0%, export 0%. Edit to your own tax table. */
function taxRate(taxType) { return taxType === 'Domestic' ? 0.10 : 0; }

/** Export the InvoiceForm sheet as an A4 PDF into the client's Drive folder. */
function exportInvoicePdf(invoiceNo, folderId) {
  const sheet = SS.getSheetByName('InvoiceForm');
  const url = `https://docs.google.com/spreadsheets/d/${SS.getId()}/export?format=pdf` +
    `&gid=${sheet.getSheetId()}&portrait=true&size=A4&fitw=true&gridlines=false`;
  const blob = UrlFetchApp.fetch(url, { headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() } })
    .getBlob().setName(invoiceNo + '.pdf');
  return DriveApp.getFolderById(folderId || DEFAULT_FOLDER_ID).createFile(blob);
}

/** Create (not send) a Gmail draft with the PDF attached, for a person to review. */
function createInvoiceDraft(email, invoiceNo, file) {
  return GmailApp.createDraft(email, `Invoice ${invoiceNo}`,
    `Hello,\n\nPlease find invoice ${invoiceNo} attached.\n\nKind regards`,
    { attachments: [file.getAs(MimeType.PDF)] });
}

/** One-click flow from the invoice form. */
function issueInvoice() {
  const f = SS.getSheetByName('InvoiceForm');
  const taxType = f.getRange('B3').getValue(), email = f.getRange('B4').getValue();
  const no = nextInvoiceNumber(taxType);
  f.getRange('B1').setValue(no);
  SpreadsheetApp.flush();
  const pdf = exportInvoicePdf(no, f.getRange('B5').getValue());
  createInvoiceDraft(email, no, pdf);
  logSalesLines(no);
  SS.toast(`${no} saved to Drive and drafted in Gmail (not sent)`);
}

/** Copy the invoice's line items to the sales analytics sheet. */
function logSalesLines(invoiceNo) {
  const f = SS.getSheetByName('InvoiceForm');
  const lines = f.getRange('A10:D30').getValues().filter(r => r[0]);
  const out = SS.getSheetByName('SalesLog');
  lines.forEach(r => out.appendRow([new Date(), invoiceNo, ...r]));
}

/** Payables intake: called with fields extracted from a supplier PDF. */
function logPayable(supplier, amount, dueDate, confidence) {
  const status = confidence < CONFIDENCE_MIN ? 'Check' : 'OK';
  SS.getSheetByName('Payables').appendRow([supplier, amount, dueDate, confidence, status]);
  return status; // only 'OK' rows are forwarded to the accountant
}
