const fs = require('fs');

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

    // Update renderSalesLines to populate the voucher list
    appFinalJs = appFinalJs.replace(
        /const idStr = document\.getElementById\('edit-sales-id'\)\.value;\n  let paid = 0;\n  if\(idStr\) \{\n    const id = parseInt\(idStr\);\n    paid = allInvoices\.filter[\s\S]*?\}\n  document\.getElementById\('sales-paid-total'\)\.innerText/g,
        `const idStr = document.getElementById('edit-sales-id').value;
  let paid = 0;
  if(idStr) {
    const id = parseInt(idStr);
    const linkedVouchers = allInvoices.filter(t => (t.type === 'receipt' || t.type === 'payment') && t.status === 'posted' && String(t.linked_invoice_id) === String(id));
    paid = linkedVouchers.reduce((sum, v) => sum + (parseFloat(v.total_amount) || 0), 0);
    
    const container = document.getElementById('sales-linked-vouchers-container');
    const list = document.getElementById('sales-linked-vouchers-list');
    if (linkedVouchers.length > 0) {
        if(container) container.style.display = 'block';
        if(list) list.innerHTML = linkedVouchers.map(v => {
            const accName = currentAccounts.find(a => a.id == v.treasury_account_id)?.name || 'غير محدد';
            return \`<li>🔹 سند \${v.type === 'receipt' ? 'قبض' : 'صرف'} رقم <strong>\${v.id}</strong> بمبلغ <strong>\${v.total_amount}</strong> (الخزينة: \${accName}) بتاريخ \${v.date.split('T')[0]}</li>\`;
        }).join('');
    } else {
        if(container) container.style.display = 'none';
        if(list) list.innerHTML = '';
    }
  } else {
    const container = document.getElementById('sales-linked-vouchers-container');
    if(container) container.style.display = 'none';
  }
  document.getElementById('sales-paid-total').innerText`
    );

    // Update renderPurchasesLines to populate the voucher list
    appFinalJs = appFinalJs.replace(
        /const idStr = document\.getElementById\('edit-purchases-id'\)\.value;\n  let paid = 0;\n  if\(idStr\) \{\n    const id = parseInt\(idStr\);\n    paid = allInvoices\.filter[\s\S]*?\}\n  document\.getElementById\('purchases-paid-total'\)\.innerText/g,
        `const idStr = document.getElementById('edit-purchases-id').value;
  let paid = 0;
  if(idStr) {
    const id = parseInt(idStr);
    const linkedVouchers = allInvoices.filter(t => (t.type === 'receipt' || t.type === 'payment') && t.status === 'posted' && String(t.linked_invoice_id) === String(id));
    paid = linkedVouchers.reduce((sum, v) => sum + (parseFloat(v.total_amount) || 0), 0);
    
    const container = document.getElementById('purchases-linked-vouchers-container');
    const list = document.getElementById('purchases-linked-vouchers-list');
    if (linkedVouchers.length > 0) {
        if(container) container.style.display = 'block';
        if(list) list.innerHTML = linkedVouchers.map(v => {
            const accName = currentAccounts.find(a => a.id == v.treasury_account_id)?.name || 'غير محدد';
            return \`<li>🔹 سند \${v.type === 'receipt' ? 'قبض' : 'صرف'} رقم <strong>\${v.id}</strong> بمبلغ <strong>\${v.total_amount}</strong> (الخزينة: \${accName}) بتاريخ \${v.date.split('T')[0]}</li>\`;
        }).join('');
    } else {
        if(container) container.style.display = 'none';
        if(list) list.innerHTML = '';
    }
  } else {
    const container = document.getElementById('purchases-linked-vouchers-container');
    if(container) container.style.display = 'none';
  }
  document.getElementById('purchases-paid-total').innerText`
    );

    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('Added detailed vouchers list inside modals successfully.');
} catch (e) {
    console.error('Error patching:', e);
}
