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 formatWeight = (weight) => {
  return Number(weight || 0).toLocaleString("en-IN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

const formatWeightTon = (val) => {
  return `${(Number(val || 0) / 1000).toLocaleString("en-IN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })} T`;
};

const generateDeliveryChallanPDF = async (
  challan,
  items,
) => {

  try {

    // =========================================
    // TEMPLATE
    // =========================================

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

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

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

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

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

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

    // =========================================
    // REPLACEMENTS
    // =========================================

    const replacements = {

      // COMPANY

      company_name:
        challan.company_name || "-",

      company_address:
        challan.company_address || "-",

      company_gstin:
        challan.company_gstin || "-",

      company_phone:
        challan.company_phone || "-",

      // CHALLAN

      challan_number:
        challan.challan_number || "-",

      challan_date:
        formatDate(
          challan.challan_date,
        ),

      dispatch_date:
        formatDate(
          challan.dispatch_date,
        ),

      order_date:
        formatDate(
          challan.order_date,
        ),

      reference_no:
        challan.reference_no || "-",

      challan_type:
        challan.challan_type || "Dispatch",

      // CUSTOMER

      customer_name:
        challan.customer_name || "-",

      customer_address:
        challan.customer_address || "-",

      customer_phone:
        challan.customer_phone || "-",

      customer_gst:
        challan.customer_gst || "-",

      place_of_supply:
        challan.place_of_supply || "-",

      // VEHICLE

      vehicle_no:
        challan.vehicle_no || "-",

      driver_name:
        challan.driver_name || "-",

      lr_number:
        challan.lr_number || "-",

      // WEIGHTS

      gross_weight:
        formatWeightTon(
          challan.gross_weight,
        ),

      tare_weight:
        formatWeightTon(
          challan.tare_weight,
        ),

      net_weight:
        formatWeightTon(
          challan.net_weight,
        ),

      dispatch_qty:
        formatWeightTon(
          challan.dispatch_qty,
        ),

      // REMARKS

      remarks:
        challan.remarks || "-",
    };

    // =========================================
    // REPLACE VARIABLES
    // =========================================

    Object.entries(replacements).forEach(
      ([key, value]) => {

        html = html.replace(
          new RegExp(`{{${key}}}`, "g"),
          value ?? "-",
        );
      },
    );

    // =========================================
    // ITEMS ROWS
    // =========================================

    let itemsRows = "";

    items.forEach((item, index) => {

      itemsRows += `
        <tr>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:center;
            "
          >
            ${index + 1}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
            "
          >
            ${item.product_name || "-"}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:center;
            "
          >
            ${item.hsn || "-"}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:center;
            "
          >
            ${formatWeight(item.qty)}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:center;
            "
          >
            ${item.uom || "-"}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:right;
            "
          >
            ${formatWeightTon(
              item.gross_weight ||
              challan.gross_weight,
            )}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:right;
            "
          >
            ${formatWeightTon(
              item.tare_weight ||
              challan.tare_weight,
            )}
          </td>

          <td
            style="
              border:1px solid #444;
              padding:8px;
              font-size:12px;
              text-align:right;
            "
          >
            ${formatWeightTon(
              item.net_weight ||
              challan.net_weight,
            )}
          </td>

        </tr>
      `;
    });

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

    // =========================================
    // 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: "networkidle0",
    });

    // =========================================
    // 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(
      "DELIVERY CHALLAN PDF ERROR:",
      error,
    );

    throw error;
  }
};

module.exports = generateDeliveryChallanPDF;