const fs = require('fs');

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

    // Fix btn-save-sales netTotal calculation
    spJs = spJs.replace(
        /let netTotal = 0;\s*currentSalesLines\.forEach\(line => \{[\s\S]*?netTotal \+= \(tot - disc\);\s*\}\);/,
        `let netTotal = 0;
    currentSalesLines.forEach(line => {
        const tot = (parseFloat(line.qty) || 0) * (parseFloat(line.price) || 0);
        let disc = 0;
        const dType = line.discount_type || line.discountType || 'percent';
        const dVal = parseFloat(line.discount) || 0;
        if (dType === 'percent') {
            disc = tot * (dVal / 100);
        } else {
            disc = dVal;
        }
        if (disc > tot) disc = tot;
        netTotal += (tot - disc);
    });`
    );

    // Fix btn-save-purchases netTotal calculation
    spJs = spJs.replace(
        /let netTotal = 0;\s*currentPurchasesLines\.forEach\(line => \{[\s\S]*?netTotal \+= \(tot - disc\);\s*\}\);/,
        `let netTotal = 0;
    currentPurchasesLines.forEach(line => {
        const tot = (parseFloat(line.qty) || 0) * (parseFloat(line.price) || 0);
        let disc = 0;
        const dType = line.discount_type || line.discountType || 'percent';
        const dVal = parseFloat(line.discount) || 0;
        if (dType === 'percent') {
            disc = tot * (dVal / 100);
        } else {
            disc = dVal;
        }
        if (disc > tot) disc = tot;
        netTotal += (tot - disc);
    });`
    );

    // Fix generateSalesJournal to calculate from scratch
    spJs = spJs.replace(
        /let totalDiscount = 0;\s*let totalCogs = 0;\s*\(invoice\.items \|\| \[\]\)\.forEach\(line => \{[\s\S]*?const grossTotal = netTotal \+ totalDiscount;/,
        `let totalDiscount = 0;
      let totalCogs = 0;
      let computedGross = 0;
      (invoice.items || []).forEach(line => {
          const qty = parseFloat(line.qty) || 0;
          const price = parseFloat(line.price) || 0;
          const tot = qty * price;
          computedGross += tot;
          
          let disc = 0;
          const dType = line.discount_type || line.discountType || 'percent';
          const dVal = parseFloat(line.discount) || 0;
          
          if (dType === 'percent') {
              disc = tot * (dVal / 100);
          } else {
              disc = dVal;
          }
          if (disc > tot) disc = tot;
          totalDiscount += disc;
  
          if(typeof window.balancesCache !== 'undefined') {
              let b = window.balancesCache[line.item_id];
              let avgCost = b ? b.avgCost : 0;
              totalCogs += (qty * avgCost);
          }
      });
  
      const grossTotal = computedGross;
      const netTotal = computedGross - totalDiscount;`
    );

    // Fix generatePurchasesJournal to calculate from scratch
    spJs = spJs.replace(
        /let totalDiscount = 0;\s*\(invoice\.items \|\| \[\]\)\.forEach\(line => \{[\s\S]*?const grossTotal = netTotal \+ totalDiscount;/,
        `let totalDiscount = 0;
    let computedGross = 0;
    (invoice.items || []).forEach(line => {
        const qty = parseFloat(line.qty) || 0;
        const price = parseFloat(line.price) || 0;
        const tot = qty * price;
        computedGross += tot;
        
        let disc = 0;
        const dType = line.discount_type || line.discountType || 'percent';
        const dVal = parseFloat(line.discount) || 0;
        
        if (dType === 'percent') {
            disc = tot * (dVal / 100);
        } else {
            disc = dVal;
        }
        if (disc > tot) disc = tot;
        totalDiscount += disc;
    });

    const grossTotal = computedGross;
    const netTotal = computedGross - totalDiscount;`
    );

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

    let html = fs.readFileSync('d:/برنامج مخازن/index.html', 'utf8');
    const version = Date.now().toString();
    html = html.replace(/v=\d+/g, 'v=' + version);
    fs.writeFileSync('d:/برنامج مخازن/index.html', html, 'utf8');

    console.log('Bulletproof totals applied!');
} catch (e) {
    console.error(e);
}
