const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');

    // we want to inject our logic right after filtering out financial vouchers in renderInvoices()
    const anchor = "if (t.type === 'receipt' || t.type === 'payment' || t.type === 'money_transfer' || t.type === 'pay_client_abstract') return false;";
    
    const newFilter = `if (t.type === 'receipt' || t.type === 'payment' || t.type === 'money_transfer' || t.type === 'pay_client_abstract') return false;
        
        // Exclude sales/purchases/returns that do not contain any inventory items (e.g. only services)
        if (['sales', 'purchases', 'sales_return', 'purchases_return'].includes(t.type)) {
            let hasInventory = false;
            if (t.items && t.items.length > 0) {
                for (let line of t.items) {
                    const it = currentItems.find(i => String(i.id) === String(line.item_id));
                    if (it && it.category !== 'خدمة') {
                        hasInventory = true;
                        break;
                    }
                }
            }
            if (!hasInventory) return false;
        }
        
        // Exclude petty_cash_settlement that don't have inventory type items
        if (t.type === 'petty_cash_settlement') {
            let hasInventory = false;
            if (t.items && t.items.length > 0) {
                for (let line of t.items) {
                    if (line.item_type === 'inventory') {
                        hasInventory = true;
                        break;
                    }
                }
            }
            if (!hasInventory) return false;
        }`;

    js = js.replace(anchor, newFilter);
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched app_final.js successfully for inventory items filter');
}

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