const fs = require('fs');

let js = fs.readFileSync('subcontracts.js', 'utf8');

const newPayAbstract = `window.payAbstract = function(id, suggestedAmount = null) {
    const a = currentSubcontractAbstracts.find(x => x.id === id);
    if (!a) return;
    
    if (suggestedAmount === null) {
        const linkedVouchers = allInvoices.filter(v => (v.type === 'receipt' || v.type === 'payment') && v.linked_invoice_id == 'sca-' + id && v.status === 'posted');
        let totalPaid = 0;
        linkedVouchers.forEach(v => totalPaid += parseFloat(v.amount) || 0);
        let remaining = (parseFloat(a.net_value) || 0) - totalPaid;
        // fix floating point errors
        remaining = Math.round(remaining * 100) / 100;
        suggestedAmount = Math.max(0, remaining);
    }
    
    window.openVoucherModal('payment');
    
    setTimeout(() => {
        document.getElementById('voucher-linked-invoice').value = 'sca-' + a.id;
        document.getElementById('voucher-amount').value = suggestedAmount;
        document.getElementById('voucher-status').value = 'posted';
        
        const sc = currentSubcontracts.find(s => s.id === parseInt(a.contract_id));
        if (sc) {
            const subc = currentContacts.find(c => c.id === parseInt(sc.subcontractor_id));
            if (subc) {
                document.getElementById('voucher-contact').value = subc.id;
            }
        }
    }, 100);
};`;

// We will replace the entire window.payAbstract function
const startIndex = js.indexOf('window.payAbstract = function');
if (startIndex !== -1) {
    let endIndex = js.indexOf('};', startIndex);
    if (endIndex !== -1) {
        endIndex += 2;
        js = js.substring(0, startIndex) + newPayAbstract + js.substring(endIndex);
        fs.writeFileSync('subcontracts.js', js, 'utf8');
        console.log('Successfully patched payAbstract in subcontracts.js!');
    }
}

// Also update fix_subcontracts.js
if (fs.existsSync('fix_subcontracts.js')) {
    let fixJs = fs.readFileSync('fix_subcontracts.js', 'utf8');
    const start2 = fixJs.indexOf('window.payAbstract = function');
    if (start2 !== -1) {
        let end2 = fixJs.indexOf('};', start2);
        if (end2 !== -1) {
            end2 += 2;
            fixJs = fixJs.substring(0, start2) + newPayAbstract + fixJs.substring(end2);
            fs.writeFileSync('fix_subcontracts.js', fixJs, 'utf8');
            console.log('Successfully patched payAbstract in fix_subcontracts.js!');
        }
    }
}

// Cache buster
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/v=\d+/g, 'v=' + Date.now());
fs.writeFileSync('index.html', html, 'utf8');
