const fs = require('fs');

function patchModule(modulePath, buttonIds) {
    if (!fs.existsSync(modulePath)) return;
    let content = fs.readFileSync(modulePath, 'utf8');
    
    // Check if already patched
    if (content.includes('cloneNode(true)')) {
        console.log(`Module ${modulePath} is already patched.`);
        return;
    }

    let prependLogic = `
// Strip old listeners from app_final.js
${JSON.stringify(buttonIds)}.forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});\n\n`;

    fs.writeFileSync(modulePath, prependLogic + content, 'utf8');
    console.log(`Patched ${modulePath}`);
}

patchModule('d:/برنامج مخازن/accounting_module.js', ['btn-save-account', 'btn-save-journal']);
patchModule('d:/برنامج مخازن/sales_purchases_module.js', ['btn-save-sales', 'btn-save-purchases', 'btn-save-invoice']);
patchModule('d:/برنامج مخازن/petty_cash_module.js', ['btn-save-settlement']); // I'm not sure if btn-save-settlement is the ID, let's assume it is.
patchModule('d:/برنامج مخازن/vouchers_returns.js', ['btn-execute-decision', 'btn-confirm-receipt']); 

