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
};

const formatWeightTon = (val) => {
  return `${(Number(val || 0) / 1000).toLocaleString("en-IN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })} `;
};
// 🔹 helper function
const amountInWords = (num) => {
  try {
    return (
      "" +
      toWords.toWords(Math.round(num || 0)).replace(/-/g, " ") +
      " Rupees Only"
    );
  } catch {
    return "Zero Rupees Only";
  }
};

const generateDispatchInvoicePDF = async (dispatch, 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,
    });
  };

  try {
    // =====================================
    // TEMPLATE PATH
    // =====================================

    const templatePath = path.join(
      __dirname,
      "../../templates/dispatchInvoiceTemplate.html",
    );

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

// const logoBase64 = fs.readFileSync(logoPath, "base64");

// const logoUrl = `data:image/png;base64,${logoBase64}`;

    // =====================================
    // LOGO
    // =====================================

    const logoBase64 = fs.readFileSync(logoPath, "base64");

    const logoUrl = `data:image/png;base64,${logoBase64}`;

    // =====================================
    // LOAD TEMPLATE
    // =====================================

    let html = fs.readFileSync(templatePath, "utf8");

    // =====================================
    // COMPANY DATA
    // =====================================
    html = html.replace(
  /{{logo_url}}/g,
  logoUrl,
);

    html = html.replace(/{{company_name}}/g, company.company_name || "-");

    html = html.replace(/{{company_address}}/g, company.company_address || "-");

    html = html.replace(/{{company_gstin}}/g, company.company_gstin || "-");

    html = html.replace(/{{company_cin}}/g, company.company_cin || "-");

    html = html.replace(/{{company_phone}}/g, company.company_phone || "-");

    html = html.replace(/{{company_email}}/g, company.company_email || "-");

    // =====================================
    // CUSTOMER
    // =====================================

    html = html.replace(/{{customer_name}}/g, dispatch.customer_name || "-");

    html = html.replace(
      /{{customer_address}}/g,
      dispatch.customer_address || "-",
    );

    html = html.replace(/{{customer_gst}}/g, dispatch.customer_gst || "-");

    // =====================================
    // DISPATCH DETAILS
    // =====================================

    html = html.replace(/{{shipment_no}}/g, dispatch.shipment_no || "-");

    html = html.replace(/{{sales_order_no}}/g, dispatch.sales_order_no || "-");

    html = html.replace(/{{dispatch_no}}/g, dispatch.dispatch_no || "-");

    html = html.replace(
      /{{dispatch_date}}/g,
      formatDate(dispatch.dispatch_date),
    );

    html = html.replace(/{{movement_type}}/g, dispatch.movement_type || "-");

    // =====================================
    // VEHICLE DETAILS
    // =====================================

    html = html.replace(/{{vehicle_no}}/g, dispatch.vehicle_no || "-");

    html = html.replace(/{{vehicle_type}}/g, dispatch.vehicle_type || "-");

    html = html.replace(
      /{{vehicle_capacity}}/g,
      dispatch.vehicle_capacity || "-",
    );

    html = html.replace(/{{driver_name}}/g, dispatch.driver_name || "-");

    html = html.replace(/{{driver_contact}}/g, dispatch.driver_contact || "-");

    // =====================================
    // TRANSPORT DETAILS
    // =====================================

    html = html.replace(/{{transport_mode}}/g, dispatch.transport_mode || "-");

    html = html.replace(
      /{{transport_agency}}/g,
      dispatch.transport_agency || "-",
    );

    html = html.replace(/{{lr_number}}/g, dispatch.lr_number || "-");

    html = html.replace(/{{eway_bill_no}}/g, dispatch.eway_bill_no || "-");

    html = html.replace(/{{seal_number}}/g, dispatch.seal_number || "-");

    // =====================================
    // WEIGHT DETAILS
    // =====================================

    // html = html.replace(
    //   /{{gross_weight}}/g,
    //   formatMoney(dispatch.gross_weight),
    // );

    // html = html.replace(/{{tare_weight}}/g, formatMoney(dispatch.tare_weight));

    // html = html.replace(/{{net_weight}}/g, formatMoney(dispatch.net_weight));

    // html = html.replace(
    //   /{{dispatch_qty}}/g,
    //   formatMoney(dispatch.dispatch_qty),
    // );
    html = html.replace(
  /{{gross_weight}}/g,
  formatWeightTon(dispatch.gross_weight),
);

html = html.replace(
  /{{tare_weight}}/g,
  formatWeightTon(dispatch.tare_weight),
);

html = html.replace(
  /{{net_weight}}/g,
  formatWeightTon(dispatch.net_weight),
);

html = html.replace(
  /{{dispatch_qty}}/g,
  formatWeightTon(dispatch.dispatch_qty),
);

    html = html.replace(
      /{{weighbridge_name}}/g,
      dispatch.weighbridge_name || "-",
    );

    // =====================================
    // SHIPPING
    // =====================================

    html = html.replace(
      /{{shipping_address}}/g,
      dispatch.shipping_address || "-",
    );

    html = html.replace(
      /{{expected_delivery}}/g,
      formatDate(dispatch.expected_delivery),
    );

    html = html.replace(/{{remarks}}/g, dispatch.remarks || "-");

    html = html.replace(
      /{{shipment_status}}/g,
      dispatch.shipment_status || "-",
    );

    html = html.replace(/{{product_name}}/g, dispatch.product_name || "-");

    html = html.replace(/{{item_rate}}/g, formatMoney(dispatch.rate || 0));

    html = html.replace(
      /{{gross_amount}}/g,
      formatMoney(dispatch.total_amount || 0),
    );

    html = html.replace(
      /{{discount_amount}}/g,
      formatMoney(dispatch.discount_amount || 0),
    );

    html = html.replace(
      /{{tax_amount}}/g,
      formatMoney(dispatch.tax_amount || 0),
    );

    html = html.replace(
      /{{total_amount}}/g,
      formatMoney(dispatch.final_amount || dispatch.total_amount || 0),
    );

    html = html.replace(
      /{{amount_words}}/g,
      amountInWords(dispatch.final_amount || dispatch.total_amount || 0),
    );

    // =====================================
    // SIGNATURES
    // =====================================

    html = html.replace(/{{prepared_by}}/g, dispatch.prepared_by || "-");

    html = html.replace(/{{security_name}}/g, dispatch.security_name || "-");

    html = html.replace(
      /{{weighbridge_operator}}/g,
      dispatch.weighbridge_operator || "-",
    );

    html = html.replace(/{{approved_by}}/g, dispatch.approved_by || "-");

    // =====================================
    // ITEMS
    // =====================================

    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">
            ${formatMoney(item.qty)}
          </td>

          <td class="text-center">
            ${item.uom || "-"}
          </td>

         

          <td class="text-center">
            ${item.rate || "-"}
          </td>

          <td class="text-right">
            ${formatMoney(item.amount)}
          </td>
        </tr>
      `;
    });

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

    // =====================================
    // LAUNCH BROWSER
    // =====================================

    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",
      ],
    });

    // =====================================
    // PAGE
    // =====================================

    const page = await browser.newPage();

    await page.setContent(html, {
      waitUntil: "load",
    });

    // =====================================
    // PDF
    // =====================================

    const pdf = await page.pdf({
      format: "A4",

      printBackground: true,

      margin: {
        top: "10px",
        bottom: "10px",
        left: "10px",
        right: "10px",
      },
    });

    await browser.close();

    return pdf;
  } catch (error) {
    console.log("DISPATCH INVOICE PDF ERROR:", error);

    throw error;
  }
};

module.exports = generateDispatchInvoicePDF;
