const fs = require('fs');
let code = fs.readFileSync('contractors_module.js', 'utf8');

// 1. Fix payClientAbstract
code = code.replace(/window\.openVoucherModal\('receipt'\);/g, "window.currentLinkedInvoiceId = 'cab-' + ab.id;\n        window.openVoucherModal('receipt', 'cab-' + ab.id);");

// 2. Fix abstract number generation in openClientAbstractModal
const regex = /const nextId = .*;\n\s*if\(document\.getElementById\('client-abstract-number'\)\) document\.getElementById\('client-abstract-number'\)\.value = 'CAB-' \+ nextId;/g;
const replacement = `let maxNum = 0;
      currentClientAbstracts.forEach(a => {
          let num = parseInt(String(a.abstract_number).replace(/[^\\d]/g, '')) || 0;
          if(num > maxNum) maxNum = num;
      });
      const nextId = maxNum + 1;
      if(document.getElementById('client-abstract-number')) document.getElementById('client-abstract-number').value = 'جاري ' + nextId;`;

code = code.replace(regex, replacement);

fs.writeFileSync('contractors_module.js', code, 'utf8');

let indexHtml = fs.readFileSync('index.html', 'utf8');
indexHtml = indexHtml.replace(/v=20260610m/g, 'v=20260610n');
fs.writeFileSync('index.html', indexHtml, 'utf8');

console.log('Fixed pay linkage and abstract numbering');
