const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');

    // 1. Add Delete button for POSTED settlements
    const searchRender = `} else {
            actions += \`<button class="btn btn-sm btn-secondary" onclick="viewSettlement(\${s.id})">👁️ عرض</button>\`;
        }`;
        
    const replaceRender = `} else {
            actions += \`<button class="btn btn-sm btn-secondary" onclick="viewSettlement(\${s.id})">👁️ عرض</button>\`;
            const canDelete = currentUser.role === 'مدير عام' || (currentUser.permissions && currentUser.permissions.includes('approve_settlements'));
            if (canDelete) {
                actions += \` <button class="btn btn-sm btn-danger" onclick="deleteSettlement(\${s.id})">🗑️ حذف بالقيود والأطراف</button>\`;
            }
        }`;
        
    js = js.replace(searchRender, replaceRender);


    // 2. Rewrite deleteSettlement to clean up ALL related entries
    const searchDelete = `window.deleteSettlement = async function(id) {
    if (!confirm("هل أنت متأكد من حذف هذه التسوية بشكل نهائي؟")) return;
    await window.DB.remove('transactions', id);
    await loadData();
}`;

    const replaceDelete = `window.deleteSettlement = async function(id) {
    if (!confirm("تحذير خطير: هل أنت متأكد من حذف هذه التسوية وجميع القيود المحاسبية وأذون التوريد المرتبطة بها نهائياً؟")) return;
    
    try {
        const s = allInvoices.find(i => i.id === id);
        if (!s) {
            // Fallback if not found in memory
            await window.DB.remove('transactions', id);
        } else {
            // 1. Delete Journal Entries related to expenses
            const relatedJournals = currentJournals.filter(j => j.type === 'settlement' && j.ref_id === id);
            for (let j of relatedJournals) {
                await window.DB.remove('journal_entries', j.id);
            }
            
            // 2. Find and Delete any generated inventory invoices (purchases type)
            const dbInvs = await window.DB.getAll('transactions');
            const generatedInvoices = dbInvs.filter(inv => inv.is_from_settlement === true && inv.settlement_ref === id);
            for (let inv of generatedInvoices) {
                // Delete the generated invoice itself
                await window.DB.remove('transactions', inv.id);
                
                // Delete the journal entry generated by the storekeeper if they already approved it
                const allJournals = await window.DB.getAll('journal_entries');
                const invJournal = allJournals.find(j => j.reference === \`فاتورة مشتريات #\${inv.id}\`);
                if (invJournal) {
                    await window.DB.remove('journal_entries', invJournal.id);
                }
            }
            
            // 3. Delete the settlement itself
            await window.DB.remove('transactions', id);
        }
        
        await loadData();
        if (typeof renderSettlements === 'function') renderSettlements();
        alert("تم حذف التسوية وحذف كل التوجيهات المحاسبية والمخزنية التابعة لها بنجاح.");
    } catch(e) {
        alert("حدث خطأ أثناء الحذف: " + e.message);
    }
}`;

    js = js.replace(searchDelete, replaceDelete);

    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched deleteSettlement and renderSettlements to allow deleting posted settlements with all sides.');
}

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