const fs = require('fs');

let js = fs.readFileSync('d:/برنامج مخازن/sales_purchases_module.js', 'utf8');

// Replace calculation in btn-save-sales
js = js.replace(
    /currentSalesLines\.forEach\(line => \{\s*const tot = \(line\.qty \* line\.price\);\s*const disc = tot \* \(line\.discount \/ 100\);\s*netTotal \+= \(tot - disc\);\s*\}\);/g,
    `currentSalesLines.forEach(line => {
      const tot = (line.qty * line.price);
      let disc = 0;
      const isPercent = line.discount_type === 'percent' || !line.discount_type;
      if (isPercent) {
          disc = tot * (line.discount / 100);
      } else {
          disc = line.discount || 0;
      }
      if (disc > tot) disc = tot;
      netTotal += (tot - disc);
    });`
);

// Replace calculation in btn-save-purchases
js = js.replace(
    /currentPurchasesLines\.forEach\(line => \{\s*const tot = \(line\.qty \* line\.price\);\s*const disc = tot \* \(line\.discount \/ 100\);\s*netTotal \+= \(tot - disc\);\s*\}\);/g,
    `currentPurchasesLines.forEach(line => {
      const tot = (line.qty * line.price);
      let disc = 0;
      const isPercent = line.discount_type === 'percent' || !line.discount_type;
      if (isPercent) {
          disc = tot * (line.discount / 100);
      } else {
          disc = line.discount || 0;
      }
      if (disc > tot) disc = tot;
      netTotal += (tot - disc);
    });`
);

fs.writeFileSync('d:/برنامج مخازن/sales_purchases_module.js', js);
console.log("Calculations fixed!");
