const fs = require('fs');

try {
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    // Add treasury population to openSalesModal
    appFinalJs = appFinalJs.replace(
        /const itemSel = document\.getElementById\('sales-item'\);\n  itemSel\.innerHTML = '<option value="">اختر الصنف\.\.\.<\/option>' \+ currentItems\.map\(i => `<option value="\$\{i\.id\}">\$\{i\.name\} \(\$\{i\.unit \|\| 'وحدة'\}\)<\/option>`\)\.join\(''\);/g,
        `const itemSel = document.getElementById('sales-item');
  itemSel.innerHTML = '<option value="">اختر الصنف...</option>' + currentItems.map(i => \`<option value="\${i.id}">\${i.name} (\${i.unit || 'وحدة'})</option>\`).join('');
  
  const trSel = document.getElementById('sales-treasury');
  if (trSel) {
      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('نقد'));
      trSel.innerHTML = '<option value="">-- اختر الخزينة/البنك --</option>' + cashAccounts.map(a => \`<option value="\${a.id}">\${a.name}</option>\`).join('');
  }`
    );

    // Add treasury population to openPurchasesModal
    appFinalJs = appFinalJs.replace(
        /const itemSel2 = document\.getElementById\('purchases-item'\);\n  itemSel2\.innerHTML = '<option value="">اختر الصنف\.\.\.<\/option>' \+ currentItems\.map\(i => `<option value="\$\{i\.id\}">\$\{i\.name\} \(\$\{i\.unit \|\| 'وحدة'\}\)<\/option>`\)\.join\(''\);/g,
        `const itemSel2 = document.getElementById('purchases-item');
  itemSel2.innerHTML = '<option value="">اختر الصنف...</option>' + currentItems.map(i => \`<option value="\${i.id}">\${i.name} (\${i.unit || 'وحدة'})</option>\`).join('');
  
  const trSel2 = document.getElementById('purchases-treasury');
  if (trSel2) {
      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('نقد'));
      trSel2.innerHTML = '<option value="">-- اختر الخزينة/البنك --</option>' + cashAccounts.map(a => \`<option value="\${a.id}">\${a.name}</option>\`).join('');
  }`
    );

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');

    // Bust cache
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('Populated treasury dropdowns in invoice modals successfully.');
} catch (e) {
    console.error('Error patching:', e);
}
