// gatherers_report.js — كشف الجلابين المطور بالكامل

// -------------------------------------------------------
// State
// -------------------------------------------------------
let state = {
    gatherers: [],
    filtered: [],
    activeGatherer: null,
    viewMode: 'current', // 'current', 'previous', 'date_range'
    modalTab: 'grouped',  // 'grouped', 'detailed'
    summary: {}
};

// -------------------------------------------------------
// DOM
// -------------------------------------------------------
const dom = {
    statTotalGatherers: document.getElementById('stat-total-gatherers'),
    statTotalQty: document.getElementById('stat-total-qty'),
    statTotalWeight: document.getElementById('stat-total-weight'),
    statTotalRevenue: document.getElementById('stat-total-revenue'),

    grid: document.getElementById('gatherers-grid'),
    emptyState: document.getElementById('empty-state'),

    searchInput: document.getElementById('search-input'),
    searchClearBtn: document.getElementById('search-clear-btn'),
    refreshBtn: document.getElementById('refresh-btn'),

    // Modal
    modal: document.getElementById('gatherer-modal'),
    modalName: document.getElementById('modal-gatherer-name'),
    modalStatCustomers: document.getElementById('modal-stat-customers'),
    modalStatQty: document.getElementById('modal-stat-qty'),
    modalStatWeight: document.getElementById('modal-stat-weight'),
    modalStatRevenue: document.getElementById('modal-stat-revenue'),
    modalTbody: document.getElementById('modal-tbody'),
    modalTable: document.getElementById('modal-table'),
    modalEmpty: document.getElementById('modal-empty'),
    modalSearchInput: document.getElementById('modal-search-input'),
    closeModalBtn: document.getElementById('close-modal-btn'),
    closeModalFooter: document.getElementById('close-modal-footer-btn'),

    themeToggle: document.getElementById('theme-toggle'),
    toastContainer: document.getElementById('toast-container')
};

let lastStates = {};
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                let hasChanges = false;
                targetTables.forEach(t => {
                    const newTs = res.states[t] || 0;
                    if (lastStates[t] !== undefined && lastStates[t] !== newTs) {
                        hasChanges = true;
                    }
                    lastStates[t] = newTs;
                });
                if (hasChanges) {
                    refreshCallback();
                }
            }
        })
        .catch(err => console.error("Error checking states:", err));
}

// -------------------------------------------------------
// Init
// -------------------------------------------------------
document.addEventListener('DOMContentLoaded', () => {
    initTheme();
    setupEventListeners();



    // Populate initial states
    fetch('api/check_state.php')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => { });

    loadReport();
    setInterval(() => {
        checkSystemStateAndRefresh(['forms'], () => loadReport(true));
    }, 3000);
});

window.setViewMode = function (mode) {
    state.viewMode = mode;

    const btnCurrent = document.getElementById("btn-view-current");
    const btnPrevious = document.getElementById("btn-view-previous");
    const wTitle = document.getElementById("welcome-title");
    const wDesc = document.getElementById("welcome-desc");
    const cSubtitle = document.getElementById("card-subtitle");

    if (btnCurrent && btnPrevious) {
        if (mode === 'current') {
            btnCurrent.style.background = "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)";
            btnCurrent.style.color = "#fff";
            btnCurrent.style.border = "none";
            btnCurrent.style.boxShadow = "0 2px 8px rgba(99, 102, 241, 0.2)";

            btnPrevious.style.background = "var(--bg-input)";
            btnPrevious.style.color = "var(--text-secondary)";
            btnPrevious.style.border = "1.5px solid var(--border-color)";
            btnPrevious.style.boxShadow = "none";

            if (wTitle) wTitle.innerHTML = 'كشف الجلابين — الوردية الحالية 🚛';
            if (wDesc) wDesc.innerHTML = 'عرض الجلابين الذين تم تسجيل مواد لهم في الوردية الحالية مع إجمالي مبيعاتهم.';
            if (cSubtitle) cSubtitle.innerHTML = 'الجلابون الذين سُجِّلت لهم مواد في هذه الوردية';
        } else {
            btnPrevious.style.background = "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)";
            btnPrevious.style.color = "#fff";
            btnPrevious.style.border = "none";
            btnPrevious.style.boxShadow = "0 2px 8px rgba(99, 102, 241, 0.2)";

            btnCurrent.style.background = "var(--bg-input)";
            btnCurrent.style.color = "var(--text-secondary)";
            btnCurrent.style.border = "1.5px solid var(--border-color)";
            btnCurrent.style.boxShadow = "none";

            if (wTitle) wTitle.innerHTML = 'كشف الجلابين — كافة الفترات 🚛';
            if (wDesc) wDesc.innerHTML = 'عرض كافة كشوفات ومبيعات الجلابين المسجلين لجميع الفترات والورديات.';
            if (cSubtitle) cSubtitle.innerHTML = 'كافة مبيعات الجلابين عبر جميع الفترات';
        }
    }

    loadReport();
};

let lastReportJson = "";
function loadReport(isSilent = false) {
    if (!isSilent) {
        dom.grid.innerHTML = `
            <div style="grid-column:1/-1; text-align:center; padding:60px 20px; color:var(--text-secondary);">
                <i class="fa-solid fa-spinner fa-spin" style="font-size:28px; display:block; margin-bottom:12px;"></i>
                <p>جاري تحميل بيانات كشف الجلابين...</p>
            </div>`;
    }

    let url = `api/gatherers_report.php?action=shift_report&mode=${state.viewMode}`;
    if (state.viewMode === 'previous') {
        url += `&show_all=true`;
    }

    fetch(url)
        .then(r => r.json())
        .then(data => {
            if (data.status !== 'success') {
                if (!isSilent) {
                    showToast('فشل تحميل البيانات', 'danger');
                    dom.grid.innerHTML = '';
                    dom.emptyState.style.display = 'block';
                }
                return;
            }
            const reportJson = JSON.stringify(data);
            if (reportJson === lastReportJson && isSilent) {
                return; // Nothing changed, skip rendering
            }
            lastReportJson = reportJson;

            state.gatherers = data.gatherers || [];
            state.summary = data.summary || {};
            applySearch();
            updateSummary(data.summary || {});

            // If details modal is open, silently update its contents as well
            if (state.activeGatherer) {
                const updatedG = state.gatherers.find(g => g.id === state.activeGatherer.id || g.name === state.activeGatherer.name);
                if (updatedG) {
                    state.activeGatherer = updatedG;
                    dom.modalStatCustomers.textContent = updatedG.customer_count;
                    dom.modalStatQty.textContent = updatedG.total_qty.toLocaleString('en-US');
                    dom.modalStatWeight.textContent = formatNum(updatedG.total_weight) + ' كجم';
                    dom.modalStatRevenue.textContent = `${formatCurrency(updatedG.total_revenue)} ${getCurrency()}`;
                    applyModalSearch();
                }
            }
        })
        .catch(err => {
            console.error(err);
            if (!isSilent) showToast('خطأ في الاتصال بالخادم', 'danger');
        });
}

// -------------------------------------------------------
// Summary
// -------------------------------------------------------
function updateSummary(s) {
    if (dom.statTotalGatherers) dom.statTotalGatherers.textContent = s.total_gatherers || 0;
    if (dom.statTotalQty) dom.statTotalQty.textContent = (s.grand_qty || 0).toLocaleString('en-US');
    if (dom.statTotalWeight) dom.statTotalWeight.textContent = formatNum(s.grand_weight || 0);
    if (dom.statTotalRevenue) dom.statTotalRevenue.textContent = `${formatCurrency(s.grand_revenue || 0)} ${getCurrency()}`;
}

// -------------------------------------------------------
// Render Cards (Enhanced Visual KPIs)
// -------------------------------------------------------
function renderCards() {
    dom.grid.innerHTML = '';
    const list = state.filtered;

    if (list.length === 0) {
        dom.emptyState.style.display = 'block';
        return;
    }
    dom.emptyState.style.display = 'none';

    list.forEach(g => {
        const card = document.createElement('div');
        card.className = 'gatherer-card';
        card.onclick = () => openModal(g);

        const initials = g.name ? g.name.substring(0, 2) : 'ج';
        const percentage = g.revenue_percentage || 0;
        const avgUnitPrice = g.avg_unit_price || 0;

        card.innerHTML = `
            <div class="gatherer-header">
                <div class="gatherer-avatar">${escapeHTML(initials)}</div>
                <div style="flex:1;">
                    <div style="display:flex; align-items:center; justify-content:space-between; gap:6px;">
                        <div class="gatherer-name">${escapeHTML(g.name)}</div>
                        <span style="background:rgba(99, 102, 241, 0.12); color:var(--primary); padding:2px 8px; border-radius:12px; font-size:11px; font-weight:800;">
                            ${percentage}% من الإجمالي
                        </span>
                    </div>
                    <span class="gatherer-phone">${escapeHTML(g.phone || '—')}</span>
                </div>
            </div>

            <!-- Revenue Progress Bar -->
            <div style="background:var(--bg-input); height:6px; border-radius:3px; overflow:hidden; margin:-4px 0 2px 0;">
                <div style="background:linear-gradient(90deg, #6366f1, #10b981); height:100%; width:${Math.min(percentage, 100)}%; transition:width 0.4s ease;"></div>
            </div>

            <div class="gatherer-stats">
                <div class="g-stat">
                    <span class="g-stat-label"><i class="fa-solid fa-users" style="margin-left:4px;"></i>الزبائن</span>
                    <span class="g-stat-value">${g.customer_count}</span>
                </div>
                <div class="g-stat">
                    <span class="g-stat-label"><i class="fa-solid fa-hashtag" style="margin-left:4px;"></i>العدد</span>
                    <span class="g-stat-value" style="color:#3b82f6;">${g.total_qty.toLocaleString('en-US')}</span>
                </div>
                <div class="g-stat">
                    <span class="g-stat-label"><i class="fa-solid fa-weight-hanging" style="margin-left:4px;"></i>الوزن</span>
                    <span class="g-stat-value" style="color:#f59e0b;">${formatNum(g.total_weight)}</span>
                </div>
                <div class="g-stat">
                    <span class="g-stat-label"><i class="fa-solid fa-sack-dollar" style="margin-left:4px;"></i>الإيرادات</span>
                    <span class="g-stat-value" style="color:#10b981;">${formatCurrency(g.total_revenue)}</span>
                </div>
            </div>

            <div class="gatherer-footer">
                <span style="font-size:11px; color:var(--text-secondary);">متوسط القطعة: <strong>${formatCurrency(avgUnitPrice)} ${getCurrency()}</strong></span>
                <span style="font-size:11px; color:var(--primary); font-weight:700;">التفاصيل <i class="fa-solid fa-chevron-left"></i></span>
            </div>
        `;
        dom.grid.appendChild(card);
    });
}

// -------------------------------------------------------
// Modal (Grouped vs Detailed View Tabs)
// -------------------------------------------------------
function openModal(g) {
    state.activeGatherer = g;

    dom.modalName.textContent = g.name;
    dom.modalStatCustomers.textContent = g.customer_count;
    dom.modalStatQty.textContent = g.total_qty.toLocaleString('en-US');
    dom.modalStatWeight.textContent = formatNum(g.total_weight) + ' كجم';
    dom.modalStatRevenue.textContent = `${formatCurrency(g.total_revenue)} ${getCurrency()}`;

    if (dom.modalSearchInput) dom.modalSearchInput.value = '';
    setModalTab('grouped');
    dom.modal.classList.add('open');
}

window.setModalTab = function (tab) {
    state.modalTab = tab;
    const btnGrouped = document.getElementById("modal-tab-grouped");
    const btnDetailed = document.getElementById("modal-tab-detailed");

    if (tab === 'grouped') {
        if (btnGrouped) {
            btnGrouped.style.background = "var(--primary)";
            btnGrouped.style.color = "#fff";
            btnGrouped.style.border = "none";
        }
        if (btnDetailed) {
            btnDetailed.style.background = "var(--bg-input)";
            btnDetailed.style.color = "var(--text-secondary)";
            btnDetailed.style.border = "1px solid var(--border-color)";
        }
    } else {
        if (btnDetailed) {
            btnDetailed.style.background = "var(--primary)";
            btnDetailed.style.color = "#fff";
            btnDetailed.style.border = "none";
        }
        if (btnGrouped) {
            btnGrouped.style.background = "var(--bg-input)";
            btnGrouped.style.color = "var(--text-secondary)";
            btnGrouped.style.border = "1px solid var(--border-color)";
        }
    }
    applyModalSearch();
};

function renderModalTable(rows) {
    const thead = document.getElementById("modal-thead");
    dom.modalTbody.innerHTML = '';

    if (!rows || rows.length === 0) {
        dom.modalTable.style.display = 'none';
        dom.modalEmpty.style.display = 'block';
        return;
    }

    dom.modalTable.style.display = '';
    dom.modalEmpty.style.display = 'none';

    if (state.modalTab === 'grouped') {
        // Grouped View (by Material)
        if (thead) {
            thead.innerHTML = `
                <tr>
                    <th>اسم المادة</th>
                    <th>إجمالي العدد</th>
                    <th>إجمالي الوزن (كجم)</th>
                    <th>إجمالي المبيعات الصافية</th>
                </tr>`;
        }

        const byMaterial = {};
        rows.forEach(r => {
            const key = r.material_name;
            if (!byMaterial[key]) {
                byMaterial[key] = {
                    name: key,
                    total_qty: 0,
                    total_weight: 0,
                    total_revenue: 0,
                    accounting_type: r.accounting_type || ''
                };
            }
            byMaterial[key].total_qty += r.quantity;
            byMaterial[key].total_weight += (r.weight ?? 0);
            byMaterial[key].total_revenue += (r.subtotal !== undefined ? r.subtotal : r.total);
        });

        Object.values(byMaterial).forEach(m => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td style="font-weight:700;">${escapeHTML(m.name)}</td>
                <td>${m.total_qty.toLocaleString('en-US')}</td>
                <td>${m.total_weight > 0 ? formatNum(m.total_weight) : '—'}</td>
                <td style="font-weight:700; color:var(--success);">
                    ${formatCurrency(m.total_revenue)} ${getCurrency()}
                </td>
            `;
            dom.modalTbody.appendChild(tr);
        });

    } else {
        // Detailed View (by Form / Customer / Item)
        if (thead) {
            thead.innerHTML = `
                <tr>
                    <th>رقم الاستمارة</th>
                    <th>اسم الزبون</th>
                    <th>اسم المادة</th>
                    <th>العدد</th>
                    <th>الوزن (كجم)</th>
                    <th>السعر المفرد</th>
                    <th>الإجمالي الصافي</th>
                    <th>التاريخ</th>
                </tr>`;
        }

        rows.forEach(r => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td style="font-weight:700; color:var(--primary);">#${r.form_id}</td>
                <td style="font-weight:600;">${escapeHTML(r.customer_name)}</td>
                <td>${escapeHTML(r.material_name)}</td>
                <td>${r.quantity.toLocaleString('en-US')}</td>
                <td>${r.weight ? formatNum(r.weight) : '—'}</td>
                <td>${formatCurrency(r.price)} ${getCurrency()}</td>
                <td style="font-weight:700; color:var(--success);">${formatCurrency(r.subtotal)} ${getCurrency()}</td>
                <td style="font-size:11px; color:var(--text-secondary);">${escapeHTML(r.form_date || '')}</td>
            `;
            dom.modalTbody.appendChild(tr);
        });
    }
}

function closeModal() {
    dom.modal.classList.remove('open');
    state.activeGatherer = null;
}

// -------------------------------------------------------
// Search & Filter
// -------------------------------------------------------
function applySearch() {
    const term = (dom.searchInput?.value || '').trim().toLowerCase();
    if (!term) {
        state.filtered = [...state.gatherers];
    } else {
        state.filtered = state.gatherers.filter(g =>
            g.name.toLowerCase().includes(term)
        );
    }
    renderCards();
}

function applyModalSearch() {
    if (!state.activeGatherer) return;
    const term = (dom.modalSearchInput?.value || '').trim().toLowerCase();
    if (!term) {
        renderModalTable(state.activeGatherer.items);
        return;
    }
    const filtered = state.activeGatherer.items.filter(r =>
        (r.material_name && r.material_name.toLowerCase().includes(term)) ||
        (r.customer_name && r.customer_name.toLowerCase().includes(term)) ||
        (r.form_id && String(r.form_id).includes(term))
    );
    renderModalTable(filtered);
}

// -------------------------------------------------------
// Excel Export & Print Features
// -------------------------------------------------------
window.exportGatherersToExcel = function () {
    if (!state.gatherers || state.gatherers.length === 0) {
        showToast("لا توجد بيانات للتصدير", "warning");
        return;
    }

    let csvContent = "\uFEFF"; // UTF-8 BOM
    csvContent += "ت,اسم الجلاب,رقم الهاتف,عدد الزبائن,إجمالي العدد,إجمالي الوزن (كجم),إجمالي الإيرادات (د.ع),نسبة المشاركة (%)\n";

    state.gatherers.forEach((g, idx) => {
        csvContent += `"${idx + 1}","${g.name || ''}","${g.phone || ''}","${g.customer_count}","${g.total_qty}","${g.total_weight}","${g.total_revenue}","${g.revenue_percentage}%"\n`;
    });

    csvContent += "\n\n";
    csvContent += "تفاصيل مبيعات الجلابين حسب الفواتير والزبائن:\n";
    csvContent += "اسم الجلاب,رقم الاستمارة,اسم الزبون,اسم المادة,العدد,الوزن,السعر,الإجمالي,التاريخ\n";

    state.gatherers.forEach(g => {
        (g.items || []).forEach(item => {
            csvContent += `"${g.name}","#${item.form_id}","${item.customer_name}","${item.material_name}","${item.quantity}","${item.weight || 0}","${item.price}","${item.subtotal}","${item.form_date}"\n`;
        });
    });

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

window.printGatherersReport = function () {
    const gatherers = state.gatherers || [];
    if (gatherers.length === 0) {
        showToast("لا توجد بيانات بتقرير الجلابين للطباعة", "warning");
        return;
    }

    const orgName = getOrgName();
    const cur = getCurrency();
    const today = new Date().toLocaleDateString('ar-IQ', { year: 'numeric', month: 'long', day: 'numeric' });
    const modeText = state.viewMode === 'current' ? 'الوردية الحالية' : (state.filterStartDate ? `الفترة من ${state.filterStartDate} إلى ${state.filterEndDate || 'الآن'}` : 'كافة الأوقات');

    let totalCustSum = 0;
    let totalQtySum = 0;
    let totalWeightSum = 0;
    let totalRevSum = 0;

    let rowsHtml = gatherers.map((g, idx) => {
        const c = parseInt(g.customer_count || 0);
        const q = parseFloat(g.total_qty || 0);
        const w = parseFloat(g.total_weight || 0);
        const r = parseFloat(g.total_revenue || 0);
        totalCustSum += c;
        totalQtySum += q;
        totalWeightSum += w;
        totalRevSum += r;

        return `
            <tr>
                <td style="text-align:center; font-weight:700; color:#64748b;">${idx + 1}</td>
                <td><strong style="color:#0f172a; font-size:12.5px;">${escapeHTML(g.name || '')}</strong></td>
                <td style="text-align:center; direction:ltr; font-family:monospace; color:#475569;">${escapeHTML(g.phone || 'غير مسجل')}</td>
                <td style="text-align:center; font-weight:700;">${c} زبائن</td>
                <td style="text-align:center; font-weight:800; color:#1e293b;">${q.toLocaleString('ar-IQ')}</td>
                <td style="text-align:center; font-weight:800; color:#d97706;">${w > 0 ? w.toLocaleString('ar-IQ') + ' كجم' : '—'}</td>
                <td style="text-align:center; font-weight:900; color:#4f46e5; direction:ltr;">${r.toLocaleString('ar-IQ')} ${cur}</td>
            </tr>
        `;
    }).join("");

    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(orgName)}</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;
    }

    .kpi-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
        margin-bottom: 16px;
    }
    .kpi-box {
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        padding: 10px 14px;
        text-align: center;
    }
    .kpi-label { font-size: 10.5px; color: #64748b; font-weight: 700; margin-bottom: 4px; }
    .kpi-val { font-size: 15px; font-weight: 900; color: #0f172a; }
    .kpi-val.indigo { color: #4f46e5; }
    .kpi-val.amber { color: #d97706; }

    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;
    }
    table.report-table tfoot tr {
        background: #0f172a;
        color: #ffffff;
        font-weight: 900;
    }
    table.report-table tfoot td {
        padding: 10px;
        border: 1px solid #0f172a;
        font-size: 12px;
    }

    .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(modeText)}</strong></div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="border:none; padding:0;">
                    <div class="kpi-grid">
                        <div class="kpi-box">
                            <div class="kpi-label">عدد الجلابين بالتقرير</div>
                            <div class="kpi-val">${gatherers.length} جلاب</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">إجمالي عدد الزبائن المسجلين</div>
                            <div class="kpi-val">${totalCustSum} زبون</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">إجمالي الأوزان</div>
                            <div class="kpi-val amber">${totalWeightSum.toLocaleString('ar-IQ')} كجم</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">إجمالي المستحقات المجمعة</div>
                            <div class="kpi-val indigo">${totalRevSum.toLocaleString('ar-IQ')} ${cur}</div>
                        </div>
                    </div>

                    <table class="report-table">
                        <thead>
                            <tr>
                                <th style="width:40px;">ت</th>
                                <th>اسم الجلاب</th>
                                <th style="width:110px;">رقم الهاتف</th>
                                <th style="width:90px;">عدد الزبائن</th>
                                <th style="width:110px;">إجمالي العدد</th>
                                <th style="width:110px;">إجمالي الوزن</th>
                                <th style="width:140px;">إجمالي المستحقات</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${rowsHtml}
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="3" style="text-align:right;">الإجمالي الكلي المستحق للجلابين:</td>
                                <td style="text-align:center;">${totalCustSum} زبون</td>
                                <td style="text-align:center;">${totalQtySum.toLocaleString('ar-IQ')}</td>
                                <td style="text-align:center; color:#fde68a;">${totalWeightSum.toLocaleString('ar-IQ')} كجم</td>
                                <td style="text-align:center; color:#a5b4fc; direction:ltr;">${totalRevSum.toLocaleString('ar-IQ')} ${cur}</td>
                            </tr>
                        </tfoot>
                    </table>
                </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">توقيع المستلم / الجلاب</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();
};

// -------------------------------------------------------
// Event Listeners
// -------------------------------------------------------
function setupEventListeners() {
    dom.searchInput?.addEventListener('input', applySearch);
    dom.searchClearBtn?.addEventListener('click', () => {
        if (dom.searchInput) dom.searchInput.value = '';
        applySearch();
    });
    dom.refreshBtn?.addEventListener('click', () => loadReport(false));
    dom.closeModalBtn?.addEventListener('click', closeModal);
    dom.closeModalFooter?.addEventListener('click', closeModal);
    dom.modal?.addEventListener('click', e => { if (e.target === dom.modal) closeModal(); });
    dom.modalSearchInput?.addEventListener('input', applyModalSearch);
    dom.themeToggle?.addEventListener('click', toggleTheme);
    document.getElementById('btn-logout')?.addEventListener('click', () => {
        localStorage.removeItem('auth_token');
        window.location.href = 'login.php';
    });
}

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

function toggleTheme() {
    const dark = document.body.classList.toggle('dark-theme');
    if (dom.themeToggle) dom.themeToggle.innerHTML = dark
        ? '<i class="fa-solid fa-sun"></i>'
        : '<i class="fa-solid fa-moon"></i>';
    localStorage.setItem('dashboard_theme', dark ? 'dark' : 'light');
}

// -------------------------------------------------------
// Toast
// -------------------------------------------------------
function showToast(message, type = 'success') {
    const icons = { success: 'fa-circle-check', danger: 'fa-circle-xmark', warning: 'fa-circle-exclamation', info: 'fa-circle-info' };
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<i class="fa-solid ${icons[type] || icons.success} toast-icon"></i><span class="toast-message">${message}</span>`;
    dom.toastContainer?.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

// -------------------------------------------------------
// Helpers
// -------------------------------------------------------
function getCurrency() {
    try { return JSON.parse(localStorage.getItem('dashboard_settings') || '{}').currency || 'د.ع'; }
    catch { return 'د.ع'; }
}

function formatCurrency(val) {
    return parseFloat(val || 0).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

function formatNum(val) {
    return parseFloat(val || 0).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
}

function escapeHTML(str) {
    if (!str) return '';
    return String(str).replace(/[&<>'"]/g, t => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[t] || t));
}

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 || "مكتب الحاج أمجد سهل عبدالامير";
}
