const fs = require('fs');

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

    // 1. Add window.processInvoicePayment
    if (!appFinalJs.includes('window.processInvoicePayment')) {
        const processPaymentFn = `
window.processInvoicePayment = async function(invoice, invType) {
    const paidAmountInput = document.getElementById(invType + '-paid-amount');
    const treasuryInput = document.getElementById(invType + '-treasury');
    
    if (!paidAmountInput || !treasuryInput) return;
    
    const paidAmount = parseFloat(paidAmountInput.value) || 0;
    const treasuryId = parseInt(treasuryInput.value) || null;
    
    if (paidAmount <= 0) return;
    if (!treasuryId) {
        console.warn('Treasury not selected for payment.');
        return;
    }
    
    const voucherType = invType === 'sales' ? 'receipt' : 'payment';
    
    const v = {
        id: Date.now() + Math.floor(Math.random() * 1000),
        type: voucherType,
        date: invoice.date,
        doc_no: String(invoice.id),
        contact_id: invoice.contact_id,
        treasury_account_id: treasuryId,
        amount: paidAmount,
        notes: \`دفعة نقدية عند حفظ فاتورة \${invType === 'sales' ? 'المبيعات' : 'المشتريات'} رقم \${invoice.id}\`,
        status: 'posted',
        created_by: typeof currentUser !== 'undefined' && currentUser ? currentUser.username : 'النظام',
        linked_invoice_id: invoice.id
    };
    
    await window.DB.add('transactions', v);
    
    if (typeof window.generateVoucherJournal === 'function') {
        await window.generateVoucherJournal(v);
    }
    
    // Reset paid amount so it doesn't duplicate if they edit again and don't change it.
    paidAmountInput.value = 0;
};
`;
        appFinalJs += '\n' + processPaymentFn;
    }

    // 2. Inject into btn-save-sales
    if (!appFinalJs.includes(`await window.processInvoicePayment(obj, 'sales');`)) {
        appFinalJs = appFinalJs.replace(
            /if\(status === 'posted'\) {\s*await generateSalesJournal\(obj\);\s*}/g,
            `if(status === 'posted') {
         await generateSalesJournal(obj);
         await window.processInvoicePayment(obj, 'sales');
      }`
        );
    }

    // 3. Inject into btn-save-purchases
    if (!appFinalJs.includes(`await window.processInvoicePayment(obj, 'purchases');`)) {
        appFinalJs = appFinalJs.replace(
            /if\(status === 'posted'\) {\s*await generatePurchasesJournal\(obj\);\s*}/g,
            `if(status === 'posted') {
         await generatePurchasesJournal(obj);
         await window.processInvoicePayment(obj, 'purchases');
      }`
        );
    }

    // 4. Update renderRelatedLinks to include Vouchers (سندات)
    // We replace the renderRelatedLinks function logic to include vouchers
    if (appFinalJs.includes('window.renderRelatedLinks = function')) {
        if (!appFinalJs.includes('const relatedVouchers = allInvoices.filter(i => (i.type === \'receipt\' || i.type === \'payment\')')) {
            appFinalJs = appFinalJs.replace(
                /if\s*\(\s*typeof\s*currentJournals\s*!==\s*'undefined'\s*\)\s*\{/g,
                `
            const relatedVouchers = allInvoices.filter(i => (i.type === 'receipt' || i.type === 'payment') && (String(i.linked_invoice_id) === String(inv.id) || (i.notes && i.notes.includes(String(inv.id)))));
            relatedVouchers.forEach(v => {
                html += \`<button class="btn btn-sm btn-success" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); if(typeof editVoucher === 'function') editVoucher(\${v.id}); else alert('السند رقم \${v.id} بمبلغ \${v.amount}')">💵 عرض \${v.type === 'receipt' ? 'سند قبض' : 'سند صرف'} (#\${v.id})</button>\`;
                hasLinks = true;
            });
            
            if(inv.status === 'posted' && (inv.type === 'sales' || inv.type === 'purchases')) {
                html += \`<button class="btn btn-sm btn-primary" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('\${inv.type === 'sales' ? 'receipt' : 'payment'}'); }">➕ تسجيل دفعة جديدة</button>\`;
                hasLinks = true;
            }

            if (typeof currentJournals !== 'undefined') {`
            );
        }
    }

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
    console.log('Successfully patched app_final.js for invoice payments.');
} catch(e) {
    console.error('Error patching app_final.js:', e);
}
