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

const newCode = `
window.payClientAbstract = function(id, suggestedAmount = null) {
    const ab = currentClientAbstracts.find(a => a.id === id);
    if (!ab) return;
    
    // Find client in contacts list (might need to map project client_name to contact)
    // Or just leave contact empty if not easily mapped
    
    if (suggestedAmount === null) {
        const linkedVouchers = allInvoices.filter(v => (v.type === 'receipt' || v.type === 'payment') && v.linked_invoice_id == 'cab-' + id && v.status === 'posted');
        let totalPaid = 0;
        linkedVouchers.forEach(v => totalPaid += parseFloat(v.amount) || 0);
        let remaining = parseFloat(ab.net_value) - totalPaid;
        remaining = Math.round(remaining * 100) / 100;
        suggestedAmount = Math.max(0, remaining);
    }
    
    window.openVoucherModal('receipt');
    
    setTimeout(() => {
        // Find contact by name to prefill if possible
        const contact = currentContacts.find(c => c.name === ab.client_name);
        if(contact) {
            document.getElementById('voucher-contact').value = contact.id;
        }
        
        document.getElementById('voucher-amount').value = suggestedAmount;
        document.getElementById('voucher-notes').value = 'دفعة من مستخلص إيراد رقم ' + (ab.abstract_number || ab.id);
        document.getElementById('voucher-status').value = 'posted';
        document.getElementById('voucher-modal-title').innerText = 'سند قبض لمستخلص إيراد (' + (ab.abstract_number || ab.id) + ')';
        window.currentLinkedInvoiceId = 'cab-' + ab.id;
    }, 300);
};
`;

if (!code.includes('window.payClientAbstract = function')) {
    code += newCode;
    fs.writeFileSync('app_final.js', code, 'utf8');
    console.log('payClientAbstract added to app_final.js');
} else {
    console.log('payClientAbstract already exists.');
}
