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 generateQCCertificatePDF = async (qcData) => {
  // =====================================
  // LOAD TEMPLATE
  // =====================================

  let html = fs.readFileSync(
    path.join(__dirname, "../../templates/qcTemplate.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);

  // <td>${row.parameter_name || "-"}</td>
  // <td>${row.specification_type || "-"}</td>
  // <td>${row.specification_value || "-"}</td>
  // <td>${row.accepted_with_penalty || "-"}</td>
  // <td>${row.actual_result || "-"}</td>
  // <td>${row.deduction_percent || "0.00"}%</td>

  // =====================================
  // BUILD PARAMETER ROWS
  // =====================================

  let parameterRows = "";

  //   qcData.parameters.forEach((row) => {

  //     parameterRows += `
  //       <tr>

  //         <td>${row.parameter_name || "-"}</td>

  // <td>${row.specification_type || "-"}</td>

  // <td>${row.specification_value || "-"}%</td>

  // <td>${row.accepted_with_penalty || "-"}</td>

  // <td>${Number(row.actual_result).toFixed(2)}%</td>

  // <td>${Number(row.deduction_percent).toFixed(2)}%</td>
  //       </tr>
  //     `;
  //   });

  // =====================================
  // BUILD DEDUCTION ROWS
  // =====================================
  qcData.parameters.forEach((row) => {
    parameterRows += `
    <tr>
      <td>${row.parameter_name || "-"}</td>

      <td>${row.specification_type || "-"}</td>
      <td>${row.specification_value || "-"}</td>

      <td colspan="2">
        ${row.accepted_with_penalty || "-"}
      </td>

      <td colspan="2">
        ${row.actual_result || "-"}%
      </td>

      <td>
        ${row.deduction_percent || "0.00"}%
      </td>
    </tr>
  `;
  });

  let deductionRows = "";

//   qcData.parameters.forEach((row) => {
//     deductionRows += `
//       <tr>
      


//         <td>${row.parameter_name}</td>
// <td>Deduction's</td>
// <td>${row.deduction_percent}%</td>
// <td>${Number(row.deduction_mt).toFixed(3)}</td>
//       </tr>
//     `;
//   });
qcData.parameters.forEach((row, index) => {
  deductionRows += `
  <tr>
    <td>${row.parameter_name || "-"}</td>
    <td>Deduction's</td>
    <td>${Number(row.deduction_percent || 0).toFixed(2)}%</td>
    <td>${Number(row.deduction_mt || 0).toFixed(3)}</td>
  `;

  if (index === 0) {
    deductionRows += `
      <td><b>Received Weight</b></td>
      <td>${Number(qcData.received_weight_mt || 0).toFixed(3)}</td>
    `;
  } else if (index === 1) {
    deductionRows += `
      <td><b>Total Deduction Weight</b></td>
      <td>${Number(qcData.total_deduction_mt || 0).toFixed(3)}</td>
    `;
  } else if (index === 2) {
    deductionRows += `
      <td><b>Final Weight</b></td>
      <td>${Number(qcData.final_weight_mt || 0).toFixed(3)}</td>
    `;
  } else {
    deductionRows += `
      <td></td>
      <td></td>
    `;
  }

  deductionRows += `</tr>`;
});



//   deductionRows += `
// <tr>
//   <td>Bag Weight %</td>
//   <td>Each Bag</td>
//   <td>200 Gram's</td>
//   <td>${qcData.bag_weight_mt || "0.000"}</td>
// </tr>
// `;

deductionRows += `
<tr>
  <td>Bag Weight %</td>
  <td>Each Bag</td>
  <td>200 Gram's</td>
  <td>${Number(qcData.bag_weight_mt || 0).toFixed(3)}</td>
  <td></td>
  <td></td>
</tr>
`;

  // <td>${row.parameter_name || "-"}</td>
  // <td>Deduction</td>
  // <td>${row.deduction_percent || 0}%</td>
  // <td>${row.deduction_mt || 0}</td>

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

  const replacements = {
    sl_no: qcData.id,

    report_date: formatDate(qcData.created_at),

    po_number: qcData.po_number,

    po_date: formatDate(qcData.po_date),

    invoice_no: qcData.invoice_no,

    vendor_name: qcData.vendor,

    vehicle_number: qcData.vehicle_number,

    material_name: qcData.material_name,

    quantity_bags: qcData.quantity_bags || 0,

    received_weight: qcData.received_weight_mt,

    total_deduction_weight: qcData.total_deduction_mt || 0,

    final_weight: qcData.final_weight_mt,

    total_deduction_percent: qcData.total_deduction_percent,

    qc_result: qcData.qc_result,

    parameter_rows: parameterRows,

    deduction_rows: deductionRows,
  };

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

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

  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,

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

  await browser.close();

  return pdf;
};

module.exports = generateQCCertificatePDF;
