const fs = require('fs');

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

const fieldsToProtect = [
    'sales-returns-total',
    'sales-returns-notes',
    'sales-returns-treasury',
    'purchases-returns-total',
    'purchases-returns-notes',
    'purchases-returns-treasury'
];

fieldsToProtect.forEach(field => {
    // For Assignments: document.getElementById('X').value = ...
    // Note: We use a regex to capture the rest of the line
    const regexAssign = new RegExp(\`document\\\\.getElementById\\\\('\${field}'\\\\)\\\\.value = (.*?);\\n\`, 'g');
    js = js.replace(regexAssign, \`const el_\${field.replace(/-/g, '_')} = document.getElementById('\${field}'); if(el_\${field.replace(/-/g, '_')}) el_\${field.replace(/-/g, '_')}.value = $1;\\n\`);

    // For Reading: document.getElementById('X').value
    // Not strictly needed if they just return empty string, but let's be careful.
    const regexRead = new RegExp(\`document\\\\.getElementById\\\\('\${field}'\\\\)\\\\.value\`, 'g');
    js = js.replace(regexRead, \`(document.getElementById('\${field}') ? document.getElementById('\${field}').value : '')\`);
});

// Also protect the treasurySelect.innerHTML line
js = js.replace(/treasurySelect\.innerHTML =/g, 'if(treasurySelect) treasurySelect.innerHTML =');
js = js.replace(/treasurySelect\.innerHTML \+=/g, 'if(treasurySelect) treasurySelect.innerHTML +=');

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

// Bust cache
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 JS null errors');
