document.addEventListener("DOMContentLoaded", () => {
    // DOM Elements
    const gatherersContainer = document.getElementById("gatherers-list-container");
    const settlementModal = document.getElementById("settlement-modal");

    const btnCloseModal = document.getElementById("close-settlement-modal-btn");
    const btnCloseModalFooter = document.getElementById("close-settlement-modal-btn-footer");

    const btnFilterShift = document.getElementById("modal-btn-filter-shift");
    const btnFilterAll = document.getElementById("modal-btn-filter-all");

    const modalJallabName = document.getElementById("modal-jallab-name");
    const modalJallabPhone = document.getElementById("modal-jallab-phone");

    const tableCountBody = document.getElementById("table-count-body");
    const tableWeightBody = document.getElementById("table-weight-body");
    const grandTotalElement = document.getElementById("settlement-grand-total");

    // Theme toggle element
    const themeToggle = document.getElementById("theme-toggle");

    // Action Buttons
    const btnPrint = document.getElementById("print-settlement-btn");
    const btnExportExcel = document.getElementById("export-settlement-excel-btn");
    const btnOpenPayout = document.getElementById("open-pay-settlement-btn");

    // Payout Modal Elements
    const payoutModal = document.getElementById("payout-settlement-modal");
    const payoutForm = document.getElementById("payout-settlement-form");
    const payoutAmountEl = document.getElementById("payout-modal-amount");
    const payoutSafeSelect = document.getElementById("payout-safe-select");
    const payoutNotesInput = document.getElementById("payout-notes");

    // Search elements
    const jallabSearch = document.getElementById("jallab-search");
    const jallabCountBadge = document.getElementById("jallab-count-badge");

    // Custom Date Filter elements
    const filterStartDate = document.getElementById("filter-start-date");
    const filterEndDate = document.getElementById("filter-end-date");
    const btnApplyDateFilter = document.getElementById("btn-apply-date-filter");
    const btnClearDateFilter = document.getElementById("btn-clear-date-filter");

    let gatherersList = [];
    let selectedJallabId = null;
    let showAll = false; // default to shift-only
    let currentTable1 = [];
    let currentTable2 = [];
    let currentGrandTotal = 0;

    // Init Theme
    initTheme();

    // Load Gatherers List initially
    fetchGatherers();

    // Event Listeners for closing modal
    if (btnCloseModal) {
        btnCloseModal.addEventListener("click", closeModal);
    }
    if (btnCloseModalFooter) {
        btnCloseModalFooter.addEventListener("click", closeModal);
    }

    // Close when clicking overlay background
    if (settlementModal) {
        settlementModal.addEventListener("click", (e) => {
            if (e.target === settlementModal) {
                closeModal();
            }
        });
    }

    // Filter toggles
    if (btnFilterShift) {
        btnFilterShift.addEventListener("click", () => {
            if (filterStartDate) filterStartDate.value = "";
            if (filterEndDate) filterEndDate.value = "";
            if (btnClearDateFilter) btnClearDateFilter.style.display = "none";

            if (showAll || (filterStartDate && filterStartDate.value)) {
                showAll = false;
                btnFilterShift.classList.add("active");
                btnFilterAll.classList.remove("active");
                fetchSettlementData();
            }
        });
    }

    if (btnFilterAll) {
        btnFilterAll.addEventListener("click", () => {
            if (filterStartDate) filterStartDate.value = "";
            if (filterEndDate) filterEndDate.value = "";
            if (btnClearDateFilter) btnClearDateFilter.style.display = "none";

            if (!showAll || (filterStartDate && filterStartDate.value)) {
                showAll = true;
                btnFilterAll.classList.add("active");
                btnFilterShift.classList.remove("active");
                fetchSettlementData();
            }
        });
    }

    // Real-time Gatherer Search Input handler
    if (jallabSearch) {
        jallabSearch.addEventListener("input", () => {
            renderGatherersCards(jallabSearch.value.trim());
        });
    }

    // Custom Date Filter application handlers
    if (btnApplyDateFilter) {
        btnApplyDateFilter.addEventListener("click", () => {
            const start = filterStartDate ? filterStartDate.value : "";
            const end = filterEndDate ? filterEndDate.value : "";
            if (!start || !end) {
                showToast("يرجى اختيار تاريخ البدء وتاريخ النهاية أولاً", "warning");
                return;
            }
            if (start > end) {
                showToast("تاريخ البدء لا يمكن أن يكون بعد تاريخ النهاية", "warning");
                return;
            }

            if (btnFilterShift) btnFilterShift.classList.remove("active");
            if (btnFilterAll) btnFilterAll.classList.remove("active");

            if (btnClearDateFilter) btnClearDateFilter.style.display = "inline-block";

            fetchSettlementData();
        });
    }

    if (btnClearDateFilter) {
        btnClearDateFilter.addEventListener("click", () => {
            if (filterStartDate) filterStartDate.value = "";
            if (filterEndDate) filterEndDate.value = "";

            showAll = false;
            if (btnFilterShift) btnFilterShift.classList.add("active");
            if (btnFilterAll) btnFilterAll.classList.remove("active");

            btnClearDateFilter.style.display = "none";

            fetchSettlementData();
        });
    }

    // Export Excel Button
    if (btnExportExcel) {
        btnExportExcel.addEventListener("click", exportSettlementExcel);
    }

    // Open Pay Settlement Modal Button
    if (btnOpenPayout) {
        btnOpenPayout.addEventListener("click", openPayoutModal);
    }

    // Payout Form Submit
    if (payoutForm) {
        payoutForm.addEventListener("submit", handlePayoutSubmit);
    }

    // Print button click listener
    if (btnPrint) {
        btnPrint.addEventListener("click", () => {
            const jallab = gatherersList.find(g => g.id == selectedJallabId);
            const jallabName = jallab ? jallab.name : '—';
            const jallabPhone = jallab ? (jallab.phone || 'غير مسجل') : '—';

            const start = filterStartDate ? filterStartDate.value : "";
            const end = filterEndDate ? filterEndDate.value : "";
            let periodText = "الوردية الحالية";
            if (start && end) {
                periodText = `الفترة: من ${start} إلى ${end}`;
            } else if (showAll) {
                periodText = "كافة الأوقات";
            }

            let rowsCountHtml = currentTable1.map((item, idx) => `
                <tr>
                    <td>${idx + 1}</td>
                    <td>${escapeHTML(item.material_name)}</td>
                    <td>${(item.total_qty || 0).toLocaleString('ar-EG')}</td>
                    <td>${(item.avg_price || 0).toLocaleString('ar-EG')} د.ع</td>
                    <td>${(item.total_amount || 0).toLocaleString('ar-EG')} د.ع</td>
                </tr>
            `).join("");

            let rowsWeightHtml = currentTable2.map((item, idx) => `
                <tr>
                    <td>${idx + 1}</td>
                    <td>${escapeHTML(item.material_name)}</td>
                    <td>${(item.total_qty || 0).toLocaleString('ar-EG')}</td>
                    <td>${(item.total_weight || 0).toLocaleString('ar-EG')} كغم</td>
                    <td>${(item.avg_price || 0).toLocaleString('ar-EG')} د.ع</td>
                    <td>${(item.total_amount || 0).toLocaleString('ar-EG')} د.ع</td>
                </tr>
            `).join("");

            const orgName = getOrgName();
            const cur = getCurrency();
            const today = new Date().toLocaleDateString('ar-IQ', { year: 'numeric', month: 'long', day: 'numeric' });

            const printWin = window.open("", "_blank", "width=950,height=750");
            if (!printWin) {
                showToast("يرجى السماح بالنوافذ المنبثقة لطباعة كشف التسوية", "warning");
                return;
            }

            printWin.document.write(`<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>كشف تسوية مستحقات جلاب – ${escapeHTML(jallabName)}</title>
<style>
    @page { size: A4 portrait; margin: 12mm 10mm; }
    @media print {
        body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        .no-print { display: none !important; }
        thead { display: table-header-group; }
        tfoot { display: table-footer-group; }
        tr { page-break-inside: avoid; }
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
        font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
        font-size: 11.5px;
        color: #0f172a;
        background: #ffffff;
        direction: rtl;
        padding: 10px;
    }
    .report-card {
        border: 1.5px solid #cbd5e1;
        border-radius: 12px;
        padding: 20px 24px;
        max-width: 920px;
        margin: 0 auto;
    }
    .report-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #0f172a;
        padding-bottom: 14px;
        margin-bottom: 16px;
    }
    .brand-box {
        display: flex;
        align-items: center;
        gap: 12px;
    }
    .brand-icon {
        width: 48px; height: 48px;
        border-radius: 12px;
        background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
        color: #ffffff;
        font-size: 24px;
        display: flex; align-items: center; justify-content: center;
    }
    .brand-name {
        font-size: 20px;
        font-weight: 900;
        color: #0f172a;
        margin: 0 0 2px 0;
    }
    .brand-sub {
        font-size: 11px;
        color: #64748b;
        font-weight: 600;
    }
    .report-title-box {
        text-align: right;
    }
    .report-title {
        font-size: 18px;
        font-weight: 900;
        color: #4f46e5;
        margin-bottom: 4px;
    }
    .report-meta {
        font-size: 11px;
        color: #475569;
        line-height: 1.5;
    }

    .jallab-info-card {
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        padding: 12px 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }
    .jallab-name-val { font-size: 15px; font-weight: 900; color: #0f172a; }
    .jallab-phone-val { font-size: 12px; color: #475569; font-family: monospace; }

    table.report-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 16px;
        font-size: 11.5px;
    }
    table.report-table th {
        background: #0f172a;
        color: #ffffff;
        font-weight: 800;
        padding: 9px 10px;
        border: 1px solid #0f172a;
        text-align: center;
    }
    table.report-table td {
        padding: 8px 10px;
        border: 1px solid #cbd5e1;
        vertical-align: middle;
    }
    table.report-table tbody tr:nth-child(even) {
        background: #f8fafc;
    }
    
    .section-head {
        font-size: 13px;
        font-weight: 800;
        margin: 14px 0 8px 0;
        color: #1e293b;
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .amount-summary-card {
        background: linear-gradient(135deg, #059669 0%, #10b981 100%);
        color: #ffffff;
        border-radius: 10px;
        padding: 16px 22px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 16px;
        margin-bottom: 20px;
    }
    .summary-text { font-size: 14px; font-weight: 800; }
    .summary-num { font-size: 24px; font-weight: 900; direction: ltr; }

    .report-footer {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        border-top: 1.5px dashed #94a3b8;
        padding-top: 14px;
        margin-top: 16px;
    }
    .sig-block {
        text-align: center;
        width: 170px;
    }
    .sig-title { font-size: 11px; font-weight: 700; color: #475569; margin-bottom: 30px; }
    .sig-line { border-bottom: 1px solid #64748b; }
    .stamp-text { font-size: 10px; color: #94a3b8; text-align: center; }
</style>
</head>
<body>
<div class="report-card">
    <table style="width:100%; border-collapse:collapse; border:none;">
        <thead>
            <tr>
                <td style="border:none; padding:0; background:transparent; text-align:right; font-weight:normal;">
                    <div class="report-header">
                        <div class="brand-box">
                            <div class="brand-icon">📜</div>
                            <div>
                                <h1 class="brand-name">${escapeHTML(orgName)}</h1>
                                <div class="brand-sub">تقرير كشف تسوية ومستحقات الجلابين التفصيلي</div>
                            </div>
                        </div>
                        <div class="report-title-box">
                            <div class="report-title">كشف تسوية الجلاب</div>
                            <div class="report-meta">
                                <div>التاريخ: <strong>${today}</strong></div>
                                <div>النطاق: <strong>${escapeHTML(periodText)}</strong></div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="border:none; padding:0;">
                    <div class="jallab-info-card">
                        <div>
                            <div style="font-size:11px; color:#64748b; font-weight:700;">اسم الجلاب المستحق:</div>
                            <div class="jallab-name-val">${escapeHTML(jallabName)}</div>
                        </div>
                        <div style="text-align:left;">
                            <div style="font-size:11px; color:#64748b; font-weight:700;">رقم الهاتف:</div>
                            <div class="jallab-phone-val">${escapeHTML(jallabPhone)}</div>
                        </div>
                    </div>

                    ${currentTable1.length > 0 ? `
                        <div class="section-head">📦 1. المواد المحسوبة بالعدد (العدد × السعر):</div>
                        <table class="report-table">
                            <thead>
                                <tr>
                                    <th style="width:40px;">ت</th>
                                    <th>اسم المادة</th>
                                    <th style="width:110px;">العدد الكلي</th>
                                    <th style="width:130px;">معدل السعر</th>
                                    <th style="width:150px;">المبلغ الإجمالي</th>
                                </tr>
                            </thead>
                            <tbody>${rowsCountHtml}</tbody>
                        </table>
                    ` : ''}

                    ${currentTable2.length > 0 ? `
                        <div class="section-head">⚖️ 2. المواد المحسوبة بالوزن (الوزن × السعر):</div>
                        <table class="report-table">
                            <thead>
                                <tr>
                                    <th style="width:40px;">ت</th>
                                    <th>اسم المادة</th>
                                    <th style="width:110px;">العدد الكلي</th>
                                    <th style="width:110px;">الوزن الإجمالي</th>
                                    <th style="width:130px;">معدل السعر</th>
                                    <th style="width:150px;">المبلغ الإجمالي</th>
                                </tr>
                            </thead>
                            <tbody>${rowsWeightHtml}</tbody>
                        </table>
                    ` : ''}

                    <div class="amount-summary-card">
                        <div class="summary-text">إجمالي صافي مستحقات الجلاب الفعالة للتسوية:</div>
                        <div class="summary-num">${currentGrandTotal.toLocaleString('ar-IQ')} ${cur}</div>
                    </div>
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td style="border:none; padding:0;">
                    <div class="report-footer">
                        <div class="sig-block">
                            <div class="sig-title">اعتماد المحاسب / المسلّم</div>
                            <div class="sig-line"></div>
                        </div>
                        <div class="stamp-text">
                            تم استخراج التقرير إلكترونياً من نظام ${escapeHTML(orgName)}
                        </div>
                        <div class="sig-block">
                            <div class="sig-title">توقيع المستلم (${escapeHTML(jallabName)})</div>
                            <div class="sig-line"></div>
                        </div>
                    </div>
                </td>
            </tr>
        </tfoot>
    </table>
</div>
<script>
    window.onload = function() {
        setTimeout(function() { window.print(); }, 400);
    };
<\/script>
</body>
</html>`);
            printWin.document.close();
        });
    }

    // Theme Management Functions
    function initTheme() {
        const savedTheme = localStorage.getItem("dashboard_theme");
        if (savedTheme === "dark") {
            document.body.classList.add("dark-theme");
            if (themeToggle) {
                themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
            }
        } else {
            document.body.classList.remove("dark-theme");
            if (themeToggle) {
                themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
            }
        }
    }

    function toggleTheme() {
        if (document.body.classList.contains("dark-theme")) {
            document.body.classList.remove("dark-theme");
            if (themeToggle) {
                themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
            }
            localStorage.setItem("dashboard_theme", "light");
            showToast("تم تفعيل الوضع المضيء", "info");
        } else {
            document.body.classList.add("dark-theme");
            if (themeToggle) {
                themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
            }
            localStorage.setItem("dashboard_theme", "dark");
            showToast("تم تفعيل الوضع الداكن", "info");
        }
    }

    // Gatherers Functions
    function fetchGatherers() {
        if (gatherersContainer) {
            gatherersContainer.innerHTML = '<div style="grid-column: 1/-1; text-align:center; padding:40px; color:var(--text-secondary);">جاري تحميل الجلابين...</div>';
        }

        fetch("api/settlements.php?action=list_gatherers")
            .then(res => res.json())
            .then(data => {
                if (data.status === "success") {
                    gatherersList = data.gatherers;
                    if (jallabCountBadge) {
                        jallabCountBadge.textContent = gatherersList.length;
                    }
                    renderGatherersCards();
                } else {
                    showToast(data.message || "فشل تحميل قائمة الجلابين", "error");
                }
            })
            .catch(err => {
                console.error(err);
                showToast("حدث خطأ أثناء تحميل قائمة الجلابين", "error");
            });
    }

    function renderGatherersCards(filterName = "") {
        if (!gatherersContainer) return;

        const filtered = gatherersList.filter(g => {
            const nameMatch = g.name && g.name.toLowerCase().includes(filterName.toLowerCase());
            const phoneMatch = g.phone && g.phone.includes(filterName);
            return nameMatch || phoneMatch;
        });

        if (jallabCountBadge) {
            jallabCountBadge.textContent = filtered.length;
        }

        if (filtered.length === 0) {
            gatherersContainer.innerHTML = `
                <div class="no-data-placeholder" style="grid-column: 1/-1;">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <h3>لا توجد نتائج مطابقة للبحث</h3>
                    <p>تأكد من كتابة الاسم أو رقم الهاتف بشكل صحيح.</p>
                </div>
            `;
            return;
        }

        let html = "";
        filtered.forEach(g => {
            const firstLetter = g.name ? g.name.trim().charAt(0) : "ج";
            html += `
                <div class="gatherer-card" data-id="${g.id}">
                    <div class="gatherer-avatar">${escapeHTML(firstLetter)}</div>
                    <div class="gatherer-details">
                        <span class="gatherer-name">${escapeHTML(g.name)}</span>
                        <span class="gatherer-phone">${escapeHTML(g.phone || "بدون هاتف")}</span>
                    </div>
                </div>
            `;
        });
        gatherersContainer.innerHTML = html;

        // Add Click events to cards
        const cards = gatherersContainer.querySelectorAll(".gatherer-card");
        cards.forEach(card => {
            card.addEventListener("click", () => {
                const id = parseInt(card.getAttribute("data-id"));
                openSettlementModal(id);
            });
        });
    }

    function openSettlementModal(jallabId) {
        selectedJallabId = jallabId;
        const jallab = gatherersList.find(g => g.id == jallabId);
        if (!jallab) return;

        if (filterStartDate) filterStartDate.value = "";
        if (filterEndDate) filterEndDate.value = "";
        if (btnClearDateFilter) btnClearDateFilter.style.display = "none";

        showAll = false;
        if (btnFilterShift) btnFilterShift.classList.add("active");
        if (btnFilterAll) btnFilterAll.classList.remove("active");

        if (modalJallabName) modalJallabName.textContent = `تسوية الجلاب: ${jallab.name}`;
        if (modalJallabPhone) modalJallabPhone.textContent = `الهاتف: ${jallab.phone || "غير متوفر"}`;

        if (settlementModal) {
            settlementModal.classList.add("open");
        }

        fetchSettlementData();
    }

    function closeModal() {
        if (settlementModal) {
            settlementModal.classList.remove("open");
        }
        selectedJallabId = null;
    }

    function fetchSettlementData() {
        if (!selectedJallabId) return;

        tableCountBody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding:20px; color:var(--text-secondary);">جاري التحميل...</td></tr>';
        tableWeightBody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding:20px; color:var(--text-secondary);">جاري التحميل...</td></tr>';
        grandTotalElement.textContent = "0 د.ع";

        const startDate = filterStartDate ? filterStartDate.value : "";
        const endDate = filterEndDate ? filterEndDate.value : "";

        let url = `api/settlements.php?action=get_settlement&jallab_id=${selectedJallabId}`;
        if (startDate && endDate) {
            url += `&start_date=${startDate}&end_date=${endDate}`;
        } else {
            url += `&show_all=${showAll}`;
        }

        fetch(url)
            .then(res => res.json())
            .then(data => {
                if (data.status === "success") {
                    currentTable1 = data.table1 || [];
                    currentTable2 = data.table2 || [];
                    renderTables(data.table1, data.table2);
                } else {
                    showToast(data.message || "فشل جلب بيانات التسوية", "error");
                }
            })
            .catch(err => {
                console.error(err);
                showToast("حدث خطأ أثناء تحميل بيانات التسوية", "error");
            });
    }

    function renderTables(table1, table2) {
        let totalCountQty = 0;
        let totalCountAmount = 0;
        let totalWeightQty = 0;
        let totalWeightAmount = 0;

        if (table1.length === 0) {
            tableCountBody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding:20px; color:var(--text-secondary);">لا توجد مواد بالعدد لهذا الجلاب في هذه الفترة</td></tr>';
        } else {
            let html1 = "";
            table1.forEach((item, index) => {
                totalCountQty += parseFloat(item.total_qty || 0);
                totalCountAmount += parseFloat(item.total_amount || 0);
                html1 += `
                    <tr>
                        <td style="font-weight:700;">${index + 1}</td>
                        <td style="font-weight:700; color:var(--text-primary);">${escapeHTML(item.material_name)}</td>
                        <td style="font-weight:700; color:var(--primary);">${item.total_qty.toLocaleString('ar-EG')}</td>
                        <td style="font-weight:700;">${item.avg_price.toLocaleString('ar-EG')} د.ع</td>
                        <td style="font-weight:800; color:var(--success);">${item.total_amount.toLocaleString('ar-EG')} د.ع</td>
                    </tr>
                `;
            });
            tableCountBody.innerHTML = html1;
        }

        if (table2.length === 0) {
            tableWeightBody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding:20px; color:var(--text-secondary);">لا توجد مواد بالوزن لهذا الجلاب في هذه الفترة</td></tr>';
        } else {
            let html2 = "";
            table2.forEach((item, index) => {
                totalWeightQty += parseFloat(item.total_weight || 0);
                totalWeightAmount += parseFloat(item.total_amount || 0);
                html2 += `
                    <tr>
                        <td style="font-weight:700;">${index + 1}</td>
                        <td style="font-weight:700; color:var(--text-primary);">${escapeHTML(item.material_name)}</td>
                        <td style="font-weight:700; color:var(--primary);">${item.total_qty.toLocaleString('ar-EG')}</td>
                        <td style="font-weight:700; color:var(--warning);">${item.total_weight.toLocaleString('ar-EG')} كجم</td>
                        <td style="font-weight:700;">${item.avg_price.toLocaleString('ar-EG')} د.ع</td>
                        <td style="font-weight:800; color:var(--success);">${item.total_amount.toLocaleString('ar-EG')} د.ع</td>
                    </tr>
                `;
            });
            tableWeightBody.innerHTML = html2;
        }

        currentGrandTotal = totalCountAmount + totalWeightAmount;
        grandTotalElement.textContent = `${currentGrandTotal.toLocaleString('ar-EG')} د.ع`;

        const elCountQty = document.getElementById("stat-count-qty");
        const elCountAmount = document.getElementById("stat-count-amount");
        const elWeightQty = document.getElementById("stat-weight-qty");
        const elWeightAmount = document.getElementById("stat-weight-amount");
        const elVarietyCount = document.getElementById("stat-materials-count");
        const elVarietySplit = document.getElementById("stat-materials-split");
        const elStatGrandTotal = document.getElementById("stat-grand-total");

        const elBadgeCountTable = document.getElementById("badge-count-table");
        const elBadgeWeightTable = document.getElementById("badge-weight-table");

        if (elCountQty) elCountQty.textContent = `${totalCountQty.toLocaleString('ar-EG')} قطعة`;
        if (elCountAmount) elCountAmount.textContent = `${totalCountAmount.toLocaleString('ar-EG')} د.ع`;
        if (elWeightQty) elWeightQty.textContent = `${totalWeightQty.toLocaleString('ar-EG')} كجم`;
        if (elWeightAmount) elWeightAmount.textContent = `${totalWeightAmount.toLocaleString('ar-EG')} د.ع`;
        if (elVarietyCount) elVarietyCount.textContent = `${(table1.length + table2.length)} مادة`;
        if (elVarietySplit) elVarietySplit.textContent = `${table1.length} عدد | ${table2.length} وزن`;
        if (elStatGrandTotal) elStatGrandTotal.textContent = `${currentGrandTotal.toLocaleString('ar-EG')} د.ع`;

        if (elBadgeCountTable) elBadgeCountTable.textContent = `${table1.length} مواد`;
        if (elBadgeWeightTable) elBadgeWeightTable.textContent = `${table2.length} مواد`;
    }

    // Export Excel Function
    function exportSettlementExcel() {
        if (!selectedJallabId || (currentTable1.length === 0 && currentTable2.length === 0)) {
            showToast("لا توجد بيانات تسوية لتصديرها", "warning");
            return;
        }

        const jallab = gatherersList.find(g => g.id == selectedJallabId);
        const jallabName = jallab ? jallab.name : 'جلاب';

        let csv = "\uFEFF";
        csv += `كشف تسوية الجلاب: ${jallabName}\n`;
        csv += `تاريخ التصدير: ${new Date().toISOString().slice(0, 10)}\n\n`;

        if (currentTable1.length > 0) {
            csv += "المواد المحسوبة بالعدد (العدد * السعر)\n";
            csv += "التسلسل,اسم المادة,العدد الكلي,معدل السعر,المبلغ الإجمالي\n";
            currentTable1.forEach((it, idx) => {
                csv += `${idx + 1},"${(it.material_name || '').replace(/"/g, '""')}",${it.total_qty},${it.avg_price},${it.total_amount}\n`;
            });
            csv += "\n";
        }

        if (currentTable2.length > 0) {
            csv += "المواد المحسوبة بالوزن (الوزن * السعر)\n";
            csv += "التسلسل,اسم المادة,العدد الكلي,الوزن الإجمالي,معدل السعر,المبلغ الإجمالي\n";
            currentTable2.forEach((it, idx) => {
                csv += `${idx + 1},"${(it.material_name || '').replace(/"/g, '""')}",${it.total_qty},${it.total_weight},${it.avg_price},${it.total_amount}\n`;
            });
            csv += "\n";
        }

        csv += `إجمالي المستحقات,,,,,${currentGrandTotal}\n`;

        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.setAttribute("href", url);
        link.setAttribute("download", `تسوية_${jallabName.replace(/\s+/g, '_')}_${new Date().toISOString().slice(0, 10)}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        showToast("تم تصدير ملف التسوية بنجاح", "success");
    }

    // Payout Modal Functions
    function openPayoutModal() {
        if (!selectedJallabId || currentGrandTotal <= 0) {
            showToast("لا توجد مستحقات مالية متاحة للصرف لهذا الجلاب!", "warning");
            return;
        }

        if (payoutAmountEl) {
            payoutAmountEl.textContent = `${currentGrandTotal.toLocaleString('ar-EG')} د.ع`;
        }

        if (payoutSafeSelect) {
            payoutSafeSelect.innerHTML = '<option value="">جاري تحميل القاصات...</option>';
            fetch('api/settlements.php?action=list_safes')
                .then(r => r.json())
                .then(res => {
                    if (res.status === 'success' && res.safes) {
                        payoutSafeSelect.innerHTML = res.safes.map(s => `
                            <option value="${s.id}">${escapeHTML(s.name)}</option>
                        `).join('');
                    } else {
                        payoutSafeSelect.innerHTML = '<option value="">فشل جلب القاصات</option>';
                    }
                })
                .catch(() => {
                    payoutSafeSelect.innerHTML = '<option value="">خطأ في الشبكة</option>';
                });
        }

        if (payoutModal) payoutModal.classList.add("open");
    }

    window.closePayoutModal = function () {
        if (payoutModal) payoutModal.classList.remove("open");
    };

    function handlePayoutSubmit(e) {
        e.preventDefault();
        const safeId = payoutSafeSelect ? payoutSafeSelect.value : '';
        const notes = payoutNotesInput ? payoutNotesInput.value.trim() : '';

        if (!safeId) {
            showToast("يرجى اختيار القاصة أو الصندوق للتسديد", "warning");
            return;
        }

        const confirmBtn = document.getElementById("confirm-payout-btn");
        if (confirmBtn) confirmBtn.disabled = true;

        fetch('api/settlements.php?action=pay_settlement', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                jallab_id: selectedJallabId,
                safe_id: safeId,
                amount: currentGrandTotal,
                notes: notes
            })
        })
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    showToast(res.message);
                    window.closePayoutModal();
                    closeModal();
                    fetchGatherers();
                } else {
                    showToast(res.message || "فشل صرف التسوية", "danger");
                }
            })
            .catch(err => {
                console.error(err);
                showToast("حدث خطأ في السيرفر أثناء تسديد التسوية", "danger");
            })
            .finally(() => {
                if (confirmBtn) confirmBtn.disabled = false;
            });
    }

    // Helper functions
    function escapeHTML(str) {
        if (!str) return '';
        return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    }

    function showToast(message, type = "success") {
        const container = document.getElementById("toast-container");
        if (!container) return;

        const toast = document.createElement("div");
        toast.className = `toast toast-${type}`;

        let icon = '<i class="fa-solid fa-circle-check"></i>';
        if (type === "danger" || type === "error") {
            icon = '<i class="fa-solid fa-circle-xmark"></i>';
        } else if (type === "warning") {
            icon = '<i class="fa-solid fa-circle-exclamation"></i>';
        } else if (type === "info") {
            icon = '<i class="fa-solid fa-circle-info"></i>';
        }

        toast.innerHTML = `
            ${icon}
            <div class="toast-content">
                <p>${message}</p>
            </div>
        `;
        container.appendChild(toast);

        setTimeout(() => {
            toast.classList.add("show");
        }, 10);

        setTimeout(() => {
            toast.classList.remove("show");
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }
});

function getOrgName() {
    let settings = {};
    const localSettings = localStorage.getItem("dashboard_settings") || localStorage.getItem("system_settings");
    if (localSettings) {
        try { settings = JSON.parse(localSettings); } catch (e) { }
    }
    return settings.orgName || settings.org_name || settings.companyName || "مكتب الحاج أمجد سهل عبدالامير";
}

function getCurrency() {
    return "د.ع";
}

function formatNum(n) {
    if (n === null || n === undefined || isNaN(n)) return "0";
    return Number(n).toLocaleString('ar-IQ');
}
