// generateSalesOrderPDF.js
// Mirrors generateInvoicePDF.js — generates a PDF for a Sales Order

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

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

  // ── Helpers ────────────────────────────────────────────────────────────────
  const formatDate = (date) => {
    if (!date) return "-";
    return new Date(date).toLocaleDateString("en-GB"); // DD/MM/YYYY
  };

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

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

  try {
    // ── Load template & logo ─────────────────────────────────────────────────
    const templatePath = path.join(
      __dirname,
      "../../templates/salesOrderTemplate.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");

    // ── Calculations ─────────────────────────────────────────────────────────
    const totalAmount = Number(order.total_amount || 0);

    const totalGstAmount = items.reduce(
      (sum, item) => sum + Number(item.gst_amount || 0),
      0
    );

    const subtotal  = totalAmount - totalGstAmount;
    const roundOff  = 0; // adjust if needed
    const bank      = company.bank_details || {};

    // ── Company placeholders ─────────────────────────────────────────────────
    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(/{{company_cin}}/g,    company.cin         || "");
    html = html.replace(/{{company_phone}}/g,  company.phone       || "");
    html = html.replace(/{{company_email}}/g,  company.email       || "");

    // ── Customer / Order placeholders ────────────────────────────────────────
    html = html.replace(/{{customer_name}}/g,    order.customer_name    || "");
    html = html.replace(/{{customer_address}}/g, order.customer_address || "");
    html = html.replace(/{{customer_gst}}/g,     order.customer_gst     || "");

    html = html.replace(/{{so_number}}/g,       order.so_number         || "-");
    html = html.replace(/{{po_reference}}/g,    order.po_reference      || "-");
    html = html.replace(/{{order_date}}/g,      formatDate(order.created_at));
    html = html.replace(/{{delivery_date}}/g,   formatDate(order.delivery_date));

    // ── Payment placeholders ─────────────────────────────────────────────────
    html = html.replace(
      /{{advance_payment}}/g,
      order.with_advance_payment ? "Yes" : "No"
    );
    html = html.replace(
      /{{advance_percent}}/g,
      Number(order.advance_payment_percent || 0).toFixed(2)
    );
    html = html.replace(
      /{{advance_amount}}/g,
      formatMoney(order.advance_payment_amount || 0)
    );
    html = html.replace(
      /{{advance_payment_status}}/g,
      order.advance_payment_status || "-"
    );

    // ── Summary placeholders ─────────────────────────────────────────────────
    html = html.replace(/{{subtotal}}/g,    formatMoney(subtotal));
    html = html.replace(/{{gst_amount}}/g,  formatMoney(totalGstAmount));
    html = html.replace(/{{round_off}}/g,   formatMoney(roundOff));
    html = html.replace(/{{total}}/g,       formatMoney(totalAmount));
    html = html.replace(/{{amount_words}}/g,amountInWords(totalAmount));

    // ── Signatories ──────────────────────────────────────────────────────────
    html = html.replace(/{{prepared_by}}/g, order.prepared_by_name  || "-");
    html = html.replace(/{{approved_by}}/g, order.approved_by_name  || "-");

    // ── Items rows ───────────────────────────────────────────────────────────
    let itemsRows = "";

    items.forEach((item) => {
      itemsRows += `
        <tr>
          <td class="product-name">${item.product_name || "-"}</td>
          <td class="text-center">${Number(item.qty).toFixed(2)}</td>
          <td class="text-center">${item.uom_symbol || "-"}</td>
          <td class="text-right">${Number(item.rate).toFixed(2)}</td>
          <td class="text-center">${Number(item.tax_percent || 0).toFixed(0)}%</td>
          <td class="text-right">${Number(item.amount).toFixed(2)}</td>
        </tr>
      `;
    });

    html = html.replace("{{items_rows}}", itemsRows);

    // ── Generate PDF ─────────────────────────────────────────────────────────
    // ✅ Fix — auto-detect based on OS
const browser = await puppeteer.launch({
  executablePath: process.platform === 'win32'
    ? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
    : '/usr/bin/chromium-browser',  // Linux path
  args: [
    '--no-sandbox',
    '--disable-setuid-sandbox',
    '--disable-dev-shm-usage',  // Important for VPS/low memory
  ],
  headless: true,
});

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

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

    await browser.close();

    return pdf;

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

module.exports = generateSalesOrderPDF;
