
// Strip old listeners from app_final.js
["btn-save-settlement"].forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});

window.saveSettlement = async function() {
    const custodyId = document.getElementById('settlement-custody').value;
    const date = document.getElementById('settlement-date').value;
    
    // "يرجى اختيار العهدة والتاريخ."
    if (!custodyId || !date) return alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1%20%D8%A7%D9%84%D8%B9%D9%87%D8%AF%D8%A9%20%D9%88%D8%A7%D9%84%D8%AA%D8%A7%D8%B1%D9%8A%D8%AE.'));
    
    const items = [];
    let hasError = false;
    
    document.querySelectorAll('#settlement-items-tbody tr').forEach(tr => {
        const type = tr.querySelector('.set-type').value;
        const whId = tr.querySelector('.set-warehouse').value;
        const projId = tr.querySelector('.set-project').value;
        const batchEl = tr.querySelector('.set-batch');
        const batchId = (batchEl && batchEl.value) ? parseInt(batchEl.value) : null;
        const qty = parseFloat(tr.querySelector('.set-qty').value) || 0;
        const price = parseFloat(tr.querySelector('.set-price').value) || 0;
        const attachment = tr.querySelector('.set-attachment-td').dataset.attachment || '';
        const statement = tr.querySelector('.set-statement') ? tr.querySelector('.set-statement').value : '';
        
        if (qty <= 0 || price <= 0) { alert(decodeURIComponent('%D8%A7%D9%84%D9%83%D9%85%D9%8A%D8%A9%20%D9%88%D8%A7%D9%84%D8%B3%D8%B9%D8%B1%20%D9%8A%D8%AC%D8%A8%20%D8%A3%D9%86%20%D8%AA%D9%83%D9%88%D9%86%20%D9%85%D9%88%D8%AC%D8%A8%D8%A9.')); hasError = true; return; }
        
        const line = {
            item_type: type,
            warehouse_id: whId ? parseInt(whId) : null,
            project_id: projId ? parseInt(projId) : null,
            concrete_order_id: batchId,
            batch_id: batchId,
            qty: qty,
            price: price,
            attachment: attachment,
            statement: statement
        };
        
        if (type === 'inventory') {
            const itemId = tr.querySelector('.set-item-id') ? tr.querySelector('.set-item-id').value : (tr.querySelector('.set-item') ? tr.querySelector('.set-item').value : null);
            if (!itemId) { alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1%20%D8%A7%D9%84%D8%B5%D9%86%D9%81.')); hasError = true; return; }
            if (!whId) { alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1%20%D8%A7%D9%84%D9%85%D8%AE%D8%B2%D9%86%20%D9%84%D8%A8%D9%86%D8%AF%20%D8%A7%D9%84%D9%85%D8%AE%D8%B2%D9%88%D9%86.')); hasError = true; return; }
            line.item_id = parseInt(itemId);
            line.item_name = currentItems.find(i => String(i.id) === String(line.item_id))?.name || '';
        } else {
            const expAccId = tr.querySelector('.set-expense-id') ? tr.querySelector('.set-expense-id').value : null;
            if (expAccId) {
                line.expense_account_id = parseInt(expAccId);
                line.expense_name = currentAccounts.find(a => String(a.id) === String(line.expense_account_id))?.name || '';
            } else {
                const expName = tr.querySelector('.set-expense-name') ? tr.querySelector('.set-expense-name').value.trim() : '';
                line.expense_name = expName;
            }
        }
        
        items.push(line);
    });
    
    if (hasError) return;
    // "يرجى إضافة بنود للتسوية."
    if (items.length === 0) return alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A5%D8%B6%D8%A7%D9%81%D8%A9%20%D8%A8%D9%86%D9%88%D8%AF%20%D9%84%D9%84%D8%AA%D8%B3%D9%88%D9%8A%D8%A9.'));

    const isEditId = document.getElementById('settlement-modal').dataset.editId;
    
    const settlement = {
        type: 'petty_cash_settlement',
        date: date,
        user: currentUser.username,
        custody_account_id: parseInt(custodyId),
        status: 'pending',
        items: items
    };

    try {
        let savedId = null;
        if (isEditId) {
            const existing = allInvoices.find(i => String(i.id) === String(isEditId));
            savedId = existing ? existing.id : isEditId;
        }
        if (savedId) {
            settlement.id = savedId;
            await window.DB.update('transactions', settlement);
        } else {
            savedId = await window.DB.add('transactions', settlement);
        }
        closeModal('settlement-modal'); 
        await loadData(); 
        if (typeof renderSettlements === 'function') renderSettlements();
        // AUTO APPROVE HAS BEEN REMOVED TO PREVENT DUPLICATE GENERATION ON SAVE
    } catch(e) {
        // "خطأ: "
        alert(decodeURIComponent('%D8%AE%D8%B7%D8%A3%3A%20') + e.message);
    }
}

window._savingAndApproving = false;
window.saveAndApproveSettlement = async function() {
    if (window._savingAndApproving) return;
    window._savingAndApproving = true;
    const btn = document.getElementById('set-btn-approve');
    if(btn) btn.disabled = true;
    
    try {
        const custodyId = document.getElementById('settlement-custody').value;
        const date = document.getElementById('settlement-date').value;
        
        // "���� ������ ������ ��������."
        if (!custodyId || !date) { alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1%20%D8%A7%D9%84%D8%B9%D9%87%D8%AF%D8%A9%20%D9%88%D8%A7%D9%84%D8%AA%D8%A7%D8%B1%D9%8A%D8%AE.')); return; }
        
        const items = [];
        let hasError = false;
        
        document.querySelectorAll('#settlement-items-tbody tr').forEach(tr => {
            const type = tr.querySelector('.set-type').value;
            const whId = tr.querySelector('.set-warehouse').value;
            const projId = tr.querySelector('.set-project').value;
        const batchEl = tr.querySelector('.set-batch');
        const batchId = (batchEl && batchEl.value) ? parseInt(batchEl.value) : null;
        const qty = parseFloat(tr.querySelector('.set-qty').value) || 0;
        const price = parseFloat(tr.querySelector('.set-price').value) || 0;
        const attachment = tr.querySelector('.set-attachment-td').dataset.attachment || '';
        const statement = tr.querySelector('.set-statement') ? tr.querySelector('.set-statement').value : '';
        
        if (qty <= 0 || price <= 0) { alert(decodeURIComponent('%D8%A7%D9%84%D9%83%D9%85%D9%8A%D8%A9%20%D9%88%D8%A7%D9%84%D8%B3%D8%B9%D8%B1%20%D9%8A%D8%AC%D8%A8%20%D8%A3%D9%86%20%D8%AA%D9%83%D9%88%D9%86%20%D9%85%D9%88%D8%AC%D8%A8%D8%A9.')); hasError = true; return; }
        
        const it = {
            item_type: type,
            warehouse_id: whId ? parseInt(whId) : null,
            project_id: projId ? parseInt(projId) : null,
            concrete_order_id: batchId,
            batch_id: batchId,
            qty: qty,
            price: price,
            attachment: attachment,
            statement: statement
        };
        
        if (type === 'inventory') {
            const itemId = tr.querySelector('.set-item-id') ? tr.querySelector('.set-item-id').value : (tr.querySelector('.set-item') ? tr.querySelector('.set-item').value : null);
            if (!itemId) { alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1%20%D8%A7%D9%84%D8%B5%D9%86%D9%81.')); hasError = true; return; }
            if (!whId) { alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1%20%D8%A7%D9%84%D9%85%D8%AE%D8%B2%D9%86%20%D9%84%D8%A8%D9%86%D8%AF%20%D8%A7%D9%84%D9%85%D8%AE%D8%B2%D9%88%D9%86.')); hasError = true; return; }
            it.item_id = parseInt(itemId);
            it.item_name = currentItems.find(i => String(i.id) === String(it.item_id))?.name || '';
        } else {
            const expAccId = tr.querySelector('.set-expense-id') ? tr.querySelector('.set-expense-id').value : null;
            if (expAccId) {
                it.expense_account_id = parseInt(expAccId);
                it.expense_name = currentAccounts.find(a => String(a.id) === String(it.expense_account_id))?.name || '';
            } else {
                const expName = tr.querySelector('.set-expense-name') ? tr.querySelector('.set-expense-name').value.trim() : '';
                it.expense_name = expName;
            }
        }
        
        items.push(it);
    });
    
    if (hasError) return;
    // "يرجى إضافة بنود للتسوية."
    if (items.length === 0) return alert(decodeURIComponent('%D9%8A%D8%B1%D8%AC%D9%89%20%D8%A5%D8%B6%D8%A7%D9%81%D8%A9%20%D8%A8%D9%86%D9%88%D8%AF%20%D9%84%D9%84%D8%AA%D8%B3%D9%88%D9%8A%D8%A9.'));

    const isEditId = document.getElementById('settlement-modal').dataset.editId;
    if (!isEditId) return alert("الرجاء حفظ التسوية كمسودة أولاً قبل الاعتماد.");
    
    const settlement = {
        id: (() => {
            const existing = allInvoices.find(i => String(i.id) === String(isEditId));
            return existing ? existing.id : isEditId;
        })(),
        type: 'petty_cash_settlement',
        date: date,
        user: currentUser.username,
        custody_account_id: parseInt(custodyId),
        status: 'pending',
        items: items
    };

        await window.DB.update('transactions', settlement);
        await window.approveSettlement(settlement.id, true);
        
        closeModal('settlement-modal'); 
        await loadData(); 
        if (typeof renderSettlements === 'function') renderSettlements();
    } catch(e) {
        // "خطأ: "
        alert(decodeURIComponent('%D8%AE%D8%B7%D8%A3%3A%20') + e.message);
    } finally {
        window._savingAndApproving = false; if(document.getElementById('set-btn-approve')) document.getElementById('set-btn-approve').disabled = false;
    }
}

window.ensureExpenseAccountExists = async function(expenseName) {
    // Check if account already exists
    // "مصروفات"
    let expParent = currentAccounts.find(a => a.name === decodeURIComponent('%D9%85%D8%B5%D8%B1%D9%88%D9%81%D8%A7%D8%AA') || a.name === 'المصروفات' || a.name.includes('المصروفات') || (a.code === '5' && a.parent_id === null));
    if (!expParent) return null; // Should never happen based on loadData
    
    // Find exact match
    let acc = currentAccounts.find(a => a.name === expenseName && a.parent_id === expParent.id);
    if (acc) return acc.id;
    
    // Not found? Create it!
    const childCount = currentAccounts.filter(a => a.parent_id === expParent.id).length;
    let newCode = expParent.code + (childCount + 1).toString().padStart(2, '0');
    
    // Ensure code uniqueness just in case
    while(currentAccounts.find(a => a.code === newCode)) {
       newCode = newCode + '1';
    }
    
    const newAccId = await window.DB.add('accounts', {
        code: newCode,
        name: expenseName,
        type: 'expenses', // Safe latin key
        parent_id: expParent.id
    });
    
    // Refresh accounts list
    currentAccounts = await window.DB.getAll('accounts');
    return newAccId;
}

window._approvingSettlements = window._approvingSettlements || {};
window.approveSettlement = async function(id, skipConfirm = false) {
    if (window._approvingSettlements[id]) return;
    window._approvingSettlements[id] = true;
    
    // "هل أنت متأكد من اعتماد هذه التسوية؟ لا يمكن تعديلها بعد ذلك وسيتم توليد قيود اليومية وحركة المخازن."
    let s = allInvoices.find(i => String(i.id) === String(id));
    try {
        if (window.DB) {
            const allT = await window.DB.getAll('transactions');
            s = allT.find(i => String(i.id) === String(id)) || s;
        }
    } catch(e) { console.error(e); }
    if (!s || s.status !== 'pending') return;
    
    const unroutedExpenses = s.items.filter(it => it.item_type === 'expense' && (!it.expense_name || it.expense_name.trim() === ''));
    if (unroutedExpenses.length > 0) {
        alert("يرجى توجيه جميع المصروفات وتحديد اسم المصروف لكل بند قبل الاعتماد.");
        return;
    }
    
    try {
        let expensesTotal = 0;
        const journalLines = [];
        const inventoryByWarehouse = {};
        
        for (let it of s.items) {
            const lineTotal = it.qty * it.price;
            
            if (it.item_type === 'expense') {
                expensesTotal += lineTotal;
                const expAccId = await ensureExpenseAccountExists(it.expense_name);
                journalLines.push({ account_id: expAccId, debit: lineTotal, credit: 0, notes: (it.statement ? it.statement : (decodeURIComponent('%D8%A5%D8%AB%D8%A8%D8%A7%D8%AA%20%D9%85%D8%B5%D8%B1%D9%88%D9%81%20%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%D8%B1%D9%82%D9%85%20') + s.id)), project_id: it.project_id });
            } else if (it.item_type === 'inventory') {
                const whId = it.warehouse_id || s.warehouse_id;
                if (!inventoryByWarehouse[whId]) inventoryByWarehouse[whId] = [];
                inventoryByWarehouse[whId].push(it);
            }
        }
        
        // If there are expenses, create a direct Journal Entry
        if (expensesTotal > 0 && journalLines.length > 0) {
            // "إجمالي مصروفات تسوية عهدة رقم "
            journalLines.push({ account_id: s.custody_account_id, debit: 0, credit: expensesTotal, notes: decodeURIComponent('%D8%A5%D8%AC%D9%85%D8%A7%D9%84%D9%8A%20%D9%85%D8%B5%D8%B1%D9%88%D9%81%D8%A7%D8%AA%20%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%D8%B1%D9%82%D9%85%20') + s.id });
            const je = {
                date: s.date && s.date.includes('T') ? s.date.split('T')[0] : s.date,
                // "تسوية عهدة #"
                reference: decodeURIComponent('%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%23') + s.id,
                desc: decodeURIComponent('%D8%A5%D8%AC%D9%85%D8%A7%D9%84%D9%8A%20%D9%85%D8%B5%D8%B1%D9%88%D9%81%D8%A7%D8%AA%20%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%D8%B1%D9%82%D9%85%20') + s.id,
                rows: journalLines,
                total: expensesTotal,
                status: 'posted',
                // "النظام"
                created_by: decodeURIComponent('%D8%A7%D9%84%D9%86%D8%B8%D8%A7%D9%85'),
                user: currentUser.username,
                type: 'settlement',
                ref_id: s.id
            };
            await window.DB.add('journal_entries', je);
        }

        // For inventory items, create "purchases" invoices pending storekeeper approval
        for (let whId in inventoryByWarehouse) {
            const items = inventoryByWarehouse[whId];
            let invTotal = 0;
            items.forEach(it => invTotal += (it.qty * it.price));
            
            const whName = currentWarehouses.find(w => String(w.id) === String(whId))?.name || '';
            const custodyName = currentAccounts.find(a => a.id == s.custody_account_id)?.name || 'Custody';

            const newInv = {
                type: 'purchases',
                date: new Date().toISOString(),
                user: currentUser.username,
                contact_name: custodyName, // Show custody as supplier visually
                to_warehouse_id: parseInt(whId),
                to_warehouse_name: whName,
                status: 'pending_store',
                is_from_settlement: true,
                custody_account_id: s.custody_account_id,
                settlement_ref: s.id,
                total: invTotal,
                total_amount: invTotal,
                items: items,
                // "بضاعة من تسوية عهدة رقم "
                notes: decodeURIComponent('%D8%A8%D8%B6%D8%A7%D8%B9%D8%A9%20%D9%85%D9%86%20%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%D8%B1%D9%82%D9%85%20') + s.id
            };
            
            const newInvId = await window.DB.add('transactions', newInv);
            if (typeof window.sendInvoiceToStore === 'function') {
                await window.sendInvoiceToStore(newInvId);
            }
        }
        
        // Update settlement status
        s.status = 'posted';
        await window.DB.update('transactions', s);
        
        // SILENT APPROVAL - NO ALERT
        await loadData();
        if (typeof renderSettlements === 'function') renderSettlements();
        
    } catch(e) {
        alert(decodeURIComponent('%D8%AE%D8%B7%D8%A3%3A%20') + e.message);
    } finally {
        window._approvingSettlements[id] = false;
    }
}

window.deleteSettlement = async function(id) {
    // "هل أنت متأكد؟ سيتم حذف هذه التسوية وجميع القيود المرتبطة بها نهائياً."
    if (!confirm(decodeURIComponent('%D9%87%D9%84%20%D8%A3%D9%86%D8%AA%20%D9%85%D8%AA%D8%A3%D9%83%D8%AF%D8%9F%20%D8%B3%D9%8A%D8%AA%D9%85%20%D8%AD%D8%B0%D9%81%20%D9%87%D8%B0%D9%87%20%D8%A7%D9%84%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D9%88%D8%AC%D9%85%D9%8A%D8%B9%20%D8%A7%D9%84%D9%82%D9%8A%D9%88%D8%AF%20%D8%A7%D9%84%D9%85%D8%B1%D8%AA%D8%A8%D8%B7%D8%A9%20%D8%A8%D9%87%D8%A7%20%D9%86%D9%87%D8%A7%D8%A6%D9%8A%D8%A7%D9%8B.'))) return;
    
    try {
        const s = allInvoices.find(i => String(i.id) === String(id));
        if (!s) {
            try {
                const allTransactions = await window.DB.getAll('transactions');
                const linkedVouchers = allTransactions.filter(t => t.linked_invoice_id == id);
                for (let v of linkedVouchers) {
                    const vJournals = allJ.filter(j => j.reference && j.reference.includes(`${v.id}`));
                    for (let j of vJournals) {
                        await window.DB.remove('journal_entries', j.id);
                    }
                    await window.DB.remove('transactions', v.id);
                }
            } catch(e) { console.error(e); }
            await window.DB.remove('transactions', id);
        } else {
            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);
            }
            
            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) {
                await window.DB.remove('transactions', inv.id);
                const allJournals = await window.DB.getAll('journal_entries');
                // Check both "فاتورة مشتريات #" and "تسوية عهدة #" just in case
                const invJournal = allJournals.find(j => j.reference === decodeURIComponent('%D9%81%D8%A7%D8%AA%D9%88%D8%B1%D8%A9%20%D9%85%D8%B4%D8%AA%D8%B1%D9%8A%D8%A7%D8%AA%20%23') + inv.id || j.reference === decodeURIComponent('%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%23') + inv.settlement_ref);
                if (invJournal) {
                    await window.DB.remove('journal_entries', invJournal.id);
                }
            }
            
            try {
                const allTransactions = await window.DB.getAll('transactions');
                const linkedVouchers = allTransactions.filter(t => t.linked_invoice_id == id);
                for (let v of linkedVouchers) {
                    const vJournals = allJ.filter(j => j.reference && j.reference.includes(`${v.id}`));
                    for (let j of vJournals) {
                        await window.DB.remove('journal_entries', j.id);
                    }
                    await window.DB.remove('transactions', v.id);
                }
            } catch(e) { console.error(e); }
            
            await window.DB.remove('transactions', id);
        }
        
        await loadData();
        if (typeof renderSettlements === 'function') renderSettlements();
        // "تم حذف التسوية وجميع الحركات المرتبطة بها بنجاح."
        alert(decodeURIComponent('%D8%AA%D9%85%20%D8%AD%D8%B0%D9%81%20%D8%A7%D9%84%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D9%88%D8%AC%D9%85%D9%8A%D8%B9%20%D8%A7%D9%84%D8%AD%D8%B1%D9%83%D8%A7%D8%AA%20%D8%A7%D9%84%D9%85%D8%B1%D8%AA%D8%A8%D8%B7%D8%A9%20%D8%A8%D9%87%D8%A7%20%D8%A8%D9%86%D8%AC%D8%A7%D8%AD.'));
    } catch(e) {
        alert(decodeURIComponent('%D8%AE%D8%B7%D8%A3%3A%20') + e.message);
    }
}

window.viewSettlement = function(id) {
    openSettlementModal(id);
    // "عرض تسوية عهدة #"
    document.getElementById('settlement-modal-title').innerText = decodeURIComponent('%D8%B9%D8%B1%D8%B6%20%D8%AA%D8%B3%D9%88%D9%8A%D8%A9%20%D8%B9%D9%87%D8%AF%D8%A9%20%23') + id;
    if (typeof renderRelatedLinks === 'function') renderRelatedLinks('settlement', id, 'settlement-related-links');
    
    const modal = document.getElementById('settlement-modal');
    modal.querySelectorAll('input, select, button').forEach(el => {
        // "إغلاق" and "عرض المرفق"
        if (!el.classList.contains('close') && el.innerText !== decodeURIComponent('%D8%A5%D8%BA%D9%84%D8%A7%D9%82') && el.innerText !== decodeURIComponent('%D8%B9%D8%B1%D8%B6%20%D8%A7%D9%84%D9%85%D8%B1%D9%81%D9%82')) {
            if (el.tagName === 'BUTTON') el.style.display = 'none';
            else el.disabled = true;
        }
    });
}


