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


// module.exports = (quotation, items, company) => {
//   return new Promise((resolve, reject) => {
//     const doc = new PDFDocument({ size: "A4", margin: 40 });
//     const buffers = [];

//     doc.on("data", buffers.push.bind(buffers));
//     doc.on("end", () => resolve(Buffer.concat(buffers)));
//     doc.on("error", reject);

//     const left = 40;
//     const right = 555;
//     const width = right - left;

//     let y = 40;

//     /* ================= HEADER ================= */

//     doc
//       .font("Helvetica-Bold")
//       .fontSize(16)
//       .text("QUOTATION", left, y, { width, align: "center" });

//     y += 20;

//     doc
//       .font("Helvetica")
//       .fontSize(8)
//       .text(
//         "Please Provide Your Quotation For The Below Mentioned Items.",
//         left,
//         y,
//         { width, align: "center" },
//       );

//     y += 14;

//     doc.text(
//       "Ensure Pricing, Taxes, And Delivery Details Are Clearly Specified.",
//       left,
//       y,
//       { width, align: "center" },
//     );

//     y += 25;

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

//     doc.text(`QTN ID : ${quotation.quotation_number}`, left, y);

//     doc.text(`Date : ${new Date().toLocaleDateString()}`, left, y, {
//       width,
//       align: "right",
//     });

//     y += 25;

//     /* ================= LOGO ================= */

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

//     const boxH = 110;
//     const gap = 15;
//     const boxW = (width - gap) / 2;

//     /* ================= FROM ================= */
//     doc.strokeColor("#e5e7eb");
//     doc.roundedRect(left, y, boxW, boxH, 8).stroke();

//     if (fs.existsSync(logoPath)) {
//       doc.image(logoPath, left + 10, y + 10, { width: 60 });
//     }

//     doc
//       .font("Helvetica-Bold")
//       .fontSize(10)
//       .text("From:", left + 10, y + 40);

//     doc
//       .font("Helvetica")
//       .font("Helvetica-Bold")
//       .fontSize(10)
//       .text(company.name || "ERP Enterprise", left + 10, y + 55);
      
//     //   .text(company.address || "", left + 10, y + 80);
//     doc
//      .font("Helvetica")
//      .fontSize(8)
//      .text(company.address || "", left + 10, y + 70, {
//       width: boxW - 20,
//       lineBreak: true,
//     });

//     /* ================= TO ================= */

//     const toX = left + boxW + gap;

//     doc.roundedRect(toX, y, boxW, boxH, 8).stroke();

//     doc.font("Helvetica-Bold").text("To:", toX + 10, y + 10);

//     doc
//       .fontSize(10)
//       .font("Helvetica")
//       .font("Helvetica-Bold")
//       .text(quotation.customer_name || "Customer", toX + 10, y + 25)
//     doc.font("Helvetica")  
//     .fontSize(8)
//       .text(quotation.customer_address || "Hyderabad", toX + 10, y + 40)
//     doc.font("Helvetica")  
//       .text(`GSTIN: ${quotation.gstin || "-"}`, toX + 10, y + 55);

//     y += boxH + 25;

  
//     const col = {
//   sno: left,
//   product: left + 40,   // +10
//   desc: left + 150,     // +20
//   qty: left + 290,      // +20
//   uom: left + 340,      // +20
//   rate: left + 400,     // +20
//   amount: left + 460,   // +20
// };

//     doc
//       .moveTo(left, y - 5)
//       .lineTo(right, y - 5)
//       .stroke();

//     doc.font("Helvetica-Bold").fontSize(10);

//     doc.text("S.NO", col.sno, y);
//     doc.text("PRODUCT", col.product, y);
//     doc.text("DESCRIPTION", col.desc, y);
//     doc.text("QTY", col.qty, y);
//     doc.text("UOM", col.uom, y);
//     doc.text("RATE", col.rate, y);
//     //  doc.text("AMOUNT", col.amount, y);
//     doc.text("AMOUNT", col.amount - 30, y, {
//       width: 80,
//       align: "right",
//     });

//     doc
//       .moveTo(left, y + 15)
//       .lineTo(right, y + 15)
//       .stroke();

//     y += 25;

//     /* ================= ROWS ================= */

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

//     let subtotal = 0;

//     items.forEach((item, i) => {
//       const qty = Number(item.qty) || 0;
//       const rate = Number(item.rate) || 0;
//       const amount = qty * rate;

//       subtotal += amount;

//       doc.text(i + 1, col.sno, y);
//       doc.text(item.product_name || "-", col.product, y);
//       doc.text(item.description || "-", col.desc, y);

//       doc.text(qty.toFixed(2), col.qty, y);
//       doc.text(item.uom_symbol || "", col.uom, y);

//       doc.text(`₹ ${rate.toFixed(2)}`, col.rate, y);
//       //   doc.text(`₹ ${amount.toFixed(2)}`, col.amount, y);
//       doc.text(`₹ ${amount.toFixed(2)}`, col.amount - 30, y, {
//         width: 80,
//         align: "right",
//       });

//       y += 18;
//     });

//     /* ================= TOTAL BOX ================= */

//     const gst = subtotal * 0.18;
//     const total = subtotal + gst;

//     const boxX = right - 220;
//     const boxY = y + 10;

//     doc.roundedRect(boxX, boxY, 220, 100, 8).stroke();

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

//     doc.text("Subtotal", boxX + 15, boxY + 15);
//     doc.text(`₹ ${subtotal.toFixed(2)}`, boxX + 120, boxY + 15);

//     doc.text("GST (18%)", boxX + 15, boxY + 40);
//     doc.text(`₹ ${gst.toFixed(2)}`, boxX + 120, boxY + 40);

//     doc
//       .moveTo(boxX + 10, boxY + 65)
//       .lineTo(boxX + 210, boxY + 65)
//       .stroke();

//     doc.font("Helvetica-Bold");

//     doc.text("Total Amount", boxX + 15, boxY + 75);
//     doc.text(`₹ ${total.toFixed(2)}`, boxX + 120, boxY + 75);

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


const generateSalesOrderPDF = async (data, items, company) => {

      // 🔹 helper function
    const amountInWords = (num) => {
      try {
        return (
          "Rupees " +
          toWords.toWords(Math.round(num || 0)).replace(/-/g, " ") +
          " Only"
        );
      } catch {
        return "Rupees Zero Only";
      }
    };
    
    const formatDate = (date) => {
  if (!date) return "-";
  return new Date(date).toLocaleDateString("en-GB");
};

  let html = fs.readFileSync(
    path.join(__dirname, "../../templates/salesQuotation.html"),
    "utf8"
  );

    const logoPath = path.join(
    __dirname,
    "../../uploads/images/logo.png"
  );
  
  // convert to file:// format
  // const logoUrl = `file://${logoPath}`;
  // const logoUrl = `file:///${logoPath.replace(/\\/g, "/")}`;
  const logoBase64 = fs.readFileSync(logoPath, "base64");
  const logoUrl = `data:image/png;base64,${logoBase64}`;

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

  // 🔹 COMPANY
//   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(/{{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(/{{company_cin}}/g, company.cin || "");
    html = html.replace(/{{company_phone}}/g, company.phone || "");
    html = html.replace(/{{company_email}}/g, company.email || "");
  // 🔹 CUSTOMER
  html = html.replace(/{{customer_name}}/g, data.customer_name);
  html = html.replace(/{{customer_address}}/g, data.customer_address);
  html = html.replace(/{{customer_gst}}/g, data.customer_gst);

  // 🔹 ORDER DETAILS
  html = html.replace(/{{order_number}}/g, data.order_number);
//   html = html.replace(/{{order_date}}/g, data.order_date);
//   html = html.replace(/{{order_date}}/g, data.order_date || "-");
html = html.replace(/{{order_date}}/g, formatDate(data.order_date));
html = html.replace(/{{ref_date}}/g, formatDate(data.ref_date));
html = html.replace(/{{ref_no}}/g, data.ref_no || "-");
// html = html.replace(/{{ref_date}}/g, data.ref_date || "-");

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


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


//   audit
  html = html.replace(/{{prepared_by}}/g, data.prepared_by || "-");
html = html.replace(/{{verified_by}}/g, data.verified_by || "-");
html = html.replace(/{{approved_by}}/g, data.approved_by || "-");

  // 🔹 ITEMS
  let rows = "";
  items.forEach((item, i) => {
    rows += `
      <tr>
        <td>${i + 1}</td>
        <td>${item.product_name}</td>
        <td>${item.uom_symbol}</td>
        <td>${item.qty}</td>
        <td>${item.rate}</td>
        <td>${item.discount || 0}</td>
        <td>${item.gst || 0}</td>
        <td>${item.amount}</td>
      </tr>
    `;
  });

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

  // 🔹 PDF
//   const browser = await puppeteer.launch({ headless: "new" });
const browser = await puppeteer.launch({
  headless: true,

  executablePath:
    "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",

  args: [
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--disable-dev-shm-usage",
    "--disable-gpu",
  ],
});
  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;
};

module.exports  = generateSalesOrderPDF;