const fs = require('fs');

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

    // Fix the syntax error: `if (...) let ...`
    appFinal = appFinal.replace(/if \(inv\.status === 'posted'\) let bPayS = document\.getElementById\('btn-pay-inside-sales'\); if\(bPayS\) bPayS\.style\.display = 'inline-block'; else let bPayS2 = document\.getElementById\('btn-pay-inside-sales'\); if\(bPayS2\) bPayS2\.style\.display = 'none';/g, 
        "{ let bPayS = document.getElementById('btn-pay-inside-sales'); if(inv.status === 'posted') { if(bPayS) bPayS.style.display = 'inline-block'; } else { if(bPayS) bPayS.style.display = 'none'; } }");

    appFinal = appFinal.replace(/if \(inv\.status === 'posted'\) let bPayP = document\.getElementById\('btn-pay-inside-purchases'\); if\(bPayP\) bPayP\.style\.display = 'inline-block'; else let bPayP2 = document\.getElementById\('btn-pay-inside-purchases'\); if\(bPayP2\) bPayP2\.style\.display = 'none';/g, 
        "{ let bPayP = document.getElementById('btn-pay-inside-purchases'); if(inv.status === 'posted') { if(bPayP) bPayP.style.display = 'inline-block'; } else { if(bPayP) bPayP.style.display = 'none'; } }");

    fs.writeFileSync('app_final.js', appFinal, 'utf8');


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

    // Fix the syntax error: `...?.value = ...`
    vrJs = vrJs.replace(/document\.getElementById\('sales-returns-treasury'\)\?\.value = /g, 
        "let trEl = document.getElementById('sales-returns-treasury'); if(trEl) trEl.value = ");

    vrJs = vrJs.replace(/document\.getElementById\('purchases-returns-treasury'\)\?\.value = /g, 
        "let pTrEl = document.getElementById('purchases-returns-treasury'); if(pTrEl) pTrEl.value = ");

    // For the original replace that was meant to be read only, I replaced `.value` with `?.value`.
    // Wait, in `patch_robust_nulls.js`, I did:
    // js = js.replace(/document\.getElementById\('sales-returns-treasury'\)\.value/g, "document.getElementById('sales-returns-treasury')?.value");
    // Some of these were GETTERS and some were SETTERS!
    // Since `?.value` can only be a getter, if there was an assignment, it breaks.
    // So the previous replace fixed the assignment above (which was `document.getElementById('sales-returns-treasury')?.value = ...`).
    // Wait, let's just make sure ALL `?.value =` are fixed.
    
    fs.writeFileSync('vouchers_returns.js', vrJs, 'utf8');

    console.log("Syntax errors patched.");

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