const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let appJs = fs.readFileSync('app_final.js', 'utf8');
    
    const oldDeleteInvoice = /window\.deleteInvoice\s*=\s*async\s*function\s*\(\s*id\s*\)\s*\{\s*if\s*\(\s*confirm[^}]+\)\s*\{\s*await\s*window\.DB\.remove\('transactions',\s*id\s*\);\s*await\s*loadData\(\);\s*closeModal\('details-modal'\);\s*\}\s*\}/g;
    
    const newDeleteInvoice = `window.deleteInvoice = async function(id) {
  if(confirm('تنبيه: سيتم حذف الحركة والقيد المحاسبي المرتبط بها إن وجد! تأكيد؟')) {
    // Attempt to delete associated journal entries
    try {
        const allJ = await window.DB.getAll('journal_entries') || [];
        const possibleRefs = [
            \`فاتورة مبيعات #\${id}\`, \`فاتورة مشتريات #\${id}\`,
            \`voucher_\${id}\`, \`transfer_\${id}\`,
            \`sales_return_\${id}\`, \`purchases_return_\${id}\`,
            \`pay_abstract_\${id}\`, \`settlement_\${id}\`,
            \`subcontract_abstract_\${id}\`, \`pay_subcontract_abstract_\${id}\`
        ];
        
        // Find journal entries that match this transaction ID
        const jToDelete = allJ.filter(j => 
            (j.reference && possibleRefs.includes(j.reference)) || 
            (j.ref_id === id) ||
            (j.reference && j.reference.includes(\`#\${id}\`))
        );
        
        for (let j of jToDelete) {
            await window.DB.remove('journal_entries', j.id);
        }
    } catch (e) {
        console.error('Error deleting related journal entry:', e);
    }

    await window.DB.remove('transactions', id);
    await loadData(); 
    if(typeof closeModal === 'function') closeModal('details-modal');
  }
}`;

    // Replace all occurrences of the old deleteInvoice function (if any)
    if (appJs.match(oldDeleteInvoice)) {
        appJs = appJs.replace(oldDeleteInvoice, newDeleteInvoice);
        fs.writeFileSync('app_final.js', appJs, 'utf8');
        console.log('Patched app_final.js deleteInvoice');
    } else {
        console.log('Could not match old deleteInvoice in app_final.js, attempting manual inject...');
        // Manual inject
        const manualOld = `window.deleteInvoice = async function(id) {
  if(confirm('تنبيه: سيتم حذف الحركة! تأكيد؟')) {
    await window.DB.remove('transactions', id);
    await loadData(); closeModal('details-modal');
  }
}`;
        if (appJs.includes(manualOld)) {
            appJs = appJs.replace(manualOld, newDeleteInvoice);
            fs.writeFileSync('app_final.js', appJs, 'utf8');
            console.log('Patched app_final.js deleteInvoice (manual)');
        }
    }
}

// Cache buster
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/v=\d+/g, 'v=' + Date.now());
fs.writeFileSync('index.html', html, 'utf8');
