// Business Logic and UI Interactions for Materials Management Page

// -------------------------------------------------------------
// 1. App State Management
// -------------------------------------------------------------
let state = {
    materials: [],
    filteredMaterials: [],
    gatherers: [],
    commissions: [],
    workerShares: [],
    currentPage: 1,
    entriesPerPage: 10,
    searchTerm: "",
    deleteTargetId: null,
    viewMode: "current" // default to current shift/day
};

// -------------------------------------------------------------
// 2. DOM Elements Selection
// -------------------------------------------------------------
const dom = {
    tbody: document.getElementById("materials-tbody"),
    emptyState: document.getElementById("empty-state-view"),
    table: document.getElementById("materials-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"),
    
    // Stats
    statTotal: document.getElementById("stat-total"),
    statQtyType: document.getElementById("stat-qty-type"),
    statWeightType: document.getElementById("stat-weight-type"),
    
    // Pagination
    paginationInfo: document.getElementById("pagination-info-text"),
    paginationControls: document.getElementById("pagination-controls"),
    
    // Modals
    materialModal: document.getElementById("material-modal"),
    deleteConfirmModal: document.getElementById("delete-confirm-modal"),
    
    // Form
    materialForm: document.getElementById("material-form"),
    materialIdInput: document.getElementById("material-id"),
    materialNameInput: document.getElementById("material-name"),
    materialAccountingTypeSelect: document.getElementById("material-accounting-type"),
    materialWorkerShareTypeSelect: document.getElementById("material-worker-share-type"),
    materialJallabSelect: document.getElementById("material-jallab"),
    modalTitle: document.getElementById("modal-title"),
    
    // Validation Errors
    nameError: document.getElementById("name-error"),
    jallabError: document.getElementById("jallab-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"),

    // Jallab Materials Modal Elements
    jallabMaterialsModal: document.getElementById("jallab-materials-modal"),
    jallabModalTitle: document.getElementById("jallab-modal-title"),
    jallabMaterialsTbody: document.getElementById("jallab-materials-tbody"),
    jallabMaterialsTableWrapper: document.getElementById("jallab-materials-table-wrapper"),
    jallabMaterialsEmpty: document.getElementById("jallab-materials-empty"),
    closeJallabModalBtn: document.getElementById("close-jallab-modal-btn"),
    closeJallabModalBtnFooter: document.getElementById("close-jallab-modal-btn-footer")
};

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));
}

// -------------------------------------------------------------
// 3. App Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    loadMaterialsOptions().then(() => {
        loadData();
        initTheme();
        setupEventListeners();
        populateJallabDropdown();
        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(['materials'], loadData);
        }, 3000);
    });
});

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

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

// -------------------------------------------------------------
// 5. 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>
    `;
    
    dom.toastContainer.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// -------------------------------------------------------------
// 6. Statistics Calculations
// -------------------------------------------------------------
function updateStatistics() {
    // Total registered materials in current view
    const list = state.filteredMaterials;
    const totalMaterials = list.length;
    dom.statTotal.textContent = totalMaterials;

    if (totalMaterials === 0) {
        dom.statQtyType.textContent = "0";
        dom.statWeightType.textContent = "0";
        return;
    }

    const qtyMaterials = list.filter(m => m.accountingType === "عدد * سعر").length;
    const weightMaterials = list.filter(m => m.accountingType === "وزن * سعر").length;

    dom.statQtyType.textContent = qtyMaterials;
    dom.statWeightType.textContent = weightMaterials;
}

// Helper to read current currency from settings
function getCurrency() {
    const settings = localStorage.getItem("dashboard_settings");
    if (settings) {
        try {
            return JSON.parse(settings).currency || "د.ع";
        } catch (e) {}
    }
    return "د.ع";
}

// Helper to get the work day start hour from settings
function getWorkDayStartHour() {
    const settings = localStorage.getItem("dashboard_settings");
    if (settings) {
        try {
            const parsed = JSON.parse(settings);
            return parsed.workDayStartHour !== undefined ? parseInt(parsed.workDayStartHour) : 5;
        } catch (e) {
            return 5;
        }
    }
    return 5;
}

// Helper to format currency values cleanly
function formatCurrency(val) {
    return parseFloat(val).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

// -------------------------------------------------------------
// 7. Search, Filtering and Pagination Logic
// -------------------------------------------------------------
// ── Helper to calculate current shift boundaries (dynamic start hour) ──
function getCurrentShiftRange() {
    const now = new Date();
    const start = new Date(now);
    const end = new Date(now);
    const currentHour = now.getHours();
    const startHour = getWorkDayStartHour();
    
    if (currentHour >= startHour) {
        // Shift started today at startHour, ends tomorrow at startHour
        start.setHours(startHour, 0, 0, 0);
        end.setDate(end.getDate() + 1);
        end.setHours(startHour, 0, 0, 0);
    } else {
        // Shift started yesterday at startHour, ends today at startHour
        start.setDate(start.getDate() - 1);
        start.setHours(startHour, 0, 0, 0);
        end.setHours(startHour, 0, 0, 0);
    }
    return { start: start.getTime(), end: end.getTime() };
}

// ── Handle Toggle between Current Shift Materials and Previous Days Materials ──
window.setViewMode = function(mode) {
    state.viewMode = mode;
    state.currentPage = 1;
    
    const btnCurrent = document.getElementById("btn-view-current");
    const btnPrevious = document.getElementById("btn-view-previous");
    
    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";
        } 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";
        }
    }
    
    applyFilters();
};

function applyFilters() {
    state.searchTerm = dom.searchInput ? dom.searchInput.value.trim().toLowerCase() : "";
    const accFilter = document.getElementById("filter-accounting-type")?.value || "";
    const jallabFilter = document.getElementById("filter-jallab")?.value || "";
    
    // 1. Filter by viewMode (current shift vs previous days)
    let baseMaterials = [...state.materials];
    const shiftRange = getCurrentShiftRange();
    
    if (state.viewMode === 'current') {
        baseMaterials = baseMaterials.filter(item => {
            const time = new Date(item.createdAt.replace(' ', 'T')).getTime();
            return time >= shiftRange.start && time < shiftRange.end;
        });
    } else if (state.viewMode === 'previous') {
        baseMaterials = baseMaterials.filter(item => {
            const time = new Date(item.createdAt.replace(' ', 'T')).getTime();
            return time < shiftRange.start || time >= shiftRange.end;
        });
    }

    // 2. Filter by accounting type if selected
    if (accFilter) {
        baseMaterials = baseMaterials.filter(m => m.accountingType === accFilter);
    }

    // 3. Filter by Jallab if selected
    if (jallabFilter) {
        baseMaterials = baseMaterials.filter(m => String(m.jallabId) === String(jallabFilter));
    }

    // 4. Filter by search term
    if (state.searchTerm === "") {
        state.filteredMaterials = baseMaterials;
        if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
    } else {
        state.filteredMaterials = baseMaterials.filter(item => {
            const jallabName = (item.jallabName || "").toLowerCase();

            return item.name.toLowerCase().includes(state.searchTerm) || 
                   item.accountingType.toLowerCase().includes(state.searchTerm) ||
                   item.commissionType.toLowerCase().includes(state.searchTerm) ||
                   item.workerShareType.toLowerCase().includes(state.searchTerm) ||
                   jallabName.includes(state.searchTerm);
        });
        if (dom.searchResultsBadge) {
            dom.searchResultsBadge.style.display = "inline-block";
            dom.searchResultsBadge.textContent = `تم إيجاد ${state.filteredMaterials.length} نتيجة`;
        }
    }

    state.entriesPerPage = dom.entriesSelect ? parseInt(dom.entriesSelect.value) : 10;
    
    // Check if current page is out of bounds
    const totalPages = Math.ceil(state.filteredMaterials.length / state.entriesPerPage);
    if (state.currentPage > totalPages) {
        state.currentPage = totalPages || 1;
    }

    renderTable();
    updateStatistics();
}

// Search button handler
window.doSearchMaterials = function() {
    state.currentPage = 1;
    applyFilters();
    if (dom.searchInput) dom.searchInput.focus();
};

// Clear search
window.clearSearchMaterials = function() {
    if (dom.searchInput) dom.searchInput.value = "";
    const accFilter = document.getElementById("filter-accounting-type");
    if (accFilter) accFilter.value = "";
    const jallabFilter = document.getElementById("filter-jallab");
    if (jallabFilter) jallabFilter.value = "";
    if (dom.searchResultsBadge) dom.searchResultsBadge.style.display = "none";
    state.currentPage = 1;
    applyFilters();
};

// -------------------------------------------------------------
// 8. Dynamic DOM Rendering
// -------------------------------------------------------------
function populateJallabDropdown() {
    if (dom.materialJallabSelect) {
        dom.materialJallabSelect.innerHTML = '<option value="" disabled selected>-- اختر الجلاب المرتبط بالمادة --</option>';
        state.gatherers.forEach(g => {
            const option = document.createElement("option");
            option.value = g.id;
            option.textContent = g.name;
            dom.materialJallabSelect.appendChild(option);
        });
    }

    const filterJallab = document.getElementById("filter-jallab");
    if (filterJallab) {
        const currentVal = filterJallab.value;
        filterJallab.innerHTML = '<option value="">جميع الجلابين</option>';
        state.gatherers.forEach(g => {
            const option = document.createElement("option");
            option.value = g.id;
            option.textContent = g.name;
            filterJallab.appendChild(option);
        });
        filterJallab.value = currentVal;
    }
}

function renderTable() {
    dom.tbody.innerHTML = "";
    const list = state.filteredMaterials;
    const total = list.length;

    if (total === 0) {
        dom.table.style.display = "none";
        dom.emptyState.style.display = "flex";
        dom.paginationInfo.textContent = "يعرض 0 إلى 0 من أصل 0 مادة";
        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((item, index) => {
        const serial = startIndex + index + 1;
        const jallabName = item.jallabName || "غير معروف";
        const usageBadge = (item.usageCount || 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-file-invoice" style="margin-left:4px;"></i>${item.usageCount} مرة</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(item.name)}" style="font-weight:700;">${escapeHTML(item.name)}</td>
            <td>
                <span class="card-type-chip ${item.accountingType === 'عدد * سعر' ? 'primary' : 'secondary'}" style="font-size: 12px; font-weight:700; padding: 4px 10px; border-radius: 12px; background-color: ${item.accountingType === 'عدد * سعر' ? 'rgba(79, 70, 229, 0.1)' : 'rgba(245, 158, 11, 0.1)'}; color: ${item.accountingType === 'عدد * سعر' ? '#4f46e5' : '#f59e0b'};">
                    ${escapeHTML(item.accountingType)}
                </span>
            </td>
            <td style="font-weight: 700; color: var(--primary);" title="${escapeHTML(item.commissionType)}">${escapeHTML(item.commissionType)}</td>
            <td style="font-weight: 600;" title="${escapeHTML(item.workerShareType)}">${escapeHTML(item.workerShareType)}</td>
            <td style="font-weight: 600; color: var(--primary); cursor: pointer; text-decoration: underline;" title="اضغط لتصفية الجدول وعرض مواد هذا الجلاب فقط" onclick="filterByJallab('${item.jallabId}', '${escapeHTML(jallabName)}')">${escapeHTML(jallabName)}</td>
            <td>${usageBadge}</td>
            <td>
                <div class="actions-cell">
                    <button class="btn-icon btn-icon-edit" onclick="openEditModal('${item.id}')" title="تعديل">
                        <i class="fa-solid fa-pen-to-square"></i>
                    </button>
                    <button class="btn-icon btn-icon-delete" onclick="openDeleteModal('${item.id}')" title="حذف">
                        <i class="fa-solid fa-trash-can"></i>
                    </button>
                </div>
            </td>
        `;
        dom.tbody.appendChild(tr);
    });

    // Update Pagination Info
    dom.paginationInfo.textContent = `يعرض ${startIndex + 1} إلى ${endIndex} من أصل ${total} مادة`;
    
    // Render Pagination Controls
    renderPagination(total);
}

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

    // Previous Button
    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);

    // Page numbers
    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);
    }

    // Next Button
    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);
}

// -------------------------------------------------------------
// 9. Modals Open / Close Control
// -------------------------------------------------------------
// -------------------------------------------------------------
// Commission Options Manager (Dynamic localStorage list)
// -------------------------------------------------------------
// -------------------------------------------------------------
// Commission & Worker Share Options Manager (Dynamic DB-driven)
// -------------------------------------------------------------
function loadMaterialsOptions() {
    return fetch('api/materials_options.php?action=list')
        .then(response => response.json())
        .then(res => {
            if (res.status === 'success') {
                state.commissions = res.commissions || [];
                state.workerShares = res.worker_shares || [];
            }
        })
        .catch(err => {
            console.error("Failed to load materials options from DB:", err);
        });
}

function isPercentageCommission(val) {
    if (!val) return false;
    return val.includes('%') || val.includes('10%') || val.includes('20%') || val.includes('نسبة');
}

function renderCommissionOptions(checkedValues = []) {
    const listContainer = document.getElementById("commission-checkboxes-list");
    if (!listContainer) return;
    
    const options = state.commissions || [];
    listContainer.innerHTML = "";
    
    options.forEach(val => {
        const isChecked = checkedValues.includes(val);
        const itemDiv = document.createElement("div");
        itemDiv.className = "commission-option-item";
        itemDiv.style.cssText = "display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 0;";
        itemDiv.innerHTML = `
            <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; color: var(--text-primary); font-size: 13px; flex: 1; margin: 0; user-select: none;">
                <input type="checkbox" name="commission_types" value="${escapeHTML(val)}" ${isChecked ? 'checked' : ''} style="width: 16px; height: 16px; accent-color: var(--primary);">
                <span class="option-text-label">${escapeHTML(val)}</span>
            </label>
            <div style="display: flex; gap: 4px; align-items: center;">
                <button type="button" class="btn-edit-option" data-value="${escapeHTML(val)}" style="background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 4px 6px; border-radius: var(--radius-sm); font-size: 12px; transition: all 0.2s;" onmouseover="this.style.color='var(--primary)'" onmouseout="this.style.color='var(--text-secondary)'" title="تعديل">
                    <i class="fa-solid fa-pen-to-square"></i>
                </button>
                <button type="button" class="btn-delete-option" data-value="${escapeHTML(val)}" style="background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 4px 6px; border-radius: var(--radius-sm); font-size: 12px; transition: all 0.2s;" onmouseover="this.style.color='var(--danger)'" onmouseout="this.style.color='var(--text-secondary)'" title="حذف">
                    <i class="fa-solid fa-trash-can"></i>
                </button>
            </div>
        `;
        listContainer.appendChild(itemDiv);
    });

    // Enforce mutual exclusivity for percentage commission options (10% vs 20%)
    listContainer.querySelectorAll('input[name="commission_types"]').forEach(cb => {
        cb.addEventListener("change", (e) => {
            if (e.target.checked && isPercentageCommission(e.target.value)) {
                listContainer.querySelectorAll('input[name="commission_types"]').forEach(other => {
                    if (other !== e.target && isPercentageCommission(other.value)) {
                        other.checked = false;
                    }
                });
            }
        });
    });
    
    // Bind click events for Edit and Delete buttons
    listContainer.querySelectorAll(".btn-edit-option").forEach(btn => {
        btn.addEventListener("click", (e) => {
            e.stopPropagation();
            const oldVal = btn.getAttribute("data-value");
            const newVal = prompt("تعديل صيغة العمولة:", oldVal);
            if (newVal === null) return; // user cancelled
            const trimmed = newVal.trim();
            if (!trimmed) {
                showToast("الصيغة لا يمكن أن تكون فارغة", "warning");
                return;
            }
            if (/[<>'"\/]/.test(trimmed)) {
                showToast("الصيغة غير صالحة ولا يمكن أن تحتوي على رموز خاصة", "warning");
                return;
            }
            
            // Call API to edit
            fetch('api/materials_options.php?action=edit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'commission', old_value: oldVal, new_value: trimmed })
            })
            .then(response => response.json())
            .then(res => {
                if (res.status === 'success') {
                    // Update state and re-render
                    const idx = state.commissions.indexOf(oldVal);
                    if (idx !== -1) state.commissions[idx] = trimmed;
                    
                    const currentChecked = Array.from(document.querySelectorAll('input[name="commission_types"]:checked')).map(cb => cb.value);
                    const updatedChecked = currentChecked.map(v => v === oldVal ? trimmed : v);
                    
                    renderCommissionOptions(updatedChecked);
                    showToast(res.message, "success");
                } else {
                    showToast(res.message || "فشل تعديل العمولة", "danger");
                }
            })
            .catch(err => {
                showToast("حدث خطأ أثناء تعديل العمولة", "danger");
            });
        });
    });
    
    listContainer.querySelectorAll(".btn-delete-option").forEach(btn => {
        btn.addEventListener("click", (e) => {
            e.stopPropagation();
            const val = btn.getAttribute("data-value");
            if (confirm(`هل أنت متأكد من حذف خيار العمولة: "${val}"؟`)) {
                // Call API to delete
                fetch('api/materials_options.php?action=delete', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ type: 'commission', value: val })
                })
                .then(response => response.json())
                .then(res => {
                    if (res.status === 'success') {
                        const idx = state.commissions.indexOf(val);
                        if (idx !== -1) state.commissions.splice(idx, 1);
                        
                        const currentChecked = Array.from(document.querySelectorAll('input[name="commission_types"]:checked')).map(cb => cb.value);
                        const updatedChecked = currentChecked.filter(v => v !== val);
                        
                        renderCommissionOptions(updatedChecked);
                        showToast(res.message, "info");
                    } else {
                        showToast(res.message || "فشل حذف العمولة", "danger");
                    }
                })
                .catch(err => {
                    showToast("حدث خطأ أثناء حذف العمولة", "danger");
                });
            }
        });
    });
}

function renderWorkerShareOptions(selectedValue = "") {
    const listContainer = document.getElementById("worker-share-list");
    if (!listContainer) return;
    
    const options = state.workerShares || [];
    listContainer.innerHTML = "";
    
    options.forEach(val => {
        const isChecked = String(val) === String(selectedValue);
        const itemDiv = document.createElement("div");
        itemDiv.className = "worker-share-option-item";
        itemDiv.style.cssText = "display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 0;";
        itemDiv.innerHTML = `
            <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; color: var(--text-primary); font-size: 13px; flex: 1; margin: 0; user-select: none;">
                <input type="radio" name="worker_share_type" value="${escapeHTML(val)}" ${isChecked ? 'checked' : ''} style="width: 16px; height: 16px; accent-color: var(--primary);">
                <span class="option-text-label">${escapeHTML(val)}</span>
            </label>
            <div style="display: flex; gap: 4px; align-items: center;">
                <button type="button" class="btn-edit-worker-option" data-value="${escapeHTML(val)}" style="background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 4px 6px; border-radius: var(--radius-sm); font-size: 12px; transition: all 0.2s;" onmouseover="this.style.color='var(--primary)'" onmouseout="this.style.color='var(--text-secondary)'" title="تعديل">
                    <i class="fa-solid fa-pen-to-square"></i>
                </button>
                <button type="button" class="btn-delete-worker-option" data-value="${escapeHTML(val)}" style="background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 4px 6px; border-radius: var(--radius-sm); font-size: 12px; transition: all 0.2s;" onmouseover="this.style.color='var(--danger)'" onmouseout="this.style.color='var(--text-secondary)'" title="حذف">
                    <i class="fa-solid fa-trash-can"></i>
                </button>
            </div>
        `;
        listContainer.appendChild(itemDiv);
    });
    
    // Bind click events for Edit and Delete buttons
    listContainer.querySelectorAll(".btn-edit-worker-option").forEach(btn => {
        btn.addEventListener("click", (e) => {
            e.stopPropagation();
            const oldVal = btn.getAttribute("data-value");
            const newVal = prompt("تعديل خيار حق العامل:", oldVal);
            if (newVal === null) return; // user cancelled
            const trimmed = newVal.trim();
            if (!trimmed) {
                showToast("الصيغة لا يمكن أن تكون فارغة", "warning");
                return;
            }
            if (/[<>'"\/]/.test(trimmed)) {
                showToast("الصيغة غير صالحة ولا يمكن أن تحتوي على رموز خاصة", "warning");
                return;
            }
            
            // Call API to edit
            fetch('api/materials_options.php?action=edit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'worker_share', old_value: oldVal, new_value: trimmed })
            })
            .then(response => response.json())
            .then(res => {
                if (res.status === 'success') {
                    const idx = state.workerShares.indexOf(oldVal);
                    if (idx !== -1) state.workerShares[idx] = trimmed;
                    
                    const checkedRadio = document.querySelector('input[name="worker_share_type"]:checked');
                    const currentSelected = checkedRadio ? checkedRadio.value : "";
                    const updatedSelected = (currentSelected === oldVal) ? trimmed : currentSelected;
                    
                    renderWorkerShareOptions(updatedSelected);
                    showToast(res.message, "success");
                } else {
                    showToast(res.message || "فشل تعديل حق العامل", "danger");
                }
            })
            .catch(err => {
                showToast("حدث خطأ أثناء تعديل حق العامل", "danger");
            });
        });
    });
    
    listContainer.querySelectorAll(".btn-delete-worker-option").forEach(btn => {
        btn.addEventListener("click", (e) => {
            e.stopPropagation();
            const val = btn.getAttribute("data-value");
            if (confirm(`هل أنت متأكد من حذف خيار حق العامل: "${val}"؟`)) {
                // Call API to delete
                fetch('api/materials_options.php?action=delete', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ type: 'worker_share', value: val })
                })
                .then(response => response.json())
                .then(res => {
                    if (res.status === 'success') {
                        const idx = state.workerShares.indexOf(val);
                        if (idx !== -1) state.workerShares.splice(idx, 1);
                        
                        const checkedRadio = document.querySelector('input[name="worker_share_type"]:checked');
                        const currentSelected = checkedRadio ? checkedRadio.value : "";
                        const updatedSelected = (currentSelected === val) ? "" : currentSelected;
                        
                        renderWorkerShareOptions(updatedSelected);
                        showToast(res.message, "info");
                    } else {
                        showToast(res.message || "فشل حذف حق العامل", "danger");
                    }
                })
                .catch(err => {
                    showToast("حدث خطأ أثناء حذف حق العامل", "danger");
                });
            }
        });
    });
}

window.openEditModal = function(id) {
    const item = state.materials.find(x => String(x.id) === String(id));
    if (!item) return;

    clearValidationErrors();
    dom.modalTitle.textContent = "تعديل مادة";
    dom.materialIdInput.value = item.id;
    dom.materialNameInput.value = item.name;
    dom.materialAccountingTypeSelect.value = item.accountingType;
    const commTypeStr = item.commissionType || '';
    const commTypes = commTypeStr.split(' + ').map(s => s.trim());

    // Dynamically append any stored custom commissions to database options list if missing
    let modified = false;
    const promises = [];
    
    commTypes.forEach(val => {
        if (val && val !== '---' && !state.commissions.includes(val)) {
            state.commissions.push(val);
            modified = true;
            promises.push(
                fetch('api/materials_options.php?action=add', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ type: 'commission', value: val })
                }).catch(() => {})
            );
        }
    });

    const workerShareVal = item.workerShareType || '';
    if (workerShareVal && !state.workerShares.includes(workerShareVal)) {
        state.workerShares.push(workerShareVal);
        modified = true;
        promises.push(
            fetch('api/materials_options.php?action=add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'worker_share', value: workerShareVal })
            }).catch(() => {})
        );
    }

    if (promises.length > 0) {
        Promise.all(promises).then(() => {
            renderCommissionOptions(commTypes);
            renderWorkerShareOptions(workerShareVal);
        });
    } else {
        renderCommissionOptions(commTypes);
        renderWorkerShareOptions(workerShareVal);
    }
    
    dom.materialJallabSelect.value = item.jallabId;
    
    dom.materialModal.classList.add("open");
};

function openAddModal() {
    clearValidationErrors();
    dom.modalTitle.textContent = "إضافة مادة جديدة";
    dom.materialForm.reset();
    dom.materialIdInput.value = "";
    
    renderCommissionOptions([]);
    
    // Select first option by default for worker share
    const defaultWorker = state.workerShares.length > 0 ? state.workerShares[0] : "";
    renderWorkerShareOptions(defaultWorker);
    
    dom.materialModal.classList.add("open");
}

function closeModal() {
    dom.materialModal.classList.remove("open");
    dom.materialForm.reset();
    clearValidationErrors();
}

window.openDeleteModal = function(id) {
    const item = state.materials.find(x => String(x.id) === String(id));
    if (!item) return;

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

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

// -------------------------------------------------------------
// 10. Form Validation & Submission
// -------------------------------------------------------------
function clearValidationErrors() {
    dom.materialNameInput.closest(".form-group").classList.remove("has-error");
    dom.materialJallabSelect.closest(".form-group").classList.remove("has-error");
}

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

    if (!name || name.trim().length < 2) {
        dom.materialNameInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }

    if (!jallabId) {
        dom.materialJallabSelect.closest(".form-group").classList.add("has-error");
        isValid = false;
    }

    const selectedCommTypes = document.querySelectorAll('input[name="commission_types"]:checked');
    if (selectedCommTypes.length === 0) {
        showToast("يرجى اختيار نوع عمولة واحد على الأقل", "danger");
        isValid = false;
    } else {
        const selectedValues = Array.from(selectedCommTypes).map(cb => cb.value);
        const percentageSelected = selectedValues.filter(val => isPercentageCommission(val));
        if (percentageSelected.length > 1) {
            showToast("يمنع اختيار أكثر من نسبة عمولة واحدة (مثلاً إضافة 10% وإضافة 20%). يرجى اختيار نسبة واحدة فقط أو عدم اختيار أي نسبة.", "danger");
            isValid = false;
        }
    }

    const checkedWorkerShare = document.querySelector('input[name="worker_share_type"]:checked');
    if (!checkedWorkerShare) {
        showToast("يرجى اختيار حق العامل", "danger");
        isValid = false;
    }

    return isValid;
}

let isSubmitting = false;

function handleFormSubmit(e) {
    e.preventDefault();
    if (isSubmitting) return;
    
    const id = dom.materialIdInput.value;
    const name = dom.materialNameInput.value.trim();
    const accountingType = dom.materialAccountingTypeSelect.value;
    const selectedCommTypes = Array.from(document.querySelectorAll('input[name="commission_types"]:checked')).map(cb => cb.value);
    const commissionType = selectedCommTypes.length > 0 ? selectedCommTypes.join(' + ') : '';
    const checkedWorkerShare = document.querySelector('input[name="worker_share_type"]:checked');
    const workerShareType = checkedWorkerShare ? checkedWorkerShare.value : '';
    const jallabId = dom.materialJallabSelect.value;

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

    isSubmitting = true;
    const saveBtn = document.getElementById("save-btn");
    if (saveBtn) {
        saveBtn.disabled = true;
        const btnText = saveBtn.querySelector("span");
        if (btnText) btnText.textContent = "جاري الحفظ...";
    }

    fetch('api/materials.php?action=save', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id, name, accountingType, commissionType, workerShareType, jallabId })
    })
    .then(response => response.json())
    .then(res => {
        isSubmitting = false;
        if (saveBtn) {
            saveBtn.disabled = false;
            const btnText = saveBtn.querySelector("span");
            if (btnText) btnText.textContent = "حفظ البيانات";
        }
        if (res.status === 'success') {
            showToast(res.message);
            closeModal();
            loadData();
        } else {
            showToast(res.message, "danger");
        }
    })
    .catch(err => {
        isSubmitting = false;
        if (saveBtn) {
            saveBtn.disabled = false;
            const btnText = saveBtn.querySelector("span");
            if (btnText) btnText.textContent = "حفظ البيانات";
        }
        console.error(err);
        showToast("فشل الاتصال بالخادم لحفظ البيانات", "danger");
    });
}

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

    const id = state.deleteTargetId;
    
    fetch('api/materials.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, "danger");
            closeDeleteModal();
            loadData();
        } else {
            showToast(res.message, "danger");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم لحذف المادة", "danger");
    });
}

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

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

    // Close Modals
    dom.closeModalBtn.addEventListener("click", closeModal);
    dom.cancelModalBtn.addEventListener("click", closeModal);
    dom.cancelDeleteBtn.addEventListener("click", closeDeleteModal);

    // Confirm Delete
    dom.confirmDeleteBtn.addEventListener("click", handleDeleteConfirm);

    // Form Submit
    dom.materialForm.addEventListener("submit", handleFormSubmit);

    // Custom Commission Add Button listener
    const btnAddCustomComm = document.getElementById("btn-add-custom-commission");
    const customCommInput = document.getElementById("custom-commission-input");

    if (btnAddCustomComm && customCommInput) {
        btnAddCustomComm.addEventListener("click", () => {
            const val = customCommInput.value.trim();
            if (!val) {
                showToast("يرجى إدخال صيغة عمولة مخصصة أولاً", "warning");
                return;
            }
            if (/[<>'"\/]/.test(val)) {
                showToast("الصيغة غير صالحة ولا يمكن أن تحتوي على رموز خاصة", "warning");
                return;
            }
            
            if (state.commissions.includes(val)) {
                showToast("نوع العمولة هذا مضاف بالفعل في القائمة", "warning");
                return;
            }

            // Call API to add
            fetch('api/materials_options.php?action=add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'commission', value: val })
            })
            .then(response => response.json())
            .then(res => {
                if (res.status === 'success') {
                    state.commissions.push(val);
                    const currentChecked = Array.from(document.querySelectorAll('input[name="commission_types"]:checked')).map(cb => cb.value);
                    currentChecked.push(val);
                    renderCommissionOptions(currentChecked);
                    
                    customCommInput.value = "";
                    showToast(res.message, "success");
                } else {
                    showToast(res.message || "فشل إضافة العمولة", "danger");
                }
            })
            .catch(err => {
                showToast("حدث خطأ أثناء إضافة العمولة", "danger");
            });
        });
    }

    // Custom Worker Share Add Button listener
    const btnAddCustomWorkerShare = document.getElementById("btn-add-custom-worker-share");
    const customWorkerShareInput = document.getElementById("custom-worker-share-input");

    if (btnAddCustomWorkerShare && customWorkerShareInput) {
        btnAddCustomWorkerShare.addEventListener("click", () => {
            const val = customWorkerShareInput.value.trim();
            if (!val) {
                showToast("يرجى إدخال صيغة حق عامل مخصصة أولاً", "warning");
                return;
            }
            if (/[<>'"\/]/.test(val)) {
                showToast("الصيغة غير صالحة ولا يمكن أن تحتوي على رموز خاصة", "warning");
                return;
            }
            
            if (state.workerShares.includes(val)) {
                showToast("حق العامل هذا مضاف بالفعل في القائمة", "warning");
                return;
            }

            // Call API to add
            fetch('api/materials_options.php?action=add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'worker_share', value: val })
            })
            .then(response => response.json())
            .then(res => {
                if (res.status === 'success') {
                    state.workerShares.push(val);
                    renderWorkerShareOptions(val);
                    
                    customWorkerShareInput.value = "";
                    showToast(res.message, "success");
                } else {
                    showToast(res.message || "فشل إضافة حق العامل", "danger");
                }
            })
            .catch(err => {
                showToast("حدث خطأ أثناء إضافة حق العامل", "danger");
            });
        });
    }

    // Search input real-time typing
    dom.searchInput.addEventListener("input", () => {
        state.currentPage = 1;
        applyFilters();
    });

    // Entries limit select box
    dom.entriesSelect.addEventListener("change", () => {
        state.currentPage = 1;
        applyFilters();
    });

    // Theme Switch
    dom.themeToggle.addEventListener("click", toggleTheme);

    // Close Jallab Materials Modal
    dom.closeJallabModalBtn.addEventListener("click", closeJallabModal);
    dom.closeJallabModalBtnFooter.addEventListener("click", closeJallabModal);

    // Close modals on clicking overlay outside the card
    window.addEventListener("click", (e) => {
        if (e.target === dom.materialModal) {
            closeModal();
        }
        if (e.target === dom.deleteConfirmModal) {
            closeDeleteModal();
        }
        if (e.target === dom.jallabMaterialsModal) {
            closeJallabModal();
        }
    });

    // Close modals on Escape key press
    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeModal();
            closeDeleteModal();
            closeJallabModal();
        }
    });
}

// -------------------------------------------------------------
// 14. Export and Print Functions
// -------------------------------------------------------------
window.printTable = function() {
    const printWindow = window.open('', '_blank');
    const tableHtml = document.getElementById('materials-table').outerHTML;
    
    printWindow.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;
                    background-color: #fff;
                    color: #000;
                }
                h2 {
                    text-align: center;
                    margin-bottom: 20px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                    margin-top: 10px;
                }
                th, td {
                    border: 1px solid #ddd;
                    padding: 12px;
                    text-align: right;
                }
                th {
                    background-color: #f4f6f9;
                }
                /* Hide Actions Column during print */
                th:nth-child(7), td:nth-child(7) {
                    display: none;
                }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            <h1 style="text-align:center; font-size:18px; margin:0 0 6px 0; color:#1e293b;">${getOrgName()}</h1>
            <h2>قائمة المواد المسجلة</h2>
            ${tableHtml}
        </body>
        </html>
    `);
    printWindow.document.close();
};

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

window.exportExcel = function() {
    if (state.materials.length === 0) {
        showToast("لا توجد بيانات لتصديرها", "warning");
        return;
    }
    
    // CSV headers with UTF-8 BOM for Arabic Excel support
    let csvContent = "\uFEFF";
    csvContent += "التسلسل,المادة,نوع المحاسبة,نوع العمولة,حق العامل,نوع المحصول (الجلاب),عدد الاستخدامات,تاريخ الإضافة\n";
    
    state.materials.forEach((item, index) => {
        const serial = index + 1;
        const jallabName = item.jallabName || "غير معروف";
        
        const name = `"${(item.name || '').replace(/"/g, '""')}"`;
        const accType = `"${(item.accountingType || '').replace(/"/g, '""')}"`;
        const commType = `"${(item.commissionType || '').replace(/"/g, '""')}"`;
        const workerShare = `"${(item.workerShareType || '').replace(/"/g, '""')}"`;
        const jallabStr = `"${jallabName.replace(/"/g, '""')}"`;
        const usage = item.usageCount || 0;
        const date = `"${(item.createdAt || '').replace(/"/g, '""')}"`;
        
        csvContent += `${serial},${name},${accType},${commType},${workerShare},${jallabStr},${usage},${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("تم تصدير الملف بنجاح", "success");
};

window.filterByJallab = function(jallabId, jallabName) {
    // Set modal title
    dom.jallabModalTitle.textContent = `مواد الجلاب: ${jallabName}`;
    
    // Filter materials for this Jallab using jallabName (more reliable than ID matching)
    const jallabMaterials = state.materials.filter(m => String(m.jallabId) === String(jallabId) || m.jallabName === jallabName);
    
    // Clear and populate tbody
    dom.jallabMaterialsTbody.innerHTML = "";
    
    if (jallabMaterials.length === 0) {
        dom.jallabMaterialsTableWrapper.style.display = "none";
        dom.jallabMaterialsEmpty.style.display = "block";
    } else {
        dom.jallabMaterialsTableWrapper.style.display = "block";
        dom.jallabMaterialsEmpty.style.display = "none";
        
        jallabMaterials.forEach((item, index) => {
            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td class="serial-col">#${index + 1}</td>
                <td class="name-col" title="${escapeHTML(item.name)}">${escapeHTML(item.name)}</td>
                <td>
                    <span class="card-type-chip ${item.accountingType === 'عدد * سعر' ? 'primary' : 'secondary'}" style="font-size: 11px; font-weight:700; padding: 2px 8px; border-radius: 12px; background-color: ${item.accountingType === 'عدد * سعر' ? 'rgba(79, 70, 229, 0.1)' : 'rgba(245, 158, 11, 0.1)'}; color: ${item.accountingType === 'عدد * سعر' ? '#4f46e5' : '#f59e0b'};">
                        ${escapeHTML(item.accountingType)}
                    </span>
                </td>
                <td style="font-weight: 700; color: var(--primary);">${escapeHTML(item.commissionType)}</td>
                <td style="font-weight: 600;">${escapeHTML(item.workerShareType)}</td>
            `;
            dom.jallabMaterialsTbody.appendChild(tr);
        });
    }
    
    // Show Modal
    dom.jallabMaterialsModal.classList.add("open");
};

// Function to close Jallab modal
function closeJallabModal() {
    dom.jallabMaterialsModal.classList.remove("open");
}
window.closeJallabModal = closeJallabModal;

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

