const fs = require('fs');

try {
    let indexHtml = fs.readFileSync('index.html', 'utf8');

    // Remove the flex-row containing sales-returns-item
    indexHtml = indexHtml.replace(/<div class="flex-row">[\s\S]*?<select id="sales-returns-item">[\s\S]*?addSalesReturnsLine\(\)[\s\S]*?<\/div>/, '');

    // Remove the flex-row containing purchases-returns-item
    indexHtml = indexHtml.replace(/<div class="flex-row">[\s\S]*?<select id="purchases-returns-item">[\s\S]*?addPurchasesReturnsLine\(\)[\s\S]*?<\/div>/, '');

    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + timestamp);
    
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    // Make loadSalesForReturn more robust
    let vrJs = fs.readFileSync('vouchers_returns.js', 'utf8');
    vrJs = vrJs.replace(
        /const invoices = \(window\.allInvoices \|\| \[\]\)\.filter\(inv => inv\.type === 'sales' && inv\.contact_id == contactId && inv\.status === 'posted'\);/g,
        `const invoices = (window.allInvoices || []).filter(inv => inv.type === 'sales' && inv.contact_id == contactId && inv.status !== 'draft');`
    );
    vrJs = vrJs.replace(
        /const invoices = \(window\.allInvoices \|\| \[\]\)\.filter\(inv => inv\.type === 'purchases' && inv\.contact_id == contactId && inv\.status === 'posted'\);/g,
        `const invoices = (window.allInvoices || []).filter(inv => inv.type === 'purchases' && inv.contact_id == contactId && inv.status !== 'draft');`
    );
    
    fs.writeFileSync('vouchers_returns.js', vrJs, 'utf8');
    
    console.log('Old returns UI removed successfully and filter updated to include all non-draft invoices.');
} catch (e) {
    console.error('Error patching HTML UI:', e);
}
