const fs = require('fs');

function fixArrays(filename) {
    if (!fs.existsSync(filename)) return;
    let js = fs.readFileSync(filename, 'utf8');

    const lines = js.split('\n');
    for (let i = 0; i < lines.length; i++) {
        // Fix any line that has an array includes for currentAccounts.find
        if (lines[i].includes('cAcc = currentAccounts.find') && lines[i].includes('.includes(a.name.trim())')) {
            if (lines[i-1] && lines[i-1].includes('receipt')) {
                // Receipt -> Customers
                lines[i] = "          cAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));";
            } else if (lines[i-1] && lines[i-1].includes('} else {')) {
                // Payment -> Suppliers
                lines[i] = "          cAcc = currentAccounts.find(a => a.name.includes('مورد'));";
            } else if (filename.includes('sales')) {
                // Default to customers for sales returns
                lines[i] = "    let cAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));";
            } else if (filename.includes('vouchers')) {
                if (js.includes('generateSalesReturnJournal')) {
                     // Check context
                     if (lines[i].includes('let cAcc')) {
                         lines[i] = "    let cAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));";
                     }
                }
            }
        }
    }
    fs.writeFileSync(filename, lines.join('\n'), 'utf8');
}

fixArrays('vouchers_returns.js');
fixArrays('sales_purchases_module.js');

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

console.log('Fixed all array .includes matching!');
