const fs = require('fs');

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

    js = js.replace(/document\.getElementById\('sales-returns-total'\)\.value = '';/g, 
        "if(document.getElementById('sales-returns-total')) document.getElementById('sales-returns-total').value = '';");
        
    js = js.replace(/document\.getElementById\('sales-returns-notes'\)\.value = '';/g, 
        "if(document.getElementById('sales-returns-notes')) document.getElementById('sales-returns-notes').value = '';");

    js = js.replace(/document\.getElementById\('purchases-returns-total'\)\.value = '';/g, 
        "if(document.getElementById('purchases-returns-total')) document.getElementById('purchases-returns-total').value = '';");
        
    js = js.replace(/document\.getElementById\('purchases-returns-notes'\)\.value = '';/g, 
        "if(document.getElementById('purchases-returns-notes')) document.getElementById('purchases-returns-notes').value = '';");

    // Also patch anything else that might be missing in these functions just to be safe
    js = js.replace(/document\.getElementById\('sales-returns-doc-no'\)\.value = '';/g, 
        "if(document.getElementById('sales-returns-doc-no')) document.getElementById('sales-returns-doc-no').value = '';");
        
    js = js.replace(/document\.getElementById\('purchases-returns-doc-no'\)\.value = '';/g, 
        "if(document.getElementById('purchases-returns-doc-no')) document.getElementById('purchases-returns-doc-no').value = '';");

    fs.writeFileSync('vouchers_returns.js', js, 'utf8');
    console.log("Patched vouchers_returns.js null elements.");
    
    // Now let's do app_final.js just in case
    let app = fs.readFileSync('app_final.js', 'utf8');
    app = app.replace(/document\.getElementById\('sales-discount-type'\)\.value = 'value';/g, 
        "if(document.getElementById('sales-discount-type')) document.getElementById('sales-discount-type').value = 'value';");
    app = app.replace(/document\.getElementById\('purchases-discount-type'\)\.value = 'value';/g, 
        "if(document.getElementById('purchases-discount-type')) document.getElementById('purchases-discount-type').value = 'value';");
    fs.writeFileSync('app_final.js', app, 'utf8');
    console.log("Patched app_final.js null elements.");

} catch(e) {
    console.error(e);
}
