const fs = require('fs');

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

    // 1. Add Pay button to renderSales
    appFinalJs = appFinalJs.replace(
        /(let actions = `<button class="action-btn btn-view" onclick="openSalesModal\(\$\{inv\.id\}\)">[^<]+<\/button>`;)/g,
        `$1
    if (inv.status === 'posted') {
        actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('receipt', \${inv.id}, \${inv.contact_id}); }">سداد 💵</button>\`;
    }`
    );

    // 2. Add Pay button to renderPurchases
    appFinalJs = appFinalJs.replace(
        /(let actions = `<button class="action-btn btn-view" onclick="openPurchasesModal\(\$\{inv\.id\}\)">[^<]+<\/button>`;)/g,
        `$1
    if (inv.status === 'posted') {
        actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${inv.id}; openVoucherModal('payment', \${inv.id}, \${inv.contact_id}); }">سداد 💵</button>\`;
    }`
    );
    
    // Also add to renderInvoices (المعاملات) just in case
    appFinalJs = appFinalJs.replace(
        /(let actions = `<button class="action-btn btn-view" onclick="viewDetails\(\$\{t\.id\}\)">[^<]+<\/button>`;)/g,
        `$1
    if (t.status === 'posted' && (t.type === 'sales' || t.type === 'purchases')) {
        actions += \` <button class="action-btn" style="background:#28a745; color:white; margin-right:5px; padding: 5px 10px; font-weight: bold;" onclick="if(typeof openVoucherModal === 'function') { window.currentLinkedInvoiceId = \${t.id}; openVoucherModal('\${t.type === 'sales' ? 'receipt' : 'payment'}', \${t.id}, \${t.contact_id}); }">سداد 💵</button>\`;
    }`
    );

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
    console.log('Added pay buttons to tables successfully with robust regex.');
    
    // 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');
    
} catch (e) {
    console.error('Error patching:', e);
}
