const fs = require('fs');

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

    // completely rewrite openVoucherModal
    const openVoucherModalStr = `window.openVoucherModal = function(type, linkedInvoiceId = null, contactId = null) {
  window.currentLinkedInvoiceId = linkedInvoiceId;
  document.getElementById('voucher-modal-title').innerText = type === 'receipt' ? 'إنشاء سند قبض (استلام نقدية)' : 'إنشاء سند صرف (دفع نقدية)';
  document.getElementById('edit-voucher-id').value = '';
  document.getElementById('voucher-type').value = type;
  document.getElementById('voucher-date').value = new Date().toISOString().slice(0, 16);
  document.getElementById('voucher-doc-no').value = linkedInvoiceId ? String(linkedInvoiceId) : '';
  document.getElementById('voucher-amount').value = '';
  document.getElementById('voucher-notes').value = linkedInvoiceId ? 'دفعة للفاتورة رقم ' + linkedInvoiceId : '';
  document.getElementById('voucher-status').value = 'posted';
  document.getElementById('btn-save-voucher').style.display = 'inline-block';
  
  const contactSelect = document.getElementById('voucher-contact');
  contactSelect.innerHTML = '<option value="">-- اختر --</option>';
  currentContacts.forEach(c => {
    let typeName = c.type;
    contactSelect.innerHTML += \`<option value="\${c.id}">\${c.name} (\${typeName})</option>\`;
  });
  if (contactId) {
      contactSelect.value = contactId;
  }
  
  const treasurySelect = document.getElementById('voucher-treasury-account');
  const cashAccounts = currentAccounts.filter(a => a.name.includes('خزين') || a.name.includes('خزن') || a.name.includes('بنك') || a.name.includes('بنوك') || a.name.includes('صندوق') || a.name.includes('عهد') || a.name.includes('سلف') || a.name.includes('نقد'));
  treasurySelect.innerHTML = '<option value="">-- اختر الخزينة/البنك --</option>';
  cashAccounts.forEach(a => {
    treasurySelect.innerHTML += \`<option value="\${a.id}">\${a.name}</option>\`;
  });
  
  document.getElementById('voucher-modal').classList.add('active');
};`;

    code = code.replace(/window\.openVoucherModal = function\([\s\S]*?classList\.add\('active'\);\n\};/, openVoucherModalStr);
    
    fs.writeFileSync('vouchers_returns.js', code, 'utf8');
    
    console.log('Fixed openVoucherModal.');

} catch (e) {
    console.error(e);
}
