

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

const generateInvoicePDF = async (invoice, items, company) => {
  const formatDate = (date) => {
    if (!date) return "-";
    return new Date(date).toLocaleDateString("en-GB"); // DD/MM/YYYY
  };

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

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

  try {
    const templatePath = path.join(
      __dirname,
      "../../templates/invoiceTemplate.html",
    );
    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}`;

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

    // =========================
    // 🔹 COMPANY DATA
    // =========================
    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 || "");

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

    // =========================
    // 🔹 CUSTOMER DATA
    // =========================
    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 || "");

    // =========================
    // 🔹 INVOICE DETAILS
    // =========================
    html = html.replace(/{{invoice_number}}/g, invoice.invoice_number || "");
    html = html.replace(/{{invoice_date}}/g, formatDate(invoice.invoice_date));
    html = html.replace(/{{order_no}}/g, invoice.order_no || "-");
    html = html.replace(/{{po_no}}/g, invoice.po_no || "-");
    html = html.replace(/{{po_date}}/g, formatDate(invoice.po_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(/{{freight}}/g, formatMoney(invoice.freight));
    html = html.replace(/{{cgst}}/g, formatMoney(invoice.cgst));
    html = html.replace(/{{sgst}}/g, formatMoney(invoice.sgst));
    html = html.replace(/{{round_off}}/g, formatMoney(invoice.round_off));
    html = html.replace(/{{total}}/g, formatMoney(invoice.total));
    html = html.replace(
  /{{advance_adjusted_amount}}/g,
  formatMoney(invoice.advance_adjusted_amount || 0)
);

html = html.replace(
  /{{balance_payable_amount}}/g,
  formatMoney(invoice.balance_payable_amount || 0)
);

let advanceSummaryRows = "";

if (
  Number(invoice.advance_adjusted_amount || 0) > 0
) {

  advanceSummaryRows = `
  
    <tr>
      <td>
        Advance Adjusted
      </td>

      <td class="text-right">
        INR ${formatMoney(
          invoice.advance_adjusted_amount
        )}
      </td>
    </tr>

    <tr>
      <td>
        Balance Payable
      </td>

      <td class="text-right">
        INR ${formatMoney(
          invoice.balance_payable_amount
        )}
      </td>
    </tr>

  `;
}


html = html.replace(
  "{{advance_summary_rows}}",
  advanceSummaryRows
);


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

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

    // =========================
    // 🔹 ITEMS LOOP
    // =========================
    let itemsRows = "";

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

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

    // =========================
    // 🔹 GENERATE PDF
    // =========================
    // const browser = await puppeteer.launch({
    //   headless: "new",
    //   args: ["--no-sandbox"],
    // });
    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: "load" });

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

    await browser.close();

    return pdf;
  } catch (err) {
    console.error("PDF SERVICE ERROR:", err);
    throw err;
  }
};
module.exports = generateInvoicePDF;
