// src/pdf/invoiceTemplate.js
// Builds the branded payment-invoice PDF for Admin ▸ Invoices, using pdfkit.
// Layout mirrors a standard payment-request invoice: dark header with
// company details, a gold divider, invoice meta row, billed-to block,
// a description/amount table, total, amount in words, and a bank-transfer
// box the client pays into.
const PDFDocument = require('pdfkit');
const path = require('path');
const fs = require('fs');

const NAVY = '#0f1b2d';
const GOLD = '#d9a441';
const GOLD_DEEP = '#b3822c';
const INK = '#1c2430';
const MUTED = '#6b7280';
const LINE = '#e4e0d6';
const PANEL = '#f4f1e8';

const LOGO_PATH = path.join(__dirname, '..', '..', '..', 'public', 'assets', 'logo.jpg');

const COMPANY = {
  name: 'YELLOW STONE',
  nameLine2: 'TRADERS & GENERAL SUPPLIES',
  tagline: 'BUILT ON GOLD. GROUNDED IN ROCK.',
  address1: 'Mhongolo Ward, Kahama District',
  address2: 'Shinyanga Region, Tanzania',
  poBox: 'P.O. Box 472 · Postal Code 37310',
  phone: '+255 620 204 551',
  email: 'invoice@yellowstonetraders.co.tz',
  website: 'www.yellowstonetraders.co.tz'
};

function money(amount, currency) {
  const n = Number(amount || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return `${currency} ${n}`;
}

function statusLabel(status) {
  if (status === 'paid') return 'PAID';
  return 'AWAITING PAYMENT';
}

function statusColor(status) {
  return status === 'paid' ? '#2f7d4f' : GOLD_DEEP;
}

// Returns an open (not-yet-ended) PDFDocument. Caller pipes it to a
// response or file stream and calls doc.end() once done.
function renderInvoicePdf(invoice) {
  const doc = new PDFDocument({ size: 'A4', margin: 0 });
  const pageWidth = doc.page.width;
  const marginX = 48;
  const contentWidth = pageWidth - marginX * 2;

  // ---------------- Header ----------------
  const headerHeight = 128;
  doc.rect(0, 0, pageWidth, headerHeight).fill(NAVY);
  doc.rect(0, headerHeight, pageWidth, 6).fill(GOLD);

  if (fs.existsSync(LOGO_PATH)) {
    try {
      doc.image(LOGO_PATH, marginX, 28, { width: 68, height: 68 });
    } catch (e) { /* logo optional — invoice still renders without it */ }
  }

  const textX = marginX + 84;
  doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(20).text(COMPANY.name, textX, 30, { characterSpacing: 0.5 });
  doc.fontSize(11).text(COMPANY.nameLine2, textX, 52);
  doc.fillColor(GOLD).font('Helvetica-Bold').fontSize(8.5).text(COMPANY.tagline, textX, 68, { characterSpacing: 1 });
  doc.fillColor('#c7cdd8').font('Helvetica').fontSize(8.5);
  doc.text(`${COMPANY.address1}, ${COMPANY.address2}`, textX, 86);
  doc.text(`${COMPANY.phone}  |  ${COMPANY.email}`, textX, 98);
  doc.text(COMPANY.website, textX, 110);

  doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(22).text('PAYMENT INVOICE', marginX, 34, {
    width: contentWidth, align: 'right'
  });
  doc.fillColor(GOLD).font('Helvetica-Bold').fontSize(11).text(`#${invoice.invoice_number}`, marginX, 60, {
    width: contentWidth, align: 'right'
  });

  // ---------------- Meta row ----------------
  let y = headerHeight + 34;
  const colW = contentWidth / 3;
  const invoiceDate = new Date(invoice.created_at || Date.now());
  const dateLabel = invoiceDate.toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' });
  const currencyLabel = invoice.currency === 'USD' ? 'US Dollar (USD)' : 'Tanzanian Shilling (TZS)';

  function metaCell(x, label, value, valueColor) {
    doc.fillColor(MUTED).font('Helvetica-Bold').fontSize(8).text(label, x, y, { characterSpacing: 0.6 });
    doc.fillColor(valueColor || INK).font('Helvetica-Bold').fontSize(11).text(value, x, y + 13);
  }
  metaCell(marginX, 'INVOICE DATE', dateLabel);
  metaCell(marginX + colW, 'CURRENCY', currencyLabel);
  metaCell(marginX + colW * 2, 'STATUS', statusLabel(invoice.status), statusColor(invoice.status));

  y += 52;
  doc.moveTo(marginX, y).lineTo(pageWidth - marginX, y).strokeColor(LINE).lineWidth(1).stroke();

  // ---------------- Billed To ----------------
  y += 22;
  doc.fillColor(MUTED).font('Helvetica-Bold').fontSize(8).text('BILLED TO', marginX, y, { characterSpacing: 0.6 });
  y += 14;
  doc.fillColor(INK).font('Helvetica-Bold').fontSize(13).text(invoice.recipient_name || '', marginX, y);
  y += 18;
  if (invoice.recipient_address) {
    doc.fillColor(MUTED).font('Helvetica').fontSize(9.5);
    const addrLines = String(invoice.recipient_address).split('\n').filter(Boolean);
    addrLines.forEach((line) => {
      doc.text(line, marginX, y, { width: contentWidth });
      y += 13;
    });
  }

  // ---------------- Description / Amount table ----------------
  y += 16;
  const tableTop = y;
  doc.rect(marginX, tableTop, contentWidth, 24).fill(NAVY);
  doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(8.5);
  doc.text('DESCRIPTION / PURPOSE OF PAYMENT', marginX + 12, tableTop + 8, { characterSpacing: 0.4 });
  doc.text('AMOUNT', marginX, tableTop + 8, { width: contentWidth - 12, align: 'right', characterSpacing: 0.4 });

  const purposeText = invoice.official_purpose || invoice.purpose || 'Payment as agreed.';
  const amountText = money(invoice.amount, invoice.currency);
  doc.font('Helvetica').fontSize(10).fillColor(INK);
  const purposeHeight = doc.heightOfString(purposeText, { width: contentWidth - 190 });
  const rowHeight = Math.max(38, purposeHeight + 20);
  doc.rect(marginX, tableTop + 24, contentWidth, rowHeight).fill('#faf9f5');
  doc.fillColor(INK).font('Helvetica').fontSize(10).text(purposeText, marginX + 12, tableTop + 34, { width: contentWidth - 190 });
  doc.font('Helvetica-Bold').text(amountText, marginX, tableTop + 34, { width: contentWidth - 12, align: 'right' });

  const totalTop = tableTop + 24 + rowHeight;
  doc.rect(marginX, totalTop, contentWidth, 34).fill(PANEL);
  doc.fillColor(MUTED).font('Helvetica-Bold').fontSize(8.5).text('TOTAL AMOUNT DUE', marginX + 12, totalTop + 12, { characterSpacing: 0.5 });
  doc.fillColor(INK).font('Helvetica-Bold').fontSize(14).text(amountText, marginX, totalTop + 8, { width: contentWidth - 12, align: 'right' });

  y = totalTop + 34 + 14;
  doc.fillColor(MUTED).font('Helvetica-Oblique').fontSize(8.5).text(
    `(Amount in words: ${invoice.amountInWords})`, marginX, y, { width: contentWidth, align: 'center' }
  );

  // ---------------- Bank transfer box ----------------
  y += 30;
  doc.fillColor(INK).font('Helvetica-Bold').fontSize(9).text('PAY BY BANK TRANSFER TO', marginX, y, { characterSpacing: 0.4 });
  y += 16;
  const boxTop = y;
  const boxHeight = 78;
  doc.roundedRect(marginX, boxTop, contentWidth, boxHeight, 4).lineWidth(1.4).strokeColor(GOLD).stroke();
  doc.rect(marginX, boxTop, 4, boxHeight).fill(GOLD);

  const bankColW = contentWidth / 2;
  function bankCell(x, yy, label, value) {
    doc.fillColor(MUTED).font('Helvetica-Bold').fontSize(7.5).text(label, x, yy, { characterSpacing: 0.5 });
    doc.fillColor(INK).font('Helvetica-Bold').fontSize(11).text(value || '—', x, yy + 12);
  }
  bankCell(marginX + 20, boxTop + 16, 'BANK NAME', invoice.bank_name);
  bankCell(marginX + 20 + bankColW, boxTop + 16, 'ACCOUNT NAME', invoice.account_name);
  bankCell(marginX + 20, boxTop + 46, 'ACCOUNT NUMBER', invoice.account_number);
  bankCell(marginX + 20 + bankColW, boxTop + 46, 'ACCOUNT CURRENCY', invoice.currency === 'USD' ? 'US Dollar (USD)' : 'Tanzanian Shilling (TZS)');

  y = boxTop + boxHeight + 18;
  doc.fillColor(MUTED).font('Helvetica-Oblique').fontSize(8.5).text(
    `Please use "${invoice.invoice_number}" as the payment reference and share the deposit slip / transaction reference with ${COMPANY.email} to confirm receipt.`,
    marginX, y, { width: contentWidth }
  );

  // ---------------- Footer ----------------
  const footerY = doc.page.height - 56;
  doc.moveTo(marginX, footerY - 12).lineTo(pageWidth - marginX, footerY - 12).strokeColor(LINE).lineWidth(1).stroke();
  doc.fillColor(MUTED).font('Helvetica').fontSize(8).text(
    `YELLOW STONE TRADERS & GENERAL SUPPLIES  •  ${COMPANY.address1}, ${COMPANY.address2}  •  ${COMPANY.phone}  •  ${COMPANY.email}`,
    marginX, footerY, { width: contentWidth, align: 'center' }
  );
  doc.text('This is a computer-generated payment invoice and is valid without a signature.', marginX, footerY + 12, {
    width: contentWidth, align: 'center'
  });

  return doc;
}

module.exports = { renderInvoicePdf };
