const fs = require('fs');
let c = fs.readFileSync('settings_module.js', 'utf8');

if (!c.includes('const originalPrint = window.print;')) {
c += `

const originalPrint = window.print;
window.print = function() {
    // Hide original headers if they exist
    document.querySelectorAll('.print-header h1').forEach(h1 => h1.style.display = 'none');

    // Create or update global header
    if (window.currentSettings && (window.currentSettings.company_name || window.currentSettings.logo)) {
        let globalHeader = document.getElementById('global-settings-print-header');
        if (!globalHeader) {
            globalHeader = document.createElement('div');
            globalHeader.id = 'global-settings-print-header';
            globalHeader.style.cssText = 'border-bottom: 2px solid #ccc; padding-bottom: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;';
            document.body.insertBefore(globalHeader, document.body.firstChild);
        }
        
        let html = '';
        if (window.currentSettings.company_name) {
            html += \`<h1 style="margin:0;">\${window.currentSettings.company_name}</h1>\`;
        } else {
            html += \`<div></div>\`;
        }
        if (window.currentSettings.logo) {
            html += \`<img src="\${window.currentSettings.logo}" style="max-height: 80px;">\`;
        }
        globalHeader.innerHTML = html;
        
        // Ensure style exists
        if (!document.getElementById('global-settings-style')) {
            const style = document.createElement('style');
            style.id = 'global-settings-style';
            style.innerHTML = '@media screen { #global-settings-print-header { display: none !important; } } @media print { #global-settings-print-header { display: flex !important; } }';
            document.head.appendChild(style);
            // also append to body in case body was replaced
            document.body.appendChild(style.cloneNode(true));
        }
    }

    originalPrint.apply(window);
};
`;
    fs.writeFileSync('settings_module.js', c);
    console.log('Successfully patched settings_module.js with global print intercept');
} else {
    console.log('Already patched.');
}
