
// 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 => {
        // Keep close, إغلاق, عرض المرفق, export buttons and filter checkbox visible
        if (!el.classList.contains('close') && !el.classList.contains('settlement-export-btn') && el.id !== 'show-closed-batches-cb' && 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;
        }
    });
}

// ============ نظام إظهار وإخفاء وتحسين تفاصيل أمر الصب بالتسويات ============
function _getInvoicesArray() {
    if (typeof allConcreteInvoices !== 'undefined' && Array.isArray(allConcreteInvoices)) {
        return allConcreteInvoices;
    }
    return window.allConcreteInvoices || [];
}
function _getProjectsArray() {
    if (typeof currentProjects !== 'undefined' && Array.isArray(currentProjects)) {
        return currentProjects;
    }
    return window.currentProjects || [];
}
function _getContactsArray() {
    if (typeof currentContacts !== 'undefined' && Array.isArray(currentContacts)) {
        return currentContacts;
    }
    if (typeof contacts !== 'undefined' && Array.isArray(contacts)) {
        return contacts;
    }
    return window.currentContacts || window.contacts || [];
}

function _getBatchDetails(inv) {
    if (!inv) return null;
    let targetName = inv.target_name || '';
    if (!targetName && inv.target_id) {
        if (inv.client_type === 'project') {
            const projs = _getProjectsArray();
            const p = projs.find(x => String(x.id) === String(inv.target_id));
            if (p) targetName = p.name;
        } else {
            const conts = _getContactsArray();
            const c = conts.find(x => String(x.id) === String(inv.target_id));
            if (c) targetName = c.name;
        }
    }
    if (!targetName) targetName = 'عميل/مشروع عام';

    let qty = inv.billed_qty !== undefined && inv.billed_qty !== null && inv.billed_qty !== '' ? inv.billed_qty : inv.total_qty;
    qty = (parseFloat(qty) || 0).toFixed(1) + ' م³';
    
    const isClosed = inv.settlement_closed === true || inv.settlement_closed === 'true' || String(inv.settlement_closed) === '1' || inv.status === 'ملغي' || inv.status === 'مغلق';

    return { id: inv.id, targetName, qty, isClosed, date: inv.date || '', status: inv.status || '' };
}

function enrichBatchSelect(select, forceRefresh = false) {
    if (!select || (select.dataset.enriched === 'true' && !forceRefresh)) return;
    const invoices = _getInvoicesArray();
    if (!invoices || invoices.length === 0) return;
    
    const currentVal = String(select.value || '');
    const cb = document.getElementById('show-closed-batches-cb');
    const showClosed = cb ? cb.checked : false;

    let html = '<option value="">-- أمر الصب (اختياري) --</option>';
    invoices.forEach(inv => {
        const details = _getBatchDetails(inv);
        if (!details) return;
        
        // Hide if closed unless it is currently selected in this specific row or checkbox is checked
        if (details.isClosed && !showClosed && String(inv.id) !== currentVal) {
            return;
        }
        
        const label = `أمر #${inv.id} | العميل: ${details.targetName} (${details.qty})${details.isClosed ? ' [مغلق]' : ''}`;
        html += `<option value="${inv.id}" ${String(inv.id) === currentVal ? 'selected' : ''}>${label}</option>`;
    });
    
    select.innerHTML = html;
    if (currentVal && select.value !== currentVal) {
        select.value = currentVal;
    }
    select.dataset.enriched = 'true';
    
    // Ensure any leftover old badges from previous versions are removed
    const oldBadge = select.parentElement ? select.parentElement.querySelector('.batch-info-badge') : null;
    if (oldBadge) oldBadge.remove();
}

window.refreshSettlementBatchesList = function(force = true) {
    document.querySelectorAll('#settlement-items-tbody .set-batch').forEach(sel => {
        enrichBatchSelect(sel, force);
    });
};

function applySettlementPermissionsDefault(tr = null) {
    if (typeof currentUser === 'undefined' || !currentUser) return;
    try {
        const rows = tr ? [tr] : (document.querySelectorAll('#settlement-items-tbody tr') || []);
        rows.forEach(row => {
            // 1. Default Project based on user permission (صلاحية)
            const projSel = row.querySelector('.set-project');
            if (projSel && (!projSel.value || projSel.value === '')) {
                let defProj = null;
                if (currentUser.project_id && String(currentUser.project_id) !== 'null') {
                    defProj = currentUser.project_id;
                } else if (currentUser.allowed_projects && Array.isArray(currentUser.allowed_projects) && currentUser.allowed_projects.length > 0) {
                    defProj = currentUser.allowed_projects[0];
                }
                if (defProj) {
                    projSel.value = defProj;
                }
            }

            // 2. Default Warehouse based on user permission (صلاحية)
            const whSel = row.querySelector('.set-warehouse');
            if (whSel && (!whSel.value || whSel.value === '')) {
                let defWh = null;
                if (currentUser.warehouse_id && String(currentUser.warehouse_id) !== 'null') {
                    defWh = currentUser.warehouse_id;
                } else if (currentUser.allowed_warehouses && Array.isArray(currentUser.allowed_warehouses) && currentUser.allowed_warehouses.length > 0) {
                    defWh = currentUser.allowed_warehouses[0];
                }
                if (defWh) {
                    whSel.value = defWh;
                }
            }
        });

        // 3. Default Custody Account in header if creating a new settlement
        const custodySel = document.getElementById('settlement-custody');
        if (custodySel && (!custodySel.value || custodySel.value === '')) {
            if (currentUser.custody_account_id && String(currentUser.custody_account_id) !== 'null') {
                custodySel.value = currentUser.custody_account_id;
            } else if (typeof currentAccounts !== 'undefined') {
                const myAcc = currentAccounts.find(a => a && a.name && a.name.includes('عهدة') && (
                    (currentUser.username && a.name.toLowerCase().includes(currentUser.username.toLowerCase())) ||
                    (currentUser.name && a.name.toLowerCase().includes(currentUser.name.toLowerCase()))
                ));
                if (myAcc) custodySel.value = myAcc.id;
            }
        }
    } catch (e) {
        console.error('Error applying settlement permission defaults:', e);
    }
}

function wrapSettlementModalOpen() {
    if (window.openSettlementModal && !window.openSettlementModal._wrapped) {
        const orig = window.openSettlementModal;
        const wrapped = function(id = null) {
            const res = orig.apply(this, arguments);
            const cb = document.getElementById('show-closed-batches-cb');
            if (cb) cb.disabled = false;
            setTimeout(() => {
                if (typeof window.refreshSettlementBatchesList === 'function') {
                    window.refreshSettlementBatchesList(true);
                }
                if (!id) applySettlementPermissionsDefault();
            }, 150);
            setTimeout(() => {
                if (typeof window.refreshSettlementBatchesList === 'function') {
                    window.refreshSettlementBatchesList(true);
                }
                if (!id) applySettlementPermissionsDefault();
            }, 600);
            return res;
        };
        wrapped._wrapped = true;
        window.openSettlementModal = wrapped;
    }
    if (window.addSettlementRow && !window.addSettlementRow._permWrapped) {
        const origAddRow = window.addSettlementRow;
        const wrappedAddRow = function(lineData = null) {
            const res = origAddRow.apply(this, arguments);
            if (!lineData) {
                applySettlementPermissionsDefault();
                setTimeout(() => applySettlementPermissionsDefault(), 50);
            }
            return res;
        };
        wrappedAddRow._permWrapped = true;
        window.addSettlementRow = wrappedAddRow;
    }
}
wrapSettlementModalOpen();
document.addEventListener('DOMContentLoaded', wrapSettlementModalOpen);
window.addEventListener('load', wrapSettlementModalOpen);

// Observer for dynamic rows
(function() {
    const observer = new MutationObserver(function(mutations) {
        document.querySelectorAll('#settlement-items-tbody .set-batch').forEach(sel => {
            enrichBatchSelect(sel, false);
            const oldBadge = sel.parentElement ? sel.parentElement.querySelector('.batch-info-badge') : null;
            if (oldBadge) oldBadge.remove();
        });
    });
    
    const tryInitObserver = () => {
        const tbody = document.getElementById('settlement-items-tbody');
        if (tbody) {
            observer.observe(tbody, { childList: true, subtree: true });
            document.querySelectorAll('#settlement-items-tbody .set-batch').forEach(sel => {
                enrichBatchSelect(sel, false);
            });
        } else {
            setTimeout(tryInitObserver, 1000);
        }
    };
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', tryInitObserver);
    } else {
        tryInitObserver();
    }
})();

// ============ تصدير جدول التسوية ============


// Helper: read settlement table rows into array of objects
function _readSettlementRows() {
    const rows = [];
    document.querySelectorAll('#settlement-items-tbody tr').forEach(tr => {
        const getSelectText = (sel) => {
            if (!sel || sel.selectedIndex < 0) return '-';
            const text = sel.options[sel.selectedIndex].text;
            if (!sel.value || sel.value === '0' || text.startsWith('--')) return '-';
            return text;
        };
        const getVal = (el) => el ? (el.value || '') : '';

        const typeEl = tr.querySelector('.set-type');
        const itemEl = tr.querySelector('.set-item');
        const whEl = tr.querySelector('.set-warehouse');
        const projEl = tr.querySelector('.set-project');
        const batchEl = tr.querySelector('.set-batch');
        const stmtEl = tr.querySelector('.set-statement');
        const qtyEl = tr.querySelector('.set-qty');
        const priceEl = tr.querySelector('.set-price');

        const type = getSelectText(typeEl);
        const item = itemEl ? (itemEl.tagName === 'SELECT' ? getSelectText(itemEl) : getVal(itemEl)) : '';
        const warehouse = getSelectText(whEl);
        const costCenter = getSelectText(projEl);
        const batch = batchEl ? (batchEl.tagName === 'SELECT' ? getSelectText(batchEl) : getVal(batchEl)) : '';
        const statement = getVal(stmtEl);
        const qty = getVal(qtyEl);
        const price = getVal(priceEl);
        const total = (parseFloat(qty) || 0) * (parseFloat(price) || 0);

        rows.push({ type, item, warehouse, costCenter, batch, statement, qty, price, total: total.toFixed(2) });
    });
    return rows;
}

// Get settlement header info
function _getSettlementHeader() {
    const title = document.getElementById('settlement-modal-title')?.innerText || '';
    const dateEl = document.getElementById('settlement-date');
    const custodyEl = document.getElementById('settlement-custody');
    const date = dateEl ? dateEl.value : '';
    let custody = '';
    if (custodyEl && custodyEl.selectedIndex >= 0) {
        custody = custodyEl.options[custodyEl.selectedIndex].text;
    }
    const totalEl = document.getElementById('settlement-total-amount');
    const totalAmount = totalEl ? totalEl.innerText : '0';
    return { title, date, custody, totalAmount };
}

// Download as Excel-compatible file (HTML Table with .xls extension)
window.exportSettlementToFile = function() {
    var header = _getSettlementHeader();
    var rows = _readSettlementRows();

    if (rows.length === 0) {
        alert('لا توجد بنود في التسوية للتصدير');
        return;
    }

    var html = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>تسوية عهدة</x:Name><x:WorksheetOptions><x:DisplayRightToLeft/><x:DoNotDisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
<style>
  table { border-collapse: collapse; direction: rtl; font-family: 'Tahoma', Arial, sans-serif; width: 100%; }
  th { background-color: #2c3e50; color: #ffffff; border: 1px solid #000000; padding: 8px; font-weight: bold; text-align: center; }
  td { border: 1px solid #cccccc; padding: 6px; text-align: center; }
  .title { font-size: 16pt; font-weight: bold; text-align: center; background-color: #ecf0f1; border: none; padding: 10px; }
  .info { font-size: 12pt; font-weight: bold; background-color: #f8f9fa; border: 1px solid #dddddd; padding: 6px; }
  .total-row td { background-color: #e8f5e9; font-weight: bold; border: 1px solid #000000; color: #1e4620; font-size: 12pt; }
</style>
</head>
<body dir="rtl">
<table>
  <tr><td colspan="9" class="title">${header.title || 'تسوية عهدة'}</td></tr>
  <tr>
    <td colspan="3" class="info"><b>التاريخ:</b> ${header.date}</td>
    <td colspan="6" class="info"><b>حساب العهدة:</b> ${header.custody}</td>
  </tr>
  <tr><td colspan="9"></td></tr>
  <thead>
    <tr>
      <th>النوع</th>
      <th>الصنف / الحساب</th>
      <th>المخزن</th>
      <th>مركز التكلفة</th>
      <th>أمر الصب</th>
      <th>بيان التسوية</th>
      <th>الكمية</th>
      <th>السعر</th>
      <th>الإجمالي</th>
    </tr>
  </thead>
  <tbody>`;

    rows.forEach(function(r) {
        html += `
    <tr>
      <td>${r.type}</td>
      <td>${r.item}</td>
      <td>${r.warehouse}</td>
      <td>${r.costCenter}</td>
      <td>${r.batch}</td>
      <td>${r.statement}</td>
      <td>${r.qty}</td>
      <td>${r.price}</td>
      <td>${r.total}</td>
    </tr>`;
    });

    html += `
    <tr class="total-row">
      <td colspan="8" style="text-align: left; padding-left: 15px;">الإجمالي:</td>
      <td>${header.totalAmount} ج.م</td>
    </tr>
  </tbody>
</table>
</body>
</html>`;

    var blob = new Blob([html], { type: 'application/vnd.ms-excel;charset=utf-8' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    var sid = document.getElementById('settlement-modal')?.dataset?.editId || 'new';
    a.href = url;
    a.download = 'تسوية_عهدة_' + sid + '_' + new Date().toISOString().slice(0, 10) + '.xls';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// Copy table to clipboard as tab-separated text (pastes into Excel in columns)
window.copySettlementTable = function() {
    var header = _getSettlementHeader();
    var rows = _readSettlementRows();

    if (rows.length === 0) {
        alert('لا توجد بنود في التسوية للنسخ');
        return;
    }

    var TAB = '\t';
    var NL = '\n';

    var text = header.title + NL;
    text += 'التاريخ:' + TAB + header.date + NL;
    text += 'حساب العهدة:' + TAB + header.custody + NL;
    text += NL;

    var cols = ['م', 'النوع', 'الصنف/الحساب', 'المخزن', 'مركز التكلفة', 'أمر الصب', 'البيان', 'الكمية', 'السعر', 'الإجمالي'];
    text += cols.join(TAB) + NL;

    rows.forEach(function(r, i) {
        text += [i + 1, r.type, r.item, r.warehouse, r.costCenter, r.batch, r.statement, r.qty, r.price, r.total].join(TAB) + NL;
    });

    text += NL;
    text += TAB+TAB+TAB+TAB+TAB+TAB+TAB+TAB+TAB + 'الإجمالي: ' + header.totalAmount + ' ج.م' + NL;

    navigator.clipboard.writeText(text).then(function() {
        var btns = document.querySelectorAll('.settlement-export-btn');
        var btn = btns.length > 1 ? btns[1] : btns[0];
        if (btn) {
            var originalText = btn.innerText;
            btn.innerText = '✅ تم النسخ!';
            btn.style.backgroundColor = '#28a745';
            setTimeout(function() {
                btn.innerText = originalText;
                btn.style.backgroundColor = '#6f42c1';
            }, 2000);
        }
    }).catch(function() {
        var ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        alert('تم نسخ الجدول بنجاح!');
    });
}
