const fs = require('fs');

try {
    let code = fs.readFileSync('vouchers_returns.js', 'utf8');

    code = code.replace(
        /window\.openVoucherModal = function\(type\) \{[\s\n]*window\.currentLinkedInvoiceId = null;/g,
        `window.openVoucherModal = function(type, linkedInvoiceId = null, contactId = null) {
  window.currentLinkedInvoiceId = linkedInvoiceId;`
    );

    code = code.replace(
        /document\.getElementById\('voucher-contact'\)\.innerHTML \+= `<option value="\$\{c\.id\}"\>\$\{c\.name\} \(\$\{typeName\}\)<\/option>`;\n  \}\);/g,
        `document.getElementById('voucher-contact').innerHTML += \`<option value="\${c.id}">\${c.name} (\${typeName})</option>\`;
  });
  if (contactId) document.getElementById('voucher-contact').value = contactId;
  if (linkedInvoiceId) document.getElementById('voucher-notes').value = 'دفعة للفاتورة رقم ' + linkedInvoiceId;
  `
    );

    fs.writeFileSync('vouchers_returns.js', code, 'utf8');
    
    // Also fix my previous patch where I called openVoucherModal incorrectly
    let appCode = fs.readFileSync('app_final.js', 'utf8');
    appCode = appCode.replace(
        /window\.currentLinkedInvoiceId = \$\{inv\.id\}; openVoucherModal\('\$\{inv\.type === 'sales' \? 'receipt' : 'payment'\}'\);/g,
        `openVoucherModal('\${inv.type === 'sales' ? 'receipt' : 'payment'}', \${inv.id}, \${inv.contact_id});`
    );
    fs.writeFileSync('app_final.js', appCode, 'utf8');
    
    console.log('Successfully patched vouchers_returns.js and app_final.js openVoucherModal call');
} catch (e) {
    console.error(e);
}
