

// const PDFDocument = require("pdfkit");
// const path = require("path");

// const ROW_HEIGHT = 22;
// const BOTTOM_MARGIN = 40;
// const cellPaddingY = 15; //  vertical centering


// /**
//  * Industry-grade Invoice / Customer Statement PDF
//  */
// const generateStatementPdf = (res, { invoice, rows, closingBalance }) => {
//     const doc = new PDFDocument({ size: "A4", margin: 40 });

//     /* ================= RESPONSE HEADERS ================= */
//     res.setHeader("Content-Type", "application/pdf");
//     res.setHeader(
//         "Content-Disposition",
//         `attachment; filename=STATEMENT-${invoice.invoiceNumber}.pdf`
//     );
//     res.setHeader("Cache-Control", "no-store");

//     doc.pipe(res);

//     const pageLeft = 40;
//     const pageRight = 555;
//     let y = 40;

//     /* ================= LOGO ================= */
//     const logoPath = path.resolve(
//         process.cwd(),
//         "uploads/images/company-logo.png"
//     );

//     try {
//         doc.image(logoPath, pageLeft, y, { width: 90 });
//         y += 30;
//     } catch {
//         y += 20;
//     }

//     /* ================= COMPANY INFO ================= */
//     doc.font("Helvetica-Bold").fontSize(14).text(invoice.company.name, pageLeft, y);
//     y += 18;

//     doc.font("Helvetica").fontSize(9).text(invoice.company.address, pageLeft, y);
//     y += 14;

//     doc
//         .fontSize(9)
//         .text(`GSTIN: ${invoice.company.gstin || "--"}`, pageLeft, y);

//     y += 25;

//     /* ================= META (RIGHT) ================= */
//     doc
//         .font("Helvetica-Bold")
//         .fontSize(10)
//         .text("Date:", pageLeft, 70, {
//             width: pageRight - pageLeft,
//             align: "right",
//         })
//         .font("Helvetica")
//         .text(new Date().toLocaleDateString("en-IN"), pageLeft, 85, {
//             width: pageRight - pageLeft,
//             align: "right",
//         });

//     doc.moveTo(pageLeft, y).lineTo(pageRight, y).stroke();
//     y += 20;

//     /* ================= BILL TO ================= */
//     doc.font("Helvetica-Bold").fontSize(11).text("Bill To", pageLeft, y);
//     y += 14;

//     doc
//         .font("Helvetica")
//         .fontSize(10)
//         .text(invoice.customer.name, pageLeft, y)
//         .text(invoice.customer.phone || "", pageLeft, y + 12)
//         .text(invoice.customer.email || "", pageLeft, y + 24);

//     y += 50;

//     /* ================= TABLE CONFIG ================= */
//     const col = {
//         date: pageLeft,
//         type: pageLeft + 55,
//         ref: pageLeft + 115,
//         desc: pageLeft + 230,
//         amount: pageRight - 180,
//         balance: pageRight - 90,
//         end: pageRight,
//     };

//     /* ================= TABLE ================= */
//     let tableY = y;

//     drawTableHeader(doc, tableY, col);
//     tableY += ROW_HEIGHT;

//     rows.forEach((r) => {
//         if (tableY + ROW_HEIGHT > doc.page.height - BOTTOM_MARGIN) {
//             doc.addPage();
//             tableY = 50;

//             drawTableHeader(doc, tableY, col);
//             tableY += ROW_HEIGHT;
//         }

//         drawTableRow(doc, tableY, r, col);
//         tableY += ROW_HEIGHT;
//     });

//     /* ================= FOOTER ================= */
//     tableY += 10;
//     doc.moveTo(pageLeft, tableY).lineTo(pageRight, tableY).stroke();
//     tableY += 16;

//     doc
//         .font("Helvetica-Bold")
//         .fontSize(11)
//         .text(`Closing Balance: ₹${closingBalance}`, pageLeft, tableY, {
//             width: pageRight - pageLeft,
//             align: "right",
//         });

//     doc.end();
// };

// /* ================= TABLE HEADER ================= */
// function drawTableHeader(doc, y, col) {
//     doc.font("Helvetica-Bold").fontSize(9);

//     doc.text("DATE", col.date + 4, y + 6);
//     doc.text("TYPE", col.type + 4, y + 6);
//     doc.text("REFERENCE", col.ref + 4, y + 6);
//     doc.text("DESCRIPTION", col.desc + 4, y + 6);
//     //   doc.text("AMOUNT", col.amount, y + 6, { width: 60, align: "right" });
//     //   doc.text("BALANCE", col.balance - 60, y + 6, {
//     //     width: 60,
//     //     align: "right",
//     //   });
//     // doc.text("AMOUNT", col.amount, y, {
//     //     width: col.balance - col.amount,
//     //     align: "center",
//     // });

//     // doc.text("BALANCE", col.balance, y, {
//     //     width: col.end - col.balance,
//     //     align: "center",
//     // });
//     doc.text("AMOUNT", col.amount, y + 4, {
//         width: col.balance - col.amount,
//         align: "center",
//     });

//     doc.text("BALANCE", col.balance, y + 4, {
//         width: col.end - col.balance,
//         align: "center",
//     });


//     drawRowBorder(doc, y, ROW_HEIGHT, col);
// }

// /* ================= TABLE ROW ================= */
// function drawTableRow(doc, y, r, col) {
//     const amount = r.debit > 0 ? r.debit : r.credit;

//     doc.font("Helvetica").fontSize(9);

//     doc.text(
//         r.date ? new Date(r.date).toLocaleDateString("en-IN") : "-",
//         col.date + 4,
//         y + 6
//     );

//     doc.text(r.type || "-", col.type + 4, y + 6);
//     doc.text(r.reference || "-", col.ref + 4, y + 6);

//     doc.text(r.description || "-", col.desc + 4, y + 6, {
//         width: col.amount - col.desc - 10,
//     });

//     // if (amount) {
//     //     doc
//     //         .fillColor(r.debit > 0 ? "red" : "green")
//     //         .text(`₹${amount}`, col.amount, y + 6, {
//     //             width: 60,
//     //             align: "right",
//     //         });
//     // }

//     // doc
//     //     .fillColor("black")
//     //     .font("Helvetica-Bold")
//     //     .text(`₹${r.balance}`, col.balance - 60, y + 6, {
//     //         width: 60,
//     //         align: "right",
//     //     })
//     // .font("Helvetica");
//     doc.text(`₹${amount}`, col.amount, y, {
//         width: col.balance - col.amount,
//         align: "center",
//     });

//     doc.text(`₹${r.balance}`, col.balance, y, {
//         width: col.end - col.balance,
//         align: "center",
//     });

//     drawRowBorder(doc, y, ROW_HEIGHT, col,cellPaddingY);
// }

// /* ================= BORDERS ================= */
// function drawRowBorder(doc, y, height, col) {
//     doc.moveTo(col.date, y).lineTo(col.end, y).stroke();
//     doc.moveTo(col.date, y + height).lineTo(col.end, y + height).stroke();

//     [
//         col.date,
//         col.type,
//         col.ref,
//         col.desc,
//         col.amount,
//         col.balance,
//         col.end,
//     ].forEach((x) => {
//         doc.moveTo(x, y).lineTo(x, y + height).stroke();
//     });
// }

// module.exports = generateStatementPdf;


// const puppeteer = require("puppeteer");
const puppeteer = require("puppeteer-core");
const fs = require("fs");
const path = require("path");
const toWords = require("number-to-words");

const generateSalesQuotationPDF = async (invoice, items, company) => {

  const formatDate = (date) => {
    if (!date) return "-";
    return new Date(date).toLocaleDateString("en-GB");
  };

  const formatMoney = (val) => {
    return Number(val || 0).toLocaleString("en-IN", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });
  };

  const amountInWords = (num) => {
    try {
      return (
        "Rupees " +
        toWords.toWords(Math.round(num || 0)).replace(/-/g, " ") +
        " Only"
      );
    } catch {
      return "Rupees Zero Only";
    }
  };

  try {
    const templatePath = path.join(
      __dirname,
      "../../templates/salesQuotation.html"
    );

    const logoPath = path.join(
      __dirname,
      "../../uploads/images/logo.png"
    );

    const logoBase64 = fs.readFileSync(logoPath, "base64");
    const logoUrl = `data:image/png;base64,${logoBase64}`;

    let html = fs.readFileSync(templatePath, "utf8");
    const bank = company.bank_details || {};

    // 🔹 TITLE
    html = html.replace(/{{doc_title}}/g, "SALES QUOTATION");

    // 🔹 COMPANY
    html = html.replace(/{{logo_url}}/g, logoUrl);
    html = html.replace(/{{company_name}}/g, company.org_name || "");
    html = html.replace(/{{company_address}}/g, company.address || "");
    html = html.replace(/{{company_gstin}}/g, company.gstin || "");

    html = html.replace(/{{bank_name}}/g, bank.bank_name || "");
    html = html.replace(/{{account_no}}/g, bank.account_no || "");
    html = html.replace(/{{ifsc}}/g, bank.ifsc || "");

    // 🔹 CUSTOMER
    html = html.replace(/{{customer_name}}/g, invoice.customer_name || "");
    html = html.replace(/{{customer_address}}/g, invoice.customer_address || "");
    html = html.replace(/{{customer_gst}}/g, invoice.customer_gst || "");

    // 🔹 DETAILS
    html = html.replace(/{{invoice_number}}/g, invoice.invoice_number || "");
    html = html.replace(/{{invoice_date}}/g, formatDate(invoice.invoice_date));

    // 🔹 SUMMARY
    html = html.replace(/{{gross}}/g, formatMoney(invoice.gross));
    html = html.replace(/{{discount}}/g, formatMoney(invoice.discount));
    html = html.replace(/{{net_value}}/g, formatMoney(invoice.net_value));
    html = html.replace(/{{cgst}}/g, formatMoney(invoice.cgst));
    html = html.replace(/{{sgst}}/g, formatMoney(invoice.sgst));
    html = html.replace(/{{total}}/g, formatMoney(invoice.total));

    html = html.replace(/{{amount_words}}/g, amountInWords(invoice.total));

    // 🔹 SIGNATURE
    html = html.replace(/{{prepared_by}}/g, invoice.prepared_by || "-");
    html = html.replace(/{{approved_by}}/g, invoice.approved_by || "-");

    // 🔹 ITEMS
    let rows = "";
    items.forEach((item) => {
      rows += `
        <tr>
          <td>${item.product_name}</td>
          <td>${item.uom_symbol || "-"}</td>
          <td>${item.qty}</td>
          <td>${formatMoney(item.rate)}</td>
          <td>${formatMoney(item.amount)}</td>
        </tr>
      `;
    });

    html = html.replace(/{{items_rows}}/g, rows);

    // 🔹 PDF
    const browser = await puppeteer.launch({
      headless: "new",
      args: ["--no-sandbox"],
    });

    const page = await browser.newPage();
    await page.setContent(html, { waitUntil: "networkidle0" });

    const pdf = await page.pdf({
      format: "A4",
      printBackground: true,
    });

    await browser.close();

    return pdf;

  } catch (err) {
    console.error("QUOTATION PDF ERROR:", err);
    throw err;
  }
};

module.exports = generateSalesQuotationPDF;
