const fs = require('fs');

// 1. Update temp.js (enhance deleteInvoice)
let tempJs = fs.readFileSync('d:/برنامج مخازن/temp.js', 'utf8');

tempJs = tempJs.replace(
    /window\.deleteInvoice = async function\(id\) \{[\s\S]*?\n\}/,
    `window.deleteInvoice = async function(id) {
  if(confirm('تحذير: هل أنت متأكد من حذف هذا المستند؟ (سيتم حذف قيود اليومية المرتبطة به إن وجدت)')) {
    try {
        await window.DB.remove('transactions', id);
        
        // Also find and delete associated journal entries
        const journals = await window.DB.getAll('journal_entries');
        const relatedJ = journals.find(j => j.reference && (j.reference.includes('#' + id) || j.reference.includes(id.toString())));
        if (relatedJ) {
            await window.DB.remove('journal_entries', relatedJ.id);
        }
        
        // Also delete associated vouchers if any
        const vouchers = await window.DB.getAll('vouchers');
        const relatedV = vouchers.filter(v => v.linked_invoice_id === id);
        for (let v of relatedV) {
            await window.DB.remove('vouchers', v.id);
        }
        
        alert('تم الحذف بنجاح!');
        await loadData(); 
        if(typeof closeModal === 'function') closeModal('details-modal');
    } catch(e) {
        alert('حدث خطأ أثناء الحذف: ' + e.message);
    }
  }
}`
);

fs.writeFileSync('d:/برنامج مخازن/temp.js', tempJs, 'utf8');

// 2. Update sales_purchases_module.js (allow admin to delete posted)
let spJs = fs.readFileSync('d:/برنامج مخازن/sales_purchases_module.js', 'utf8');

spJs = spJs.replace(
    /if\(inv\.status === 'draft' && currentUser && currentUser\.role === 'مدير عام'\) \{/g,
    `if(currentUser && currentUser.role === 'مدير عام') {`
);

fs.writeFileSync('d:/برنامج مخازن/sales_purchases_module.js', spJs, 'utf8');

// Bust cache in index.html
let html = fs.readFileSync('d:/برنامج مخازن/index.html', 'utf8');
const version = Date.now().toString();
html = html.replace(/v=\d+/g, 'v=' + version);
fs.writeFileSync('d:/برنامج مخازن/index.html', html, 'utf8');

console.log('deleteInvoice patched and admin allowed to delete all invoices.');
