const fs = require('fs');

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

    // Fix btn-pay-inside-sales
    js = js.replace(/document\.getElementById\('btn-pay-inside-sales'\)\.style\.display = 'inline-block';/g, "let bPayS = document.getElementById('btn-pay-inside-sales'); if(bPayS) bPayS.style.display = 'inline-block';");
    js = js.replace(/document\.getElementById\('btn-pay-inside-sales'\)\.style\.display = 'none';/g, "let bPayS2 = document.getElementById('btn-pay-inside-sales'); if(bPayS2) bPayS2.style.display = 'none';");
    
    // Fix btn-delete-inside-sales
    js = js.replace(/document\.getElementById\('btn-delete-inside-sales'\)\.style\.display = 'inline-block';/g, "let bDelS = document.getElementById('btn-delete-inside-sales'); if(bDelS) bDelS.style.display = 'inline-block';");
    js = js.replace(/document\.getElementById\('btn-delete-inside-sales'\)\.style\.display = 'none';/g, "let bDelS2 = document.getElementById('btn-delete-inside-sales'); if(bDelS2) bDelS2.style.display = 'none';");

    // Fix btn-pay-inside-purchases
    js = js.replace(/document\.getElementById\('btn-pay-inside-purchases'\)\.style\.display = 'inline-block';/g, "let bPayP = document.getElementById('btn-pay-inside-purchases'); if(bPayP) bPayP.style.display = 'inline-block';");
    js = js.replace(/document\.getElementById\('btn-pay-inside-purchases'\)\.style\.display = 'none';/g, "let bPayP2 = document.getElementById('btn-pay-inside-purchases'); if(bPayP2) bPayP2.style.display = 'none';");
    
    // Fix btn-delete-inside-purchases
    js = js.replace(/document\.getElementById\('btn-delete-inside-purchases'\)\.style\.display = 'inline-block';/g, "let bDelP = document.getElementById('btn-delete-inside-purchases'); if(bDelP) bDelP.style.display = 'inline-block';");
    js = js.replace(/document\.getElementById\('btn-delete-inside-purchases'\)\.style\.display = 'none';/g, "let bDelP2 = document.getElementById('btn-delete-inside-purchases'); if(bDelP2) bDelP2.style.display = 'none';");

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

    // Also bust cache for app_final.js
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
    
    console.log("Patched app_final.js buttons.");
} catch(e) {
    console.error(e);
}
