const fs = require("fs");
const path = require("path");
const puppeteer = require("puppeteer-core");

const formatDate = (date) => {
  if (!date) return "-";

  return new Date(date).toLocaleDateString("en-GB");
};

const formatDateTime = (date) => {
  if (!date) return "-";

  return new Date(date).toLocaleString("en-GB");
};

const generateWeighmentSlipPDF = async (vehicle) => {
  let html = fs.readFileSync(
    path.join(__dirname, "../../templates/weighTemplate.html"),
    "utf8",
  );

  // LOGO

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

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

  // DATA
  const replacements = {
    ticket_no: vehicle.ticket_no || "-",
    company_name:
  vehicle.company_name || "ERP Enterprise",

company_address:
  vehicle.company_address || "-",

company_pan:
  vehicle.company_pan || "-",

company_gstin:
  vehicle.company_gstin || "-",

    vehicle_no: vehicle.vehicle_number || "-",

    product_name: vehicle.product || "-",

    supplier_name: vehicle.supplier_name || "-",

    transporter_name: vehicle.transporter_name || "-",

    driver_name: vehicle.driver_name || "-",

    destination_name: vehicle.destination_name || "-",

    gate_pass_no: vehicle.gate_pass_no || "-",

    challan_delivery_date: formatDate(vehicle.challan_delivery_date),

    // difference: vehicle.difference || "0",
    difference: (
      (Number(vehicle.delivery_qty || 0) - Number(vehicle.net_weight || 0)) /
      1000
    ).toFixed(2),

    charges: vehicle.charges || "-",

    gate_pass_date: formatDate(vehicle.gate_pass_date),

    lr_no: vehicle.lr_no || "-",

    lr_date: formatDate(vehicle.lr_date),

    transport_order_no: vehicle.transport_order_no || "-",

    quantity_bags: vehicle.quantity_bags || "0",

    delivery_challan_no: vehicle.delivery_challan_no || "-",

    // delivery_qty: vehicle.delivery_qty || "0",
    delivery_qty: (Number(vehicle.delivery_qty || 0) / 1000).toFixed(0),

    // gross_weight: vehicle.in_weight || "0",

    // tare_weight: vehicle.out_weight || "0",

    // net_weight: vehicle.net_weight || "0",

    // gross_weight: (Number(vehicle.in_weight || 0) / 1000).toFixed(0),

    // tare_weight: (Number(vehicle.out_weight || 0) / 1000).toFixed(0),

    // net_weight: (Number(vehicle.net_weight || 0) / 1000).toFixed(0),

gross_weight: Number(
  (Number(vehicle.in_weight || 0) * 1000).toFixed(0)
).toLocaleString(),

tare_weight: Number(
  (Number(vehicle.out_weight || 0) * 1000).toFixed(0)
).toLocaleString(),

net_weight: Number(
  (Number(vehicle.net_weight || 0) * 1000).toFixed(0)
).toLocaleString(),
//     gross_weight: Number(vehicle.in_weight || 0).toFixed(2),

// tare_weight: Number(vehicle.out_weight || 0).toFixed(2),

// net_weight: Number(vehicle.net_weight || 0).toFixed(2),

// gross_weight: Number(vehicle.in_weight || 0).toLocaleString("en-IN", {
//   minimumFractionDigits: 2,
//   maximumFractionDigits: 2,
// }),

// tare_weight: Number(vehicle.out_weight || 0).toLocaleString("en-IN", {
//   minimumFractionDigits: 2,
//   maximumFractionDigits: 2,
// }),

// net_weight: Number(vehicle.net_weight || 0).toLocaleString("en-IN", {
//   minimumFractionDigits: 2,
//   maximumFractionDigits: 2,
// }),

    in_datetime: formatDateTime(vehicle.time_in),

    out_datetime: formatDateTime(vehicle.exit_time),

    remarks: vehicle.security_remarks || "-",

    weighed_by: vehicle.created_by_name || vehicle.created_by || "-",
  };

  Object.entries(replacements).forEach(([key, value]) => {
    html = html.replace(new RegExp(`{{${key}}}`, "g"), value ?? "-");
  });

  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 = generateWeighmentSlipPDF;
