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

// Insert treasury population in openSalesModal
if (!code.includes('sales-treasury')) {
    code = code.replace(
        /const itemSel = document\.getElementById\('sales-item'\);[\s\S]*?itemSel\.innerHTML = '.*?<\/select>'\)\.join\(''\);/m,
        `$&
  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('');
  }`
    );
}

// Insert treasury population in openPurchasesModal
if (!code.includes('purchases-treasury')) {
    code = code.replace(
        /const itemSelP = document\.getElementById\('purchases-item'\);[\s\S]*?itemSelP\.innerHTML = '.*?<\/select>'\)\.join\(''\);/m,
        `$&
  const pTrSel = document.getElementById('purchases-treasury');
  if (pTrSel) {
    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('نقد'));
    pTrSel.innerHTML = '<option value="">-- اختر الخزينة/البنك --</option>' + cashAccounts.map(a => \`<option value="\${a.id}">\${a.name}</option>\`).join('');
  }`
    );
}

// Ensure items are populated in POS/Sales
// Actually it's already there with itemSel.innerHTML = ... currentItems.map(...)

// What about Journal Entries for POS? The user said automate journal entry on POS sale.
// We need to find the save function in sales_purchases_module.js
// Wait, the save function is usually bound inside document.addEventListener('DOMContentLoaded', ...) or similar.

fs.writeFileSync('sales_purchases_module.js', code, 'utf8');
console.log('Patched treasury lists');
