const fs = require('fs');
const path = 'd:/برنامج مخازن/index.html';

let html = fs.readFileSync(path, 'utf8');

const injectionTarget = '<script src="sales_purchases_module.js?v=202606030939" defer></script>';

if (!html.includes('petty_cash_module.js')) {
    const scriptsToInject = `
  <script src="petty_cash_module.js" defer></script>
  <script defer>
    // Auto-cleanup script for garbled data
    setTimeout(async () => {
      try {
        const txs = await window.DB.getAll('transactions');
        for (let tx of txs) {
           if (tx.notes && (tx.notes.includes('????') || tx.notes.includes('\\uFFFD'))) {
               await window.DB.remove('transactions', tx.id);
           }
        }
        const jrnls = await window.DB.getAll('journal_entries');
        for (let j of jrnls) {
           if (j.reference && (j.reference.includes('????') || j.reference.includes('\\uFFFD'))) {
               await window.DB.remove('journal_entries', j.id);
           }
        }
        const accs = await window.DB.getAll('accounts');
        for (let a of accs) {
           if (a.name && (a.name.includes('????') || a.name.includes('\\uFFFD'))) {
               await window.DB.remove('accounts', a.id);
           }
        }
        console.log("Cleanup script executed successfully.");
      } catch (e) {
        console.error("Cleanup error: ", e);
      }
    }, 3000);
  </script>`;

    html = html.replace(injectionTarget, injectionTarget + scriptsToInject);
    fs.writeFileSync(path, html, 'utf8');
    console.log('Injected successfully');
} else {
    console.log('Already injected');
}
