const fs = require('fs');

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

    // Update the IN block
    appFinalJs = appFinalJs.replace(
        /if \(\(inv\.type === 'in' \|\| inv\.type === 'opening_balance'\) \|\| \(inv\.type === 'purchases' && inv\.status === 'posted'\)\) \{/g,
        `if ((inv.type === 'in' || inv.type === 'opening_balance') || ((inv.type === 'purchases' || inv.type === 'sales_return') && inv.status === 'posted')) {`
    );

    // Update the IN warehouse logic
    // We need to add to 'fromWh' if it's sales_return, and toWh if it's others
    appFinalJs = appFinalJs.replace(
        /b\.globalQty \+= item\.qty;\s*if\(toWh\) b\.warehouses\[toWh\] \+= item\.qty;\s*b\.totalValue \+= \(item\.qty \* item\.price\);/g,
        `b.globalQty += item.qty;
        if (inv.type === 'sales_return') {
            if(fromWh) b.warehouses[fromWh] += item.qty;
        } else {
            if(toWh) b.warehouses[toWh] += item.qty;
        }
        b.totalValue += (item.qty * item.price);`
    );

    // Update the OUT block
    appFinalJs = appFinalJs.replace(
        /else if \(inv\.type === 'out_project' \|\| inv\.type === 'depreciate_asset' \|\| \(inv\.type === 'sales' && inv\.status === 'posted'\)\) \{/g,
        `else if (inv.type === 'out_project' || inv.type === 'depreciate_asset' || ((inv.type === 'sales' || inv.type === 'purchases_return') && inv.status === 'posted')) {`
    );

    // Update the OUT warehouse logic
    appFinalJs = appFinalJs.replace(
        /b\.globalQty -= item\.qty;\s*if\(fromWh\) b\.warehouses\[fromWh\] -= item\.qty;\s*b\.totalValue -= \(item\.qty \* b\.avgCost\);/g,
        `b.globalQty -= item.qty;
        if (inv.type === 'purchases_return') {
            if(toWh) b.warehouses[toWh] -= item.qty;
        } else {
            if(fromWh) b.warehouses[fromWh] -= item.qty;
        }
        b.totalValue -= (item.qty * b.avgCost);`
    );
    
    // Fix item transactions view logic (line 2375-2400)
    appFinalJs = appFinalJs.replace(
        /\(inv\.items \|\| \[\]\)\.forEach\(it => \{/g,
        `(inv.items || []).forEach(it => {
      if (it.item_id === parseInt(itemId)) {
        if (inv.type === 'sales_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مبيعات', loc: inv.from_warehouse_name || '', whId: inv.from_warehouse_id, qtyIn: it.qty, qtyOut: 0, price: it.price });
           return;
        }
        if (inv.type === 'purchases_return' && inv.status === 'posted') {
           records.push({ date: inv.date, inv: inv, type: 'مرتجع مشتريات', loc: inv.to_warehouse_name || '', whId: inv.to_warehouse_id, qtyIn: 0, qtyOut: it.qty, price: it.price });
           return;
        }
      }`
    );

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
    console.log('Inventory logic updated for returns successfully.');
} catch (e) {
    console.error('Error patching inventory logic:', e);
}
