import PDFDocument from 'pdfkit';
import { InvoiceType, TenantKind } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { isPlaceholderEmail } from '../../lib/no-login';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { NotFoundError } from '../../lib/errors';
import { getTenantFileBytes } from '../uploads/uploads.service';
import { periodEnd } from '../../lib/period';

/**
 * The printable invoice / receipt, rendered server-side.
 *
 * The web prints its own DOM with `window.print()`, which has no mobile
 * equivalent — so the document is built here instead and both clients
 * download the same bytes. One layout, one source of truth.
 *
 * The layout follows the Visionus house style shared with GymCare: a dark
 * header band carrying the hostel's identity, BILL TO beside PAYMENT DETAILS,
 * an itemised fee table, a total block, the payments received, terms and a
 * footer. It answers the questions a parent or an accountant asks of a
 * receipt: who, which room, how much, for which period, paid when, and the
 * payment / transaction reference to quote.
 *
 * Amounts are whole rupees (see `prisma/schema.prisma`); nothing here divides.
 * The endpoint, file name and invoice number are unchanged from the previous
 * layout, so existing app builds keep working and simply receive the new
 * document.
 */

// ── Formatting ─────────────────────────────────────────────────────────────

/** ₹ is not in pdfkit's built-in fonts, so the ASCII form is used throughout. */
const money = (rupees: number) =>
  `Rs. ${rupees.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

const dayLabel = (d: Date | null | undefined) =>
  d ? d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' }) : '-';

const monthLabel = (periodMonth: string) =>
  new Date(`${periodMonth}-01T00:00:00Z`).toLocaleDateString('en-IN', { month: 'long', year: 'numeric', timeZone: 'UTC' });

/** "01 Sep 2026 - 30 Nov 2026": the months an invoice covers, as dates. */
function feePeriod(periodMonth: string, cycleMonths = 1): string {
  const [y, m] = periodMonth.split('-').map(Number);
  const [ey, em] = periodEnd(periodMonth, cycleMonths).split('-').map(Number);
  const start = new Date(Date.UTC(y, m - 1, 1));
  const end = new Date(Date.UTC(ey, em, 0));
  return `${dayLabel(start)} - ${dayLabel(end)}`;
}

/** "October 2026", or "October 2026 - December 2026" for a multi-month cycle. */
function periodLabel(periodMonth: string, cycleMonths = 1): string {
  return cycleMonths > 1 ? `${monthLabel(periodMonth)} - ${monthLabel(periodEnd(periodMonth, cycleMonths))}` : monthLabel(periodMonth);
}

/** Human, stable, and unique enough to quote on the phone. Matches the clients. */
export const invoiceNumber = (id: string, periodMonth: string) =>
  `INV-${periodMonth.replace('-', '')}-${id.slice(0, 6).toUpperCase()}`;

/** The payment's own reference, printed on the receipt and shown in the apps. */
export const paymentNumber = (id: string) => `PAY-${id.slice(0, 8).toUpperCase()}`;

/** The grey caption under a billing-rule line's title. */
const LINE_KIND_SUB: Record<string, string> = {
  CHARGE: 'Additional charge',
  LATE_FEE: 'Charged after the grace period',
  PRORATA_CREDIT: 'Credit for days not stayed',
  GST: 'Hostel accommodation above the exemption limit',
  MESS: 'Mess',
};

/** The same captions in a dormitory's words: nothing about hostels or mess. */
const DORM_LINE_KIND_SUB: Record<string, string> = {
  CHARGE: 'Additional charge',
  LATE_FEE: 'Charged after the due date',
  PRORATA_CREDIT: 'Credit',
  GST: 'GST on accommodation',
};

const METHOD_LABEL: Record<string, string> = { CASH: 'Cash', UPI: 'UPI', CARD: 'Card', BANK_TRANSFER: 'Bank transfer', CHEQUE: 'Cheque', OTHER: 'Other', ONLINE: 'Online (Razorpay)' };
const methodLabel = (m: string | null | undefined) => (m ? (METHOD_LABEL[m] ?? m) : '-');

// ── Palette (GymCare house style; the accent is the hostel's own) ─────────

const NAVY = '#1a3a5c';
const NAVY2 = '#0f2540';
const LGRAY = '#f8fafc';
const DGRAY = '#1e293b';
const MGRAY = '#64748b';
const SGRAY = '#94a3b8';
const BORDER = '#e2e8f0';
const GREEN = '#16a34a';
const AMBER = '#d97706';
const RED = '#dc2626';
const WHITE = '#ffffff';
const GOLD = '#f59e0b';
const DEFAULT_ACCENT = '#2563eb';

/** A `#rrggbb` accent, or the brand default when unset or malformed. */
function safeAccent(value: string | null | undefined): string {
  return value && /^#[0-9a-fA-F]{6}$/.test(value) ? value : DEFAULT_ACCENT;
}

// ── Builder ────────────────────────────────────────────────────────────────

/**
 * Builds the PDF for one invoice.
 *
 * Scoped by `userId` when given: a student may only ever fetch their own,
 * and that check belongs here rather than in the route so no future caller
 * can skip it.
 */
export async function buildInvoicePdf(
  invoiceId: string,
  opts: { userId?: string } = {},
): Promise<{ buffer: Buffer; filename: string }> {
  const invoice = await db.invoice.findFirst({
    where: { id: invoiceId },
    include: {
      // Reversed payments count for nothing and are not printed.
      payments: { where: { status: 'CLEARED' }, orderBy: { paidAt: 'asc' } },
      // Billing-rule lines. Older invoices have none and print as one row.
      lines: { orderBy: { createdAt: 'asc' } },
      student: {
        include: {
          virtualAccount: { select: { accountNumber: true, ifsc: true, upiId: true, status: true } },
          user: { select: { name: true, email: true, phone: true } },
          bed: { select: { label: true, room: { select: { number: true, floor: true } } } },
          property: { select: { name: true, address: true, city: true, state: true } },
        },
      },
    },
  });
  if (!invoice) throw new NotFoundError('Invoice not found');

  if (opts.userId && invoice.student?.userId !== opts.userId) {
    // Not a 403: saying "exists but is not yours" would confirm another
    // student's invoice id.
    throw new NotFoundError('Invoice not found');
  }

  const settings = await db.tenantSettings.findFirst({
    select: {
      billingFirmName: true,
      billingGstin: true,
      billingAddress: true,
      billingPhone: true,
      billingEmail: true,
      billingLogoUrl: true,
      billingAccentColor: true,
    },
  });
  const logo = settings?.billingLogoUrl ? await getTenantFileBytes(getTenantIdOrThrow(), settings.billingLogoUrl) : null;

  // A dormitory's invoice speaks its language (27 Oct 2026): a customer, bed
  // and stay charges — no rent, mess or hostel — with their phone and address.
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: getTenantIdOrThrow() }, select: { kind: true } });
  const dorm = tenant?.kind === TenantKind.DORMITORY;
  const student = invoice.student;
  const property = student?.property ?? null;
  const homeAddress = student ? [student.address, student.city, student.state, student.postalCode].map((v) => v?.trim()).filter(Boolean).join(', ') : '';
  const paid = invoice.payments.reduce((n, p) => n + p.amount, 0);
  const balance = Math.max(0, invoice.amount - paid);
  const settled = balance <= 0;
  const partly = !settled && paid > 0;
  const latest = invoice.payments[invoice.payments.length - 1] ?? null;
  const accent = safeAccent(settings?.billingAccentColor);
  const firm = settings?.billingFirmName?.trim() || property?.name || 'HostelCare';
  const firmAddress =
    settings?.billingAddress?.trim() ||
    [property?.address, property?.city, property?.state].filter(Boolean).join(', ') ||
    '';
  const contactLine = [settings?.billingPhone && `Tel: ${settings.billingPhone}`, settings?.billingEmail]
    .filter(Boolean)
    .join('   |   ');
  const gstin = settings?.billingGstin?.trim() || '';
  const roomLine = student?.bed
    ? `Room ${student.bed.room.number}, Bed ${student.bed.label}${student.bed.room.floor != null ? ` (Floor ${student.bed.room.floor})` : ''}`
    : '-';
  const number = invoiceNumber(invoice.id, invoice.periodMonth);

  const doc = new PDFDocument({ size: 'A4', margin: 0, compress: true, info: { Title: `${firm} ${number}`, Author: firm } });
  const chunks: Buffer[] = [];
  doc.on('data', (c: Buffer) => chunks.push(c));
  const done = new Promise<Buffer>((resolve, reject) => {
    doc.on('end', () => resolve(Buffer.concat(chunks)));
    doc.on('error', reject);
  });

  const PW = doc.page.width;
  const PH = doc.page.height;
  const M = 44;
  const CW = PW - M * 2;

  // ── Header band ────────────────────────────────────────────────────────
  const LOGO = 54;
  const textLeft = logo ? M + LOGO + 12 : M;
  const textW = CW * 0.6 - (logo ? LOGO + 12 : 0);
  doc.font('Helvetica').fontSize(8.5);
  const addrH = firmAddress ? doc.heightOfString(firmAddress, { width: textW }) : 0;
  const HDR_H = Math.max(125, 47 + addrH + (firmAddress ? 3 : 0) + (contactLine ? 13 : 0) + (gstin ? 13 : 0) + 12);

  doc.rect(0, 0, PW, HDR_H).fill(NAVY);
  doc.save().fillColor(accent).fillOpacity(0.35).moveTo(PW, 0).lineTo(PW - 140, 0).lineTo(PW, Math.min(140, HDR_H - 4)).closePath().fill().restore();
  doc.fillOpacity(1);
  doc.rect(0, HDR_H - 4, PW, 4).fill(GOLD);

  if (logo) {
    try {
      doc.save();
      doc.roundedRect(M, 18, LOGO, LOGO, 6).fill(WHITE);
      doc.image(logo, M + 3, 21, { fit: [LOGO - 6, LOGO - 6], align: 'center', valign: 'center' });
      doc.restore();
    } catch {
      /* not a PNG/JPEG pdfkit can read — header carries the name alone */
    }
  }

  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(20).text(firm, textLeft, 20, { width: textW, lineBreak: false, ellipsis: true });
  let hy = 47;
  doc.font('Helvetica').fontSize(8.5).fillColor(SGRAY);
  if (firmAddress) {
    doc.text(firmAddress, textLeft, hy, { width: textW });
    hy += addrH + 3;
  }
  if (contactLine) {
    doc.text(contactLine, textLeft, hy, { width: textW });
    hy += 13;
  }
  if (gstin) {
    doc.font('Helvetica-Bold').fillColor('#93c5fd').text(`GSTIN: ${gstin}`, textLeft, hy, { width: textW });
  }

  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(17).text(settled ? 'RECEIPT' : 'INVOICE', M, 18, { width: CW, align: 'right' });
  doc.fillColor(SGRAY).font('Helvetica').fontSize(8.5);
  doc.text(`Invoice No:  ${number}`, M, 47, { width: CW, align: 'right' });
  doc.text(`Issued:  ${dayLabel(invoice.createdAt)}`, M, 61, { width: CW, align: 'right' });
  doc.text(`Due:  ${dayLabel(invoice.dueDate)}`, M, 75, { width: CW, align: 'right' });

  // ── Bill to | Payment details ──────────────────────────────────────────
  let y = HDR_H + 22;
  const COL2 = M + CW * 0.55;
  const billW = CW * 0.5;
  const LBL = 62;

  doc.fillColor(NAVY).font('Helvetica-Bold').fontSize(7.5).text('BILL TO', M, y);
  doc.text('PAYMENT DETAILS', COL2, y);
  y += 11;

  const studentName = student?.user.name ?? '-';
  const nameH = doc.font('Helvetica-Bold').fontSize(12.5).heightOfString(studentName, { width: billW });
  doc.fillColor(DGRAY).text(studentName, M, y, { width: billW });

  let ly = y + nameH + 7;
  const email = isPlaceholderEmail(student?.user.email) ? null : student?.user.email;
  const billRows: [string, string | null | undefined][] = dorm
    ? [
        ['Customer ID', student ? `CUS-${student.id.slice(0, 6).toUpperCase()}` : null],
        ['Phone', student?.user.phone],
        ['Address', homeAddress || null],
        ['Room', student?.bed ? roomLine : null],
        ['Email', email],
      ]
    : [
        ['Student ID', student ? `STU-${student.id.slice(0, 6).toUpperCase()}` : null],
        ['Room', roomLine],
        ['Property', property?.name],
        ['Phone', student?.user.phone],
        ['Email', email],
      ];
  doc.font('Helvetica').fontSize(9).fillColor(MGRAY);
  for (const [label, value] of billRows) {
    if (!value) continue;
    const h = Math.max(13, doc.heightOfString(value, { width: billW - LBL - 8 }));
    doc.fillColor(MGRAY).text(`${label}`, M, ly, { width: LBL });
    doc.fillColor(DGRAY).text(value, M + LBL, ly, { width: billW - LBL - 8 });
    ly += h + 2;
  }

  const RLW = 92;
  const RVX = COL2 + RLW;
  const RVW = CW * 0.45 - RLW - 4;
  let ry = y + 2;
  const payRows: [string, string][] = [
    [dorm ? 'Period' : 'Fee period', feePeriod(invoice.periodMonth, invoice.cycleMonths)],
    ['Payment ID', latest ? paymentNumber(latest.id) : '-'],
    ['Transaction ref', latest?.reference?.trim() || '-'],
    ['Mode', methodLabel(latest?.method)],
    ['Paid on', dayLabel(latest?.paidAt)],
  ];
  for (const [label, value] of payRows) {
    doc.font('Helvetica').fontSize(9).fillColor(MGRAY).text(label, COL2, ry, { width: RLW });
    const h = doc.font('Helvetica-Bold').fontSize(9).heightOfString(value, { width: RVW });
    doc.fillColor(DGRAY).text(value, RVX, ry, { width: RVW });
    ry += Math.max(14, h + 2);
  }
  ry += 3;
  const chip = settled ? { text: 'PAID', fill: GREEN, w: 46 } : partly ? { text: 'PARTIALLY PAID', fill: AMBER, w: 96 } : { text: 'UNPAID', fill: RED, w: 58 };
  doc.roundedRect(COL2, ry, chip.w, 17, 3).fill(chip.fill);
  doc.font('Helvetica-Bold').fontSize(8.5).fillColor(WHITE).text(chip.text, COL2, ry + 4.5, { width: chip.w, align: 'center' });
  ry += 17;
  // Smart Collect: the student's own transfer details, so a parent paying
  // from net banking has them on the invoice itself.
  const va = student?.virtualAccount && student.virtualAccount.status === 'active' ? student.virtualAccount : null;
  if (va && !settled) {
    ry += 8;
    doc.font('Helvetica-Bold').fontSize(7.5).fillColor(NAVY).text(dorm ? 'PAY BY BANK TRANSFER (THIS CUSTOMER ONLY)' : 'PAY BY BANK TRANSFER (THIS STUDENT ONLY)', COL2, ry);
    ry += 11;
    const vaRows: [string, string][] = [['A/c number', va.accountNumber], ['IFSC', va.ifsc], ...(va.upiId ? ([['UPI ID', va.upiId]] as [string, string][]) : [])];
    for (const [label, value] of vaRows) {
      doc.font('Helvetica').fontSize(8.5).fillColor(MGRAY).text(label, COL2, ry, { width: RLW });
      doc.font('Helvetica-Bold').fontSize(8.5).fillColor(DGRAY).text(value, RVX, ry, { width: RVW });
      ry += 12;
    }
  }

  y = Math.max(ly, ry + 24) + 14;
  doc.moveTo(M, y).lineTo(PW - M, y).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 18;

  // ── Fee table ──────────────────────────────────────────────────────────
  const TH = 27;
  const TR = 36;
  const C0 = 30;
  const C3 = 120;
  const C2 = 150;
  const C1 = CW - C0 - C2 - C3;
  const colX = [C0, C0 + C1, C0 + C1 + C2];

  doc.rect(M, y, CW, TH).fill(NAVY);
  for (const cx of colX) doc.moveTo(M + cx, y).lineTo(M + cx, y + TH).strokeColor('#2e4e70').lineWidth(0.5).stroke();
  const hY = y + 9.5;
  doc.fillColor(WHITE).font('Helvetica-Bold').fontSize(8.5);
  doc.text('#', M, hY, { width: C0, align: 'center' });
  doc.text('DESCRIPTION', M + C0 + 8, hY, { width: C1 - 16 });
  doc.text(dorm ? 'PERIOD' : 'FEE PERIOD', M + C0 + C1 + 8, hY, { width: C2 - 16 });
  doc.text('AMOUNT', M + C0 + C1 + C2 + 4, hY, { width: C3 - 12, align: 'right' });
  y += TH;

  // The rows: one per billing-rule line when the invoice has them, otherwise
  // the single row every invoice printed before billing rules existed.
  const description = dorm
    ? invoice.type === InvoiceType.RENT
      ? 'Stay charges'
      : 'Charges'
    : invoice.type === InvoiceType.RENT
      ? 'Hostel rent'
      : invoice.type === InvoiceType.MESS
        ? 'Mess charges'
        : 'Other charges';
  const rentTitle = dorm ? 'Bed charges' : 'Hostel rent';
  const kindSub = (kind: string) => (dorm ? (DORM_LINE_KIND_SUB[kind] ?? '') : (LINE_KIND_SUB[kind] ?? ''));
  const cycleNote = invoice.cycleMonths > 1 ? ` · ${invoice.cycleMonths}-month cycle` : '';
  const defaultSub = invoice.type === InvoiceType.RENT ? `${student?.bed ? roomLine : periodLabel(invoice.periodMonth, invoice.cycleMonths)}${cycleNote}` : invoice.type === InvoiceType.MESS ? `Mess - ${monthLabel(invoice.periodMonth)}` : monthLabel(invoice.periodMonth);
  const coveredFrom = invoice.coveredFrom ?? null;
  const coveredTo = invoice.coveredTo ?? null;
  const fullPeriod = feePeriod(invoice.periodMonth, invoice.cycleMonths);
  const actualPeriod = coveredFrom || coveredTo ? `${dayLabel(coveredFrom ?? new Date(`${invoice.periodMonth}-01T00:00:00Z`))} - ${coveredTo ? dayLabel(coveredTo) : fullPeriod.split(' - ')[1]}` : fullPeriod;
  const rowsToPrint: { title: string; sub: string; period: string; amount: number }[] =
    invoice.lines.length > 0
      ? invoice.lines.map((l) => ({
          title: l.kind === 'RENT' ? rentTitle : l.label,
          sub: l.kind === 'RENT' ? [l.label.replace(/^Hostel rent( · )?/, '') || null, student?.bed ? roomLine : null].filter(Boolean).join(' · ') : kindSub(l.kind),
          period: l.kind === 'RENT' || l.kind === 'PRORATA_CREDIT' ? actualPeriod : l.kind === 'GST' || l.kind === 'CHARGE' ? fullPeriod : '-',
          amount: l.amount,
        }))
      : [{ title: description, sub: defaultSub, period: fullPeriod, amount: invoice.amount }];

  // pdfkit's built-in fonts have no ₹ (stay lines carry one), so print Rs.
  for (const row of rowsToPrint) {
    row.title = row.title.replace(/₹\s?/g, 'Rs. ');
    row.sub = row.sub.replace(/₹\s?/g, 'Rs. ');
  }
  let n = 0;
  for (const row of rowsToPrint) {
    n++;
    doc.rect(M, y, CW, TR).fill(n % 2 ? LGRAY : WHITE);
    for (const cx of colX) doc.moveTo(M + cx, y).lineTo(M + cx, y + TR).strokeColor(BORDER).lineWidth(0.5).stroke();
    const dY = y + 7;
    const hasSub = row.sub.trim().length > 0;
    doc.fillColor(DGRAY).font('Helvetica').fontSize(9).text(String(n), M, dY + 5, { width: C0, align: 'center' });
    doc.font('Helvetica-Bold').fontSize(9.5).text(row.title, M + C0 + 8, hasSub ? dY : dY + 5, { width: C1 - 16, lineBreak: false, ellipsis: true });
    if (hasSub) doc.font('Helvetica').fontSize(8).fillColor(MGRAY).text(row.sub, M + C0 + 8, dY + 13, { width: C1 - 16, lineBreak: false, ellipsis: true });
    doc.font('Helvetica').fontSize(8.5).fillColor(DGRAY).text(row.period, M + C0 + C1 + 8, dY + 5, { width: C2 - 16 });
    doc.font('Helvetica-Bold').fontSize(9.5).fillColor(row.amount < 0 ? GREEN : DGRAY).text(row.amount < 0 ? `- ${money(-row.amount)}` : money(row.amount), M + C0 + C1 + C2 + 4, dY + 5, { width: C3 - 12, align: 'right' });
    y += TR;
  }
  doc.rect(M, y - TH - TR * rowsToPrint.length, CW, TH + TR * rowsToPrint.length).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 18;

  // ── Summary + total ────────────────────────────────────────────────────
  const SW = 240;
  const SX = PW - M - SW;
  const SLW = 130;
  const taxAmount = invoice.taxAmount ?? 0;
  // Prices that include GST print the basic amount and the GST inside the
  // total to the paisa: Rs. 423.73 + GST @ 18% Rs. 76.27 = Rs. 500.00.
  const taxRows: [string, string][] =
    invoice.taxInclusive && invoice.taxPaise != null
      ? [
          ['Basic amount', money((invoice.amount * 100 - invoice.taxPaise) / 100)],
          [`GST @ ${invoice.taxRate ?? 0}%`, money(invoice.taxPaise / 100)],
        ]
      : taxAmount > 0
        ? [
            ['Taxable amount', money(invoice.amount - taxAmount)],
            [invoice.taxRate ? `GST @ ${invoice.taxRate}%` : 'GST included', money(taxAmount)],
          ]
        : [];
  const rows: [string, string, string?][] = [
    ...taxRows,
    ['Invoice amount', money(invoice.amount)],
    ['Amount paid', paid > 0 ? `- ${money(paid)}` : money(0)],
  ];
  for (const [label, value] of rows) {
    doc.font('Helvetica').fontSize(9).fillColor(MGRAY).text(label, SX, y, { width: SLW });
    doc.fillColor(DGRAY).text(value, SX + SLW, y, { width: SW - SLW, align: 'right' });
    y += 15;
  }
  doc.moveTo(SX, y + 2).lineTo(SX + SW, y + 2).strokeColor(BORDER).lineWidth(0.75).stroke();
  y += 10;
  doc.rect(SX, y, SW, 32).fill(NAVY2);
  doc.font('Helvetica-Bold').fontSize(9.5).fillColor(WHITE).text(settled ? 'TOTAL PAID' : 'BALANCE DUE', SX + 10, y + 11, { width: SLW });
  doc.font('Helvetica-Bold').fontSize(13).fillColor(GOLD).text(money(settled ? invoice.amount : balance), SX + 10, y + 9, { width: SW - 20, align: 'right' });
  y += 44;

  // ── Payments received ──────────────────────────────────────────────────
  const TERMS_H = 50;
  const FOOT_H = 78;
  const TERMS_Y = PH - FOOT_H - TERMS_H - 8;

  if (invoice.payments.length > 0) {
    doc.fillColor(NAVY).font('Helvetica-Bold').fontSize(7.5).text('PAYMENTS RECEIVED', M, y);
    y += 12;
    const P = [90, 110, 70, CW - 90 - 110 - 70 - 100, 100]; // date, id, mode, ref, amount
    const PX: number[] = [];
    let cursor = M;
    for (const w of P) {
      PX.push(cursor);
      cursor += w;
    }
    const PRH = 20;
    const header = ['DATE', 'PAYMENT ID', 'MODE', 'TRANSACTION REF', 'AMOUNT'];
    doc.rect(M, y, CW, PRH).fill('#eef2f7');
    doc.font('Helvetica-Bold').fontSize(7.5).fillColor(NAVY);
    header.forEach((h, i) => doc.text(h, PX[i] + 6, y + 6.5, { width: P[i] - 12, align: i === 4 ? 'right' : 'left' }));
    y += PRH;
    for (const p of invoice.payments) {
      if (y + PRH > TERMS_Y - 6) {
        doc.addPage({ size: 'A4', margin: 0 });
        y = M;
      }
      const cells = [dayLabel(p.paidAt), paymentNumber(p.id), methodLabel(p.method), p.reference?.trim() || '-', money(p.amount)];
      doc.font('Helvetica').fontSize(8.5).fillColor(DGRAY);
      cells.forEach((c, i) =>
        doc.text(c, PX[i] + 6, y + 6, { width: P[i] - 12, align: i === 4 ? 'right' : 'left', lineBreak: false, ellipsis: true }),
      );
      doc.moveTo(M, y + PRH).lineTo(PW - M, y + PRH).strokeColor(BORDER).lineWidth(0.5).stroke();
      y += PRH;
    }
    y += 10;
  }

  if (!settled) {
    doc.font('Helvetica').fontSize(8.5).fillColor(MGRAY).text(
      invoice.dueDate
        ? `Please pay ${money(balance)} by ${dayLabel(invoice.dueDate)} and quote ${number} as the reference.`
        : `Please pay ${money(balance)} and quote ${number} as the reference.`,
      M,
      y,
      { width: CW },
    );
    y += 18;
  }

  // ── Terms + footer (always at the foot of the last page) ───────────────
  if (y > TERMS_Y - 6) doc.addPage({ size: 'A4', margin: 0 });
  doc.rect(M, TERMS_Y, CW, TERMS_H).fill(LGRAY);
  doc.rect(M, TERMS_Y, CW, TERMS_H).strokeColor(BORDER).lineWidth(0.5).stroke();
  doc.rect(M, TERMS_Y, 3, TERMS_H).fill(NAVY);
  doc.font('Helvetica-Bold').fontSize(7.5).fillColor(NAVY).text('Terms & Conditions', M + 12, TERMS_Y + 8);
  doc.font('Helvetica').fontSize(7.5).fillColor(MGRAY).text(
    (dorm
      ? '1. Charges are payable by the due date shown.\n' +
        '2. Quote the invoice number or payment ID for any query about this document.\n' +
        '3. Any discrepancy must be reported to the front desk within 7 days of issue.'
      : '1. Fees are payable by the due date shown; late payment may attract charges as per hostel policy.\n' +
        '2. Quote the invoice number or payment ID for any query about this document.\n' +
        '3. Any discrepancy must be reported to the hostel office within 7 days of issue.'),
    M + 12,
    TERMS_Y + 20,
    { width: CW - 20 },
  );

  const FY = PH - FOOT_H;
  doc.rect(0, FY, PW, FOOT_H).fill(LGRAY);
  doc.rect(0, FY, PW, 3).fill(GOLD);
  doc.fillColor(NAVY).font('Helvetica-Bold').fontSize(10.5).text(`Thank you for staying with ${firm}!`, M, FY + 14, { width: CW, align: 'center' });
  doc.fillColor(MGRAY).font('Helvetica').fontSize(8).text(
    'This is a computer-generated document and is valid without a physical signature.',
    M,
    FY + 30,
    { width: CW, align: 'center' },
  );
  const footContact = [settings?.billingPhone, settings?.billingEmail].filter(Boolean).join('   |   ');
  if (footContact) doc.fillColor(MGRAY).fontSize(7.5).text(footContact, M, FY + 44, { width: CW, align: 'center' });
  doc.fillColor(SGRAY).fontSize(7).text(
    [firm, gstin && `GSTIN: ${gstin}`, `Generated on ${dayLabel(new Date())}`].filter(Boolean).join('   |   '),
    M,
    FY + 58,
    { width: CW, align: 'center' },
  );

  doc.end();
  const buffer = await done;
  return { buffer, filename: `${number}.pdf` };
}
