// materials_report.js — كشف حركة وإيرادات المواد والمستودع المطور

let state = {
    materials: [],
    filtered: [],
    activeMaterial: null,
    viewMode: 'current', // 'current', 'previous'
    modalTab: 'grouped',  // 'grouped', 'detailed'
    summary: {}
};

const dom = {
    statTotalMaterials: document.getElementById('stat-total-materials'),
    statTotalQty: document.getElementById('stat-total-qty'),
    statTotalWeight: document.getElementById('stat-total-weight'),
    statTotalRevenue: document.getElementById('stat-total-revenue'),

    grid: document.getElementById('materials-cards-container') || document.getElementById('materials-grid'),
    emptyState: document.getElementById('empty-state-view') || document.getElementById('empty-state'),

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

    // Modal
    modal: document.getElementById('details-modal') || document.getElementById('material-modal'),
    modalName: document.getElementById('modal-material-name'),
    modalStatCount: document.getElementById('modal-stat-count'),
    modalStatQty: document.getElementById('modal-stat-qty'),
    modalStatWeight: document.getElementById('modal-stat-weight'),
    modalStatRevenue: document.getElementById('modal-stat-revenue'),
    modalTbody: document.getElementById('modal-details-tbody') || document.getElementById('modal-tbody'),
    modalTable: document.getElementById('modal-details-table') || document.getElementById('modal-table'),
    modalEmpty: document.getElementById('modal-empty-state-view') || 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));
}

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

    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, #059669 0%, #10b981 100%)";
            btnCurrent.style.color = "#fff";
            btnCurrent.style.border = "none";
            btnCurrent.style.boxShadow = "0 2px 8px rgba(16, 185, 129, 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, #059669 0%, #10b981 100%)";
            btnPrevious.style.color = "#fff";
            btnPrevious.style.border = "none";
            btnPrevious.style.boxShadow = "0 2px 8px rgba(16, 185, 129, 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) {
        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/materials_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');
                    if (dom.grid) dom.grid.innerHTML = '';
                    if (dom.emptyState) dom.emptyState.style.display = 'block';
                }
                return;
            }
            const reportJson = JSON.stringify(data);
            if (reportJson === lastReportJson && isSilent) {
                return;
            }
            lastReportJson = reportJson;

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

            if (state.activeMaterial) {
                const updatedM = state.materials.find(m => m.name === state.activeMaterial.name);
                if (updatedM) {
                    state.activeMaterial = updatedM;
                    dom.modalStatCount.textContent = updatedM.transactions ? updatedM.transactions.length : 0;
                    dom.modalStatQty.textContent = updatedM.total_qty.toLocaleString('en-US');
                    dom.modalStatWeight.textContent = formatNum(updatedM.total_weight) + ' كجم';
                    dom.modalStatRevenue.textContent = `${formatCurrency(updatedM.total_revenue)} ${getCurrency()}`;
                    applyModalSearch();
                }
            }
        })
        .catch(err => {
            console.error(err);
            if (!isSilent) showToast('خطأ في الاتصال بالخادم', 'danger');
        });
}

function updateSummary(s) {
    if (dom.statTotalMaterials) dom.statTotalMaterials.textContent = s.total_materials || 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);
}

function applySearch() {
    const query = (dom.searchInput ? dom.searchInput.value : '').trim().toLowerCase();
    if (!query) {
        state.filtered = [...state.materials];
        if (dom.searchClearBtn) dom.searchClearBtn.style.display = 'none';
    } else {
        state.filtered = state.materials.filter(m => m.name.toLowerCase().includes(query));
        if (dom.searchClearBtn) dom.searchClearBtn.style.display = 'block';
    }
    renderCards();
}

function renderCards() {
    if (!dom.grid) return;
    if (!state.filtered || state.filtered.length === 0) {
        dom.grid.innerHTML = '';
        if (dom.emptyState) dom.emptyState.style.display = 'block';
        return;
    }
    if (dom.emptyState) dom.emptyState.style.display = 'none';

    dom.grid.innerHTML = state.filtered.map((m, idx) => {
        const cur = getCurrency();
        const txCount = m.transactions ? m.transactions.length : 0;
        const initial = m.name ? m.name.charAt(0) : '📦';

        return `
        <div class="material-card" onclick="openMaterialModal('${escapeHTML(m.name)}')">
            <div class="material-card-header">
                <div class="material-avatar-wrap">
                    <div class="material-avatar">${initial}</div>
                    <div>
                        <div class="material-title">${escapeHTML(m.name)}</div>
                        <div style="font-size:11px; color:var(--text-secondary);">${m.accounting_type || 'غير محدد'}</div>
                    </div>
                </div>
                <div class="material-serial-badge">${txCount} حركة</div>
            </div>
            <div class="material-card-body">
                <div style="display:flex; justify-content:space-between; font-size:12px;">
                    <span style="color:var(--text-secondary);">إجمالي الأعداد:</span>
                    <strong style="color:var(--text-primary);">${m.total_qty.toLocaleString('en-US')} قطعة</strong>
                </div>
                <div style="display:flex; justify-content:space-between; font-size:12px;">
                    <span style="color:var(--text-secondary);">إجمالي الوزن:</span>
                    <strong style="color:#d97706;">${formatNum(m.total_weight)} كجم</strong>
                </div>
                <div style="display:flex; justify-content:space-between; font-size:12.5px; border-top:1px dashed var(--border-color); padding-top:8px; margin-top:2px;">
                    <span style="color:var(--text-secondary); font-weight:700;">إجمالي الإيراد:</span>
                    <strong style="color:#059669; font-weight:800; font-size:14px;">${formatCurrency(m.total_revenue)} ${cur}</strong>
                </div>
            </div>
        </div>`;
    }).join('');
}

window.openMaterialModal = function (materialName) {
    const mat = state.materials.find(m => m.name === materialName);
    if (!mat) return;
    state.activeMaterial = mat;

    dom.modalName.textContent = mat.name;
    dom.modalStatCount.textContent = mat.transactions ? mat.transactions.length : 0;
    dom.modalStatQty.textContent = mat.total_qty.toLocaleString('en-US');
    dom.modalStatWeight.textContent = formatNum(mat.total_weight) + ' كجم';
    dom.modalStatRevenue.textContent = `${formatCurrency(mat.total_revenue)} ${getCurrency()}`;

    if (dom.modalSearchInput) dom.modalSearchInput.value = '';
    state.modalTab = 'grouped';

    renderModalTable();
    dom.modal.classList.add('open');
};

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

window.setModalTab = function (tab) {
    state.modalTab = tab;
    const btnG = document.getElementById('tab-btn-grouped');
    const btnD = document.getElementById('tab-btn-detailed');

    if (btnG && btnD) {
        if (tab === 'grouped') {
            btnG.style.background = 'var(--primary)';
            btnG.style.color = '#fff';
            btnD.style.background = 'transparent';
            btnD.style.color = 'var(--text-secondary)';
        } else {
            btnD.style.background = 'var(--primary)';
            btnD.style.color = '#fff';
            btnG.style.background = 'transparent';
            btnG.style.color = 'var(--text-secondary)';
        }
    }
    renderModalTable();
};

function renderModalTable() {
    if (!state.activeMaterial || !state.activeMaterial.transactions) {
        dom.modalTbody.innerHTML = '';
        dom.modalEmpty.style.display = 'block';
        return;
    }

    const query = (dom.modalSearchInput ? dom.modalSearchInput.value : '').trim().toLowerCase();
    let list = state.activeMaterial.transactions;

    if (query) {
        list = list.filter(t => (t.customer_name || '').toLowerCase().includes(query) || String(t.form_id).includes(query));
    }

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

    const cur = getCurrency();
    dom.modalTbody.innerHTML = list.map((t, idx) => {
        const isCash = (t.form_status === '1');
        const statusBadge = isCash
            ? `<span style="background:rgba(16,185,129,0.12); color:#10b981; border:1px solid rgba(16,185,129,0.3); padding:3px 10px; border-radius:12px; font-weight:700; font-size:11px; display:inline-flex; align-items:center; gap:4px;"><i class="fa-solid fa-circle-check"></i> نقداً</span>`
            : `<span style="background:rgba(245,158,11,0.12); color:#d97706; border:1px solid rgba(245,158,11,0.3); padding:3px 10px; border-radius:12px; font-weight:700; font-size:11px; display:inline-flex; align-items:center; gap:4px;"><i class="fa-solid fa-clock"></i> دين / آجل</span>`;

        return `
        <tr>
            <td style="font-weight:700; color:var(--text-secondary);">${idx + 1}</td>
            <td><strong style="color:var(--primary); font-size:13.5px;">#${t.form_id}</strong></td>
            <td><strong style="color:var(--text-primary);">${escapeHTML(t.customer_name || 'زبون عام')}</strong></td>
            <td><span style="font-weight:700;">${t.quantity}</span> قطعة</td>
            <td>${t.weight !== null && t.weight !== undefined && parseFloat(t.weight) > 0 ? formatNum(t.weight) + ' كجم' : '---'}</td>
            <td>${formatCurrency(t.price)} ${cur}</td>
            <td><strong style="color:#059669; font-size:13.5px;">${formatCurrency(t.subtotal)} ${cur}</strong></td>
            <td>${statusBadge}</td>
            <td style="font-size:11.5px; color:var(--text-secondary);"><i class="fa-regular fa-calendar" style="margin-left:3px;"></i>${t.form_date ? t.form_date.substring(0, 16).replace('T', ' ') : '---'}</td>
        </tr>`;
    }).join('');
}

function applyModalSearch() {
    renderModalTable();
}

function setupEventListeners() {
    if (dom.searchInput) {
        dom.searchInput.addEventListener('input', applySearch);
    }
    if (dom.searchClearBtn) {
        dom.searchClearBtn.addEventListener('click', () => {
            dom.searchInput.value = '';
            applySearch();
        });
    }
    if (dom.refreshBtn) {
        dom.refreshBtn.addEventListener('click', () => loadReport());
    }
    if (dom.closeModalBtn) dom.closeModalBtn.addEventListener('click', closeModal);
    if (dom.closeModalFooter) dom.closeModalFooter.addEventListener('click', closeModal);

    if (dom.modalSearchInput) {
        dom.modalSearchInput.addEventListener('input', applyModalSearch);
    }
}

function initTheme() {
    const theme = localStorage.getItem('theme') || 'light';
    document.documentElement.setAttribute('data-theme', theme);
}

// Global helpers
function formatNum(num) {
    if (num === null || num === undefined || isNaN(num)) return '0';
    return Number(num).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
}

function formatCurrency(amount) {
    if (amount === null || amount === undefined || isNaN(amount)) return '0';
    return Number(amount).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
}

function getCurrency() {
    const settings = localStorage.getItem("dashboard_settings") || localStorage.getItem("system_settings");
    if (settings) {
        try { return JSON.parse(settings).currency || "د.ع"; } catch (e) { }
    }
    return "د.ع";
}

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

function showToast(message, type = 'success') {
    if (!dom.toastContainer) return;
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `<i class="fa-solid fa-circle-check"></i> <span>${message}</span>`;
    dom.toastContainer.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

// -------------------------------------------------------------
// Print Executive Report (Multi-page Header Repeating)
// -------------------------------------------------------------
window.printMaterialsReport = function () {
    const materials = state.filtered && state.filtered.length > 0 ? state.filtered : state.materials;
    if (!materials || materials.length === 0) {
        showToast("لا توجد بيانات مواد لطباعة التقرير", "warning");
        return;
    }

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

    const cur = getCurrency();
    const orgName = getOrgName();
    const today = new Date().toLocaleDateString('ar-IQ', { year: 'numeric', month: 'long', day: 'numeric' });
    const modeText = state.viewMode === 'current' ? 'الوردية الحالية' : 'كافة الفترات';

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

    let rowsHtml = materials.map((m, idx) => {
        const qty = m.total_qty || 0;
        const weight = m.total_weight || 0;
        const rev = m.total_revenue || 0;
        const txCount = m.transactions ? m.transactions.length : 0;

        totalQtySum += qty;
        totalWeightSum += weight;
        totalRevSum += rev;

        return `
        <tr>
            <td style="text-align:center;">${idx + 1}</td>
            <td style="font-weight:800; color:#0f172a;">${escapeHTML(m.name)}</td>
            <td style="text-align:center;">${escapeHTML(m.accounting_type || '---')}</td>
            <td style="text-align:center;">${txCount} حركة</td>
            <td style="text-align:center; font-weight:700;">${qty.toLocaleString('ar-IQ')}</td>
            <td style="text-align:center; font-weight:700; color:#d97706;">${weight.toLocaleString('ar-IQ')} كجم</td>
            <td style="text-align:center; font-weight:800; color:#059669; direction:ltr;">${rev.toLocaleString('ar-IQ')} ${cur}</td>
        </tr>`;
    }).join('');

    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, #059669 0%, #10b981 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: #059669;
        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.green { color: #059669; }
    .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">${materials.length} مادة</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">إجمالي القطع / الأعداد</div>
                            <div class="kpi-val">${totalQtySum.toLocaleString('ar-IQ')} قطعة</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 green">${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="4" style="text-align:right;">الإجمالي الكلي لجميع المواد:</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:#6ee7b7; 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();
};
