const fs = require('fs');

let js = fs.readFileSync('vouchers_returns.js', 'utf8');

js = js.replace(
    /cAcc = currentAccounts\.find\(a => \['العملاء', 'عملاء'\]\.includes\(a\.name\.trim\(\)\)\);/g,
    "cAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));"
);

js = js.replace(
    /cAcc = currentAccounts\.find\(a => \['الموردين', 'موردين'\]\.includes\(a\.name\.trim\(\)\)\);/g,
    "cAcc = currentAccounts.find(a => a.name.includes('مورد'));"
);

// Fallback if the encoding is really messed up
const lines = js.split('\n');
for (let i = 0; i < lines.length; i++) {
    if (lines[i].includes('voucher.type === \'receipt\'') && lines[i+1] && lines[i+1].includes('cAcc = currentAccounts.find')) {
        lines[i+1] = "          cAcc = currentAccounts.find(a => a.name.includes('عملاء') || a.name.includes('عميل'));";
    }
    if (lines[i].includes('} else {') && lines[i+1] && lines[i+1].includes('cAcc = currentAccounts.find') && lines[i-2].includes('receipt')) {
        lines[i+1] = "          cAcc = currentAccounts.find(a => a.name.includes('مورد'));";
    }
}
js = lines.join('\n');

fs.writeFileSync('vouchers_returns.js', js, 'utf8');

// 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 postVoucher account matching!');
