// Business Logic and UI Interactions for Gatherer (الجلابين) Management Page

// App State
let state = {
    gatherers: [],
    filteredGatherers: [],
    currentPage: 1,
    entriesPerPage: 10,
    searchTerm: "",
    deleteTargetId: null
};

// -------------------------------------------------------------
// DOM Elements Selection
// -------------------------------------------------------------
const dom = {
    tbody: document.getElementById("gatherers-tbody"),
    emptyState: document.getElementById("empty-state-view"),
    table: document.getElementById("gatherers-table"),
    
    // Search & Filters
    searchInput: document.getElementById("search-input"),
    searchBtn: document.getElementById("search-btn"),
    searchClearBtn: document.getElementById("search-clear-btn"),
    searchResultsBadge: document.getElementById("search-results-badge"),
    entriesSelect: document.getElementById("entries-count"),
    
    // Pagination
    paginationInfo: document.getElementById("pagination-info-text"),
    paginationControls: document.getElementById("pagination-controls"),
    
    // Modals
    gathererModal: document.getElementById("gatherer-modal"),
    deleteConfirmModal: document.getElementById("delete-confirm-modal"),
    
    // Form
    gathererForm: document.getElementById("gatherer-form"),
    gathererIdInput: document.getElementById("gatherer-id"),
    gathererNameInput: document.getElementById("gatherer-name"),
    gathererPhoneInput: document.getElementById("gatherer-phone"),
    gathererNotesInput: document.getElementById("gatherer-notes"),
    modalTitle: document.getElementById("modal-title"),
    
    // Validation Errors
    nameError: document.getElementById("name-error"),
    
    // Buttons
    openAddModalBtn: document.getElementById("open-add-modal-btn"),
    emptyStateAddBtn: document.getElementById("empty-state-add-btn"),
    closeModalBtn: document.getElementById("close-modal-btn"),
    cancelModalBtn: document.getElementById("cancel-modal-btn"),
    cancelDeleteBtn: document.getElementById("cancel-delete-btn"),
    confirmDeleteBtn: document.getElementById("confirm-delete-btn"),
    deleteItemName: document.getElementById("delete-item-name"),
    
    // Theme Toggle
    themeToggle: document.getElementById("theme-toggle"),
    
    // Notifications Container
    toastContainer: document.getElementById("toast-container")
};

let lastStates = {};
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php?_t=' + Date.now())
        .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));
}

// -------------------------------------------------------------
// App Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    loadData();
    initTheme();
    setupEventListeners();
    applyFilters();

    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => {});

    setInterval(() => {
        checkSystemStateAndRefresh(['gatherers'], loadData);
    }, 3000);
});

// Load data from MySQL database
function loadData() {
    fetch('api/gatherers.php?action=list')
        .then(response => response.json())
        .then(res => {
            if (res.status === 'success') {
                state.gatherers = res.data || [];
                updateSummaryCards();
                applyFilters();
            } else {
                showToast(res.message || "حدث خطأ أثناء تحميل البيانات", "danger");
            }
        })
        .catch(err => {
            console.error(err);
            showToast("فشل الاتصال بقاعدة البيانات", "danger");
        });
}

function updateSummaryCards() {
    const totalGatherers = state.gatherers.length;
    const activeGatherers = state.gatherers.filter(g => (g.materialsCount || 0) > 0).length;
    const totalMaterials = state.gatherers.reduce((acc, g) => acc + (g.materialsCount || 0), 0);

    const elTotal = document.getElementById("stat-total-gatherers");
    const elActive = document.getElementById("stat-active-gatherers");
    const elMat = document.getElementById("stat-total-materials");

    if (elTotal) elTotal.textContent = totalGatherers;
    if (elActive) elActive.textContent = activeGatherers;
    if (elMat) elMat.textContent = totalMaterials;
}

// -------------------------------------------------------------
// Dark/Light Theme Management
// -------------------------------------------------------------
function initTheme() {
    const savedTheme = localStorage.getItem("dashboard_theme");
    if (savedTheme === "dark") {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
    } else {
        document.body.classList.remove("dark-theme");
        if (dom.themeToggle) dom.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 (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
        localStorage.setItem("dashboard_theme", "light");
        showToast("تم تفعيل الوضع المضيء", "info");
    } else {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
        localStorage.setItem("dashboard_theme", "dark");
        showToast("تم تفعيل الوضع الداكن", "info");
    }
}

// -------------------------------------------------------------
// Toast Notification System
// -------------------------------------------------------------
function showToast(message, type = "success") {
    const toast = document.createElement("div");
    toast.className = `toast toast-${type}`;
    
    let iconClass = "fa-circle-check";
    if (type === "danger") iconClass = "fa-circle-xmark";
    if (type === "warning") iconClass = "fa-circle-exclamation";
    if (type === "info") iconClass = "fa-circle-info";
    
    toast.innerHTML = `
        <i class="fa-solid ${iconClass} toast-icon"></i>
        <span class="toast-message">${message}</span>
    `;
    
    if (dom.toastContainer) dom.toastContainer.appendChild(toast);
    setTimeout(() => { toast.remove(); }, 3000);
}

// -------------------------------------------------------------
// Search, Filtering and Pagination Logic
// -------------------------------------------------------------
function applyFilters() {
    state.searchTerm = (dom.searchInput?.value || '').trim().toLowerCase();

    if (state.searchTerm === "") {
        state.filteredGatherers = [...state.gatherers];
        if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
    } else {
        state.filteredGatherers = state.gatherers.filter(g => {
            return (g.name && g.name.toLowerCase().includes(state.searchTerm)) ||
                   (g.phone && g.phone.toLowerCase().includes(state.searchTerm)) ||
                   (g.notes && g.notes.toLowerCase().includes(state.searchTerm));
        });
        if (dom.searchResultsBadge) {
            dom.searchResultsBadge.style.display = "inline-block";
            dom.searchResultsBadge.textContent = `تم إيجاد ${state.filteredGatherers.length} نتيجة`;
        }
    }

    state.entriesPerPage = parseInt(dom.entriesSelect?.value || 10);

    const totalPages = Math.ceil(state.filteredGatherers.length / state.entriesPerPage);
    if (state.currentPage > totalPages) {
        state.currentPage = totalPages || 1;
    }

    renderTable();
}

window.doSearch = function() {
    state.currentPage = 1;
    applyFilters();
    if (dom.searchInput) dom.searchInput.focus();
};

window.clearSearch = function() {
    if (dom.searchInput) dom.searchInput.value = "";
    if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
    state.currentPage = 1;
    applyFilters();
};

// -------------------------------------------------------------
// Dynamic DOM Rendering
// -------------------------------------------------------------
function renderTable() {
    dom.tbody.innerHTML = "";
    const list = state.filteredGatherers;
    const total = list.length;

    if (total === 0) {
        dom.table.style.display = "none";
        dom.emptyState.style.display = "flex";
        if (dom.paginationInfo) dom.paginationInfo.textContent = "يعرض 0 إلى 0 من أصل 0 جلاب";
        if (dom.paginationControls) dom.paginationControls.innerHTML = "";
        return;
    }

    dom.table.style.display = "table";
    dom.emptyState.style.display = "none";

    const startIndex = (state.currentPage - 1) * state.entriesPerPage;
    const endIndex = Math.min(startIndex + state.entriesPerPage, total);
    const paginatedList = list.slice(startIndex, endIndex);

    paginatedList.forEach((gatherer, index) => {
        const serial = startIndex + index + 1;
        const formattedDate = formatDateTime(gatherer.createdAt);
        const phoneText = gatherer.phone ? escapeHTML(gatherer.phone) : '—';
        const matBadge = (gatherer.materialsCount || 0) > 0 
            ? `<span style="background:rgba(99,102,241,0.12); color:var(--primary); padding:3px 10px; border-radius:12px; font-weight:800; font-size:12px;"><i class="fa-solid fa-boxes-stacked" style="margin-left:4px;"></i>${gatherer.materialsCount} مادة</span>`
            : `<span style="color:var(--text-muted); font-size:12px;">بدون مواد</span>`;
        
        const tr = document.createElement("tr");
        tr.innerHTML = `
            <td class="serial-col">#${serial}</td>
            <td class="name-col" title="${escapeHTML(gatherer.name)}" style="font-weight:700;">${escapeHTML(gatherer.name)}</td>
            <td dir="ltr" style="text-align:right;">${phoneText}</td>
            <td>${matBadge}</td>
            <td class="date-col" style="direction: rtl; text-align: right; font-size: 12px; color: var(--text-secondary);">${escapeHTML(formattedDate)}</td>
            <td>
                <div class="actions-cell">
                    <button class="btn-icon" onclick="openGathererMaterials('${gatherer.id}')" title="كشف المواد والتوريدات" style="color:var(--success);">
                        <i class="fa-solid fa-boxes-stacked"></i>
                    </button>
                    <button class="btn-icon btn-icon-edit" onclick="openEditModal('${gatherer.id}')" title="تعديل">
                        <i class="fa-solid fa-pen-to-square"></i>
                    </button>
                    <button class="btn-icon btn-icon-delete" onclick="openDeleteModal('${gatherer.id}')" title="حذف">
                        <i class="fa-solid fa-trash-can"></i>
                    </button>
                </div>
            </td>
        `;
        dom.tbody.appendChild(tr);
    });

    if (dom.paginationInfo) {
        dom.paginationInfo.textContent = `يعرض ${startIndex + 1} إلى ${endIndex} من أصل ${total} جلاب`;
    }
    renderPagination(total);
}

function renderPagination(totalItems) {
    if (!dom.paginationControls) return;
    dom.paginationControls.innerHTML = "";
    const totalPages = Math.ceil(totalItems / state.entriesPerPage);
    if (totalPages <= 1) return;

    const prevBtn = document.createElement("button");
    prevBtn.className = "page-btn";
    prevBtn.innerHTML = '<i class="fa-solid fa-chevron-right"></i>';
    prevBtn.disabled = state.currentPage === 1;
    prevBtn.addEventListener("click", () => {
        if (state.currentPage > 1) {
            state.currentPage--;
            renderTable();
        }
    });
    dom.paginationControls.appendChild(prevBtn);

    for (let i = 1; i <= totalPages; i++) {
        const pageBtn = document.createElement("button");
        pageBtn.className = `page-btn ${state.currentPage === i ? "active" : ""}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener("click", () => {
            state.currentPage = i;
            renderTable();
        });
        dom.paginationControls.appendChild(pageBtn);
    }

    const nextBtn = document.createElement("button");
    nextBtn.className = "page-btn";
    nextBtn.innerHTML = '<i class="fa-solid fa-chevron-left"></i>';
    nextBtn.disabled = state.currentPage === totalPages;
    nextBtn.addEventListener("click", () => {
        if (state.currentPage < totalPages) {
            state.currentPage++;
            renderTable();
        }
    });
    dom.paginationControls.appendChild(nextBtn);
}

// -------------------------------------------------------------
// Modals Open / Close Control
// -------------------------------------------------------------
window.openEditModal = function(id) {
    const gatherer = state.gatherers.find(g => g.id === id);
    if (!gatherer) return;

    clearValidationErrors();
    dom.modalTitle.textContent = "تعديل بيانات الجلاب";
    dom.gathererIdInput.value = gatherer.id;
    dom.gathererNameInput.value = gatherer.name || "";
    if (dom.gathererPhoneInput) dom.gathererPhoneInput.value = gatherer.phone || "";
    if (dom.gathererNotesInput) dom.gathererNotesInput.value = gatherer.notes || "";
    
    dom.gathererModal.classList.add("open");
};

function openAddModal() {
    clearValidationErrors();
    dom.modalTitle.textContent = "إضافة جلاب جديد";
    dom.gathererForm.reset();
    dom.gathererIdInput.value = "";
    
    dom.gathererModal.classList.add("open");
}

function closeModal() {
    dom.gathererModal.classList.remove("open");
    dom.gathererForm.reset();
    clearValidationErrors();
}

window.openDeleteModal = function(id) {
    const gatherer = state.gatherers.find(g => g.id === id);
    if (!gatherer) return;

    state.deleteTargetId = id;
    dom.deleteItemName.textContent = gatherer.name;
    dom.deleteConfirmModal.classList.add("open");
};

function closeDeleteModal() {
    dom.deleteConfirmModal.classList.remove("open");
    state.deleteTargetId = null;
}

// -------------------------------------------------------------
// Form Validation & Submission
// -------------------------------------------------------------
function clearValidationErrors() {
    document.querySelectorAll(".form-group").forEach(el => {
        el.classList.remove("has-error");
    });
}

function validateForm(name) {
    let isValid = true;
    clearValidationErrors();

    if (!name || name.trim().length < 3) {
        document.getElementById("gatherer-name")?.closest(".form-group")?.classList.add("has-error");
        isValid = false;
    }

    return isValid;
}

function handleFormSubmit(e) {
    e.preventDefault();
    
    const id = dom.gathererIdInput.value;
    const name = dom.gathererNameInput.value.trim();
    const phone = dom.gathererPhoneInput ? dom.gathererPhoneInput.value.trim() : "";
    const notes = dom.gathererNotesInput ? dom.gathererNotesInput.value.trim() : "";

    if (!validateForm(name)) {
        return;
    }

    fetch('api/gatherers.php?action=save', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id, name, phone, notes })
    })
    .then(response => response.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message);
            closeModal();
            loadData();
        } else {
            showToast(res.message, "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم لحفظ البيانات", "danger");
    });
}

// -------------------------------------------------------------
// Delete Execution
// -------------------------------------------------------------
function handleDeleteConfirm() {
    if (!state.deleteTargetId) return;

    const id = state.deleteTargetId;
    
    fetch('api/gatherers.php?action=delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id })
    })
    .then(response => response.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message, "success");
            closeDeleteModal();
            loadData();
        } else {
            showToast(res.message, "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم لحذف البيانات", "danger");
    });
}

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

function formatDateTime(isoString) {
    if (!isoString) return "-";
    try {
        const date = new Date(isoString);
        if (isNaN(date.getTime())) return isoString;
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        let hours = date.getHours();
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const ampm = hours >= 12 ? 'م' : 'ص';
        hours = hours % 12;
        hours = hours ? hours : 12;
        return `${y}/${m}/${d} ${hours}:${minutes} ${ampm}`;
    } catch (e) {
        return isoString;
    }
}

// -------------------------------------------------------------
// Event Listeners Setup
// -------------------------------------------------------------
function setupEventListeners() {
    if (dom.openAddModalBtn) dom.openAddModalBtn.addEventListener("click", openAddModal);
    if (dom.emptyStateAddBtn) dom.emptyStateAddBtn.addEventListener("click", openAddModal);

    if (dom.closeModalBtn) dom.closeModalBtn.addEventListener("click", closeModal);
    if (dom.cancelModalBtn) dom.cancelModalBtn.addEventListener("click", closeModal);
    if (dom.cancelDeleteBtn) dom.cancelDeleteBtn.addEventListener("click", closeDeleteModal);

    if (dom.confirmDeleteBtn) dom.confirmDeleteBtn.addEventListener("click", handleDeleteConfirm);

    if (dom.gathererForm) dom.gathererForm.addEventListener("submit", handleFormSubmit);

    if (dom.searchInput) {
        dom.searchInput.addEventListener("input", () => {
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.searchBtn) {
        dom.searchBtn.addEventListener("click", () => {
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.searchClearBtn) {
        dom.searchClearBtn.addEventListener("click", () => {
            if (dom.searchInput) dom.searchInput.value = "";
            if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.entriesSelect) {
        dom.entriesSelect.addEventListener("change", () => {
            state.currentPage = 1;
            applyFilters();
        });
    }

    if (dom.themeToggle) dom.themeToggle.addEventListener("click", toggleTheme);

    window.addEventListener("click", (e) => {
        if (e.target === dom.gathererModal) closeModal();
        if (e.target === dom.deleteConfirmModal) closeDeleteModal();
    });

    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeModal();
            closeDeleteModal();
        }
    });
}

// -------------------------------------------------------------
// Export and Print Functions
// -------------------------------------------------------------
window.printTable = function() {
    const list = state.filteredGatherers;
    if (list.length === 0) {
        showToast("لا توجد بيانات جلابين لطباعتها", "warning");
        return;
    }

    let rowsHtml = list.map((g, idx) => {
        return `
            <tr>
                <td>${idx + 1}</td>
                <td>${escapeHTML(g.name)}</td>
                <td>${g.phone || '—'}</td>
                <td>${g.materialsCount || 0} مادة</td>
                <td>${g.notes || '—'}</td>
                <td>${formatDateTime(g.createdAt)}</td>
            </tr>
        `;
    }).join("");

    const printWin = window.open("", "_blank");
    printWin.document.write(`
        <html lang="ar" dir="rtl">
        <head>
            <title>تقرير قائمة الجلابين المسجلين</title>
            <link href="css/cairo.css" rel="stylesheet">
            <style>
                body { font-family: 'Cairo', sans-serif; padding: 20px; text-align: right; }
                table { width: 100%; border-collapse: collapse; margin-top: 15px; }
                th, td { border: 1px solid #ccc; padding: 8px 12px; text-align: right; font-size: 13px; }
                th { background: #f3f4f6; font-weight: 700; }
                .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px; }
            </style>
        </head>
        <body>
            <div class="header">
                <h1 style="font-size:18px; margin:0 0 6px 0; color:#1e293b; text-align:center;">${getOrgName()}</h1>
                <h2>تقرير كشف الجلابين والموردين المسجلين</h2>
                <p>تاريخ الطباعة: ${new Date().toLocaleDateString('ar-EG')} - إجمالي الجلابين: ${list.length}</p>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>التسلسل</th>
                        <th>اسم الجلاب</th>
                        <th>رقم الهاتف</th>
                        <th>المواد المرتبطة</th>
                        <th>ملاحظات</th>
                        <th>تاريخ التسجيل</th>
                    </tr>
                </thead>
                <tbody>
                    ${rowsHtml}
                </tbody>
            </table>
        </body>
        </html>
    `);
    printWin.document.close();
    printWin.focus();
    setTimeout(() => { printWin.print(); }, 500);
};

window.exportPDF = function() {
    window.printTable();
};

window.exportExcel = function() {
    if (state.gatherers.length === 0) {
        showToast("لا توجد بيانات لتصديرها", "warning");
        return;
    }
    
    let csvContent = "\uFEFF";
    csvContent += "التسلسل,اسم الجلاب,رقم الهاتف,عدد المواد المرتبطة,ملاحظات,تاريخ التسجيل\n";
    
    state.gatherers.forEach((g, index) => {
        const serial = index + 1;
        const name = `"${(g.name || '').replace(/"/g, '""')}"`;
        const phone = `"${(g.phone || '').replace(/"/g, '""')}"`;
        const matCount = g.materialsCount || 0;
        const notes = `"${(g.notes || '').replace(/"/g, '""')}"`;
        const date = `"${formatDateTime(g.createdAt).replace(/"/g, '""')}"`;
        
        csvContent += `${serial},${name},${phone},${matCount},${notes},${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);
};

// -------------------------------------------------------------
// Gatherer Materials & Supplies Modal Handler
// -------------------------------------------------------------
window.openGathererMaterials = function(gathererId) {
    const gatherer = state.gatherers.find(g => String(g.id) === String(gathererId));
    if (!gatherer) {
        showToast("لم يتم العثور على بيانات الجلاب", "warning");
        return;
    }

    const modal = document.getElementById("gatherer-materials-modal");
    const nameEl = document.getElementById("gmat-gatherer-name");
    const phoneEl = document.getElementById("gmat-gatherer-phone");
    const totalCountEl = document.getElementById("gmat-total-count");
    const tbody = document.getElementById("gmat-table-tbody");

    if (nameEl) nameEl.textContent = gatherer.name;
    if (phoneEl) phoneEl.textContent = gatherer.phone ? gatherer.phone : 'غير مسجل';
    if (totalCountEl) totalCountEl.textContent = `${gatherer.materialsCount || 0} مادة`;
    if (tbody) tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding:15px; color:var(--text-muted);"><i class="fa-solid fa-spinner fa-spin" style="margin-left:6px;"></i>جاري تحميل المواد الموردة...</td></tr>`;

    if (modal) modal.classList.add("open");

    fetch(`api/gatherers.php?action=get_materials&gatherer_id=${gathererId}`)
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.data) {
                if (res.data.length === 0) {
                    tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding:15px; color:var(--text-muted);">لا توجد مواد مسجلة باسم هذا الجلاب حتى الآن</td></tr>`;
                    return;
                }

                tbody.innerHTML = res.data.map(m => {
                    const avgPrice = parseFloat(m.defaultPrice || 0);
                    const priceText = avgPrice > 0 ? `${avgPrice.toLocaleString('ar-EG')} د.ع` : '—';
                    return `
                    <tr style="border-bottom: 1px solid var(--border-color);">
                        <td style="padding: 8px 12px; font-weight:700;">${escapeHTML(m.name)}</td>
                        <td style="padding: 8px 12px; text-align:center;">${escapeHTML(m.unit || 'كغم')}</td>
                        <td style="padding: 8px 12px; text-align:center; font-weight:600;">${priceText}</td>
                        <td style="padding: 8px 12px; text-align:center; font-weight:700; color:var(--primary);">${(parseFloat(m.totalSoldQty || 0)).toLocaleString('ar-EG')} ${escapeHTML(m.unit || 'كغم')}</td>
                        <td style="padding: 8px 12px; text-align:center; font-weight:700; color:var(--success);">${(parseFloat(m.totalSoldAmount || 0)).toLocaleString('ar-EG')} د.ع</td>
                    </tr>
                `}).join("");
            } else {
                tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding:15px; color:var(--danger);">فشل تحميل مواد الجلاب</td></tr>`;
            }
        })
        .catch(err => {
            console.error(err);
            tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding:15px; color:var(--danger);">خطأ في الاتصال بالسيرفر</td></tr>`;
        });
};

window.closeGathererMaterialsModal = function() {
    const modal = document.getElementById("gatherer-materials-modal");
    if (modal) modal.classList.remove("open");
};

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

