const fs = require('fs');

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

    // Fix openPurchasesReturnModal crashing when it tries to populate the removed itemSelect
    vrJs = vrJs.replace(
        /const itemSelect = document\.getElementById\('purchases-returns-item'\);\s*itemSelect\.innerHTML = '<option value="">-- [^<]+ --<\/option>';\s*currentItems\.forEach\(i => \{\s*itemSelect\.innerHTML \+= `<option value="\$\{i\.id\}">\$\{i\.name\}<\/option>`;\s*\}\);/g,
        ''
    );

    // Let's also check for sales-returns-item just in case
    vrJs = vrJs.replace(
        /const itemSelect = document\.getElementById\('sales-returns-item'\);\s*itemSelect\.innerHTML = '<option value="">-- [^<]+ --<\/option>';\s*currentItems\.forEach\(i => \{\s*itemSelect\.innerHTML \+= `<option value="\$\{i\.id\}">\$\{i\.name\}<\/option>`;\s*\}\);/g,
        ''
    );
    
    // Also check if there's any null references in openSalesReturnModal and openPurchasesReturnModal
    vrJs = vrJs.replace(/document\.getElementById\('sales-returns-item'\)\.innerHTML/g, "/*removed*/");
    vrJs = vrJs.replace(/document\.getElementById\('purchases-returns-item'\)\.innerHTML/g, "/*removed*/");

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

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

    console.log('Fixed openPurchasesReturnModal crash successfully.');
} catch (e) {
    console.error('Error patching vouchers_returns.js:', e);
}
