// Business Logic for Home/Dashboard (الرئيسية)
// ✅ Connected to MySQL Database via APIs

// -------------------------------------------------------------
// 1. App State
// -------------------------------------------------------------
let state = {
    safes: [],
    transactions: [],
    forms: [],
    debtStats: null,
    materials: [],
    shiftStats: null
};

// -------------------------------------------------------------
// 2. DOM Elements
// -------------------------------------------------------------
const dom = {
    // Financial stats
    statCash:         document.getElementById("stat-cash"),
    statDebts:        document.getElementById("stat-debts"),
    statShiftDebts:   document.getElementById("stat-shift-debts"),
    statRepayments:   document.getElementById("stat-repayments"),
    statSales:        document.getElementById("stat-sales"),
    // Shift / forms stats
    statFormsTotal:   document.getElementById("stat-forms-total"),
    statActiveForms:  document.getElementById("stat-active-forms"),
    statInactiveForms:document.getElementById("stat-inactive-forms"),
    statWorkerShift:  document.getElementById("stat-worker-shift"),
    statCommission10: document.getElementById("stat-commission-10"),
    statBags:         document.getElementById("stat-bags"),
    statBala:         document.getElementById("stat-bala"),
    // UI
    themeToggle:      document.getElementById("theme-toggle"),
    toastContainer:   document.getElementById("toast-container"),

    // Worker Share Breakdown Modal
    cardWorkerShare:          document.getElementById("card-worker-share"),
    workerShareModal:         document.getElementById("worker-share-modal"),
    closeWorkerModalBtn:      document.getElementById("close-worker-modal-btn"),
    closeWorkerModalBtnFooter:document.getElementById("close-worker-modal-btn-footer"),
    workerShareGroupsList:    document.getElementById("worker-share-groups-list"),

    // Sales Breakdown Modal
    cardSales:                document.getElementById("card-sales"),
    salesModal:               document.getElementById("sales-modal"),
    closeSalesModalBtn:       document.getElementById("close-sales-modal-btn"),
    closeSalesModalBtnFooter: document.getElementById("close-sales-modal-btn-footer"),
    salesGroupsList:          document.getElementById("sales-groups-list"),

    // Bala Breakdown Modal
    cardBala:                 document.getElementById("card-bala"),
    balaModal:                document.getElementById("bala-modal"),
    closeBalaModalBtn:        document.getElementById("close-bala-modal-btn"),
    closeBalaModalBtnFooter:  document.getElementById("close-bala-modal-btn-footer"),
    balaGroupsList:           document.getElementById("bala-groups-list"),

    // Bags Breakdown Modal
    cardBags:                 document.getElementById("card-bags"),
    bagsModal:                document.getElementById("bags-modal"),
    closeBagsModalBtn:        document.getElementById("close-bags-modal-btn"),
    closeBagsModalBtnFooter:  document.getElementById("close-bags-modal-btn-footer"),
    bagsGroupsList:           document.getElementById("bags-groups-list"),

    // Today's Debts (Invoices) Modal
    cardShiftDebts:                 document.getElementById("card-shift-debts"),
    todayDebtsModal:                document.getElementById("today-debts-modal"),
    closeTodayDebtsModalBtn:        document.getElementById("close-today-debts-modal-btn"),
    closeTodayDebtsModalBtnFooter:  document.getElementById("close-today-debts-modal-btn-footer"),

    // Today's Cash Forms Modal
    cardCashStats:                  document.getElementById("card-cash-stats"),
    todayCashFormsModal:            document.getElementById("today-cash-forms-modal"),
    closeTodayCashModalBtn:         document.getElementById("close-today-cash-modal-btn"),
    closeTodayCashModalBtnFooter:   document.getElementById("close-today-cash-modal-btn-footer")
};

let isSystemStateInitialized = false;
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] || '';
                    if (isSystemStateInitialized && lastStates[t] !== undefined && lastStates[t] !== newTs) {
                        hasChanges = true;
                    }
                    lastStates[t] = newTs;
                });
                isSystemStateInitialized = true;
                if (hasChanges) {
                    refreshCallback();
                }
            }
        })
        .catch(err => console.error("Error checking states:", err));
}

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

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

    loadDashboardData();
    setInterval(() => {
        checkSystemStateAndRefresh(['forms', 'safe_transactions', 'debtors'], loadDashboardData);
    }, 3000);
});

function loadDashboardData() {
    Promise.allSettled([
        fetch('api/safes.php?action=list').then(r => r.json()).catch(() => null),
        fetch('api/forms.php?action=list').then(r => r.json()).catch(() => null),
        fetch('api/debts.php?action=get_stats').then(r => r.json()).catch(() => null),
        fetch('api/materials.php?action=list').then(r => r.json()).catch(() => null),
        fetch('api/forms.php?action=shift_stats').then(r => r.json()).catch(() => null)
    ])
    .then(results => {
        const [safeRes, formRes, debtRes, matRes, shiftStatsRes] = results.map(r => r.value ?? null);

        if (safeRes?.status === 'success') {
            state.safes        = safeRes.safes;
            state.transactions = safeRes.transactions;
        }
        if (formRes?.status === 'success')        state.forms      = formRes.data;
        if (debtRes?.status === 'success')        state.debtStats  = debtRes.stats;
        if (matRes?.status === 'success')         state.materials  = matRes.materials;
        if (shiftStatsRes?.status === 'success')  state.shiftStats = shiftStatsRes;

        updateStatistics();
    })
    .catch(err => console.error("Dashboard load failure:", err));
}

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

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

// -------------------------------------------------------------
// 6. Statistics
// -------------------------------------------------------------
function updateStatistics() {
    const currentWorkDay = getWorkDayDate(new Date());
    const cur  = getCurrency();
    const txs  = state.transactions || [];
    const safes = state.safes || [];
    const ss = state.shiftStats || {};

    // ── 1. النقدي (الخزائن) ──
    const totalCash = ss.total_cash || 0;
    if (dom.statCash) dom.statCash.textContent = `${formatCurrency(totalCash)} ${cur}`;

    // ── 2. ديون مستحقة ──
    const totalDebts = ss.total_outstanding_debts || 0;
    if (dom.statDebts) dom.statDebts.textContent = `${formatCurrency(totalDebts)} ${cur}`;

    // ── 2.5 ديون اليوم (الاستمارات) ──
    const shiftDebts = ss.today_invoice_debts || 0;
    if (dom.statShiftDebts) dom.statShiftDebts.textContent = `${formatCurrency(shiftDebts)} ${cur}`;

    // ── 3. استلام الديون ──
    const totalRepayments = ss.total_shift_repayments || 0;
    if (dom.statRepayments) dom.statRepayments.textContent = `${formatCurrency(totalRepayments)} ${cur}`;

    // ── 8. المبيعات — مجموع المبيعات حسب النوع ──
    const totalSales = ss.total_sales || 0;
    if (dom.statSales) dom.statSales.textContent = `${formatCurrency(totalSales)} ${cur}`;

    // ── إحصائيات الوردية من API ──
    animateCount(dom.statFormsTotal,    ss.total_forms    || 0);
    animateCount(dom.statActiveForms,   ss.active_forms   || 0);
    animateCount(dom.statInactiveForms, ss.inactive_forms || 0);
    if (dom.statBags) dom.statBags.textContent = `${formatCurrency(ss.bags_count || 0)} ${cur}`;
    if (dom.statBala) dom.statBala.textContent = `${formatCurrency(ss.bala_revenue || 0)} ${cur}`;

    if (dom.statCommission10) dom.statCommission10.textContent = `${formatCurrency(ss.total_commission_10 || 0)} ${cur}`;
    if (dom.statWorkerShift)  dom.statWorkerShift.textContent  = `${formatCurrency(ss.total_worker_share  || 0)} ${cur}`;
}

// أنيميشن عداد رقمي
function animateCount(el, target) {
    if (!el) return;
    const currentVal = parseInt(el.textContent.replace(/,/g, '')) || 0;
    if (currentVal === target) return; // No change, do nothing
    
    const steps = 30;
    let step = 0;
    const diff = target - currentVal;
    const inc = diff / steps;
    const timer = setInterval(() => {
        step++;
        const current = step >= steps ? target : Math.round(currentVal + (step * inc));
        el.textContent = current.toLocaleString('en-US');
        if (step >= steps) clearInterval(timer);
    }, 600 / steps);
}

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

function getWorkDayStartHour() {
    try { return parseInt(JSON.parse(localStorage.getItem("dashboard_settings") || '{}').workDayStartHour ?? 5); }
    catch (e) { return 5; }
}

function getWorkDayDate(dateInput) {
    const d = new Date(dateInput);
    if (isNaN(d.getTime())) return dateInput;
    if (typeof dateInput === 'string' && !dateInput.includes('T') && !dateInput.includes(':')) return dateInput;
    const startHour = getWorkDayStartHour();
    const adjusted = new Date(d.getTime() - (startHour * 60 * 60 * 1000));
    const y = adjusted.getFullYear();
    const m = String(adjusted.getMonth() + 1).padStart(2, '0');
    const day = String(adjusted.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
}

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

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

// -------------------------------------------------------------
// 8. Event Listeners
// -------------------------------------------------------------
function setupEventListeners() {
    if (dom.themeToggle) dom.themeToggle.addEventListener("click", toggleTheme);

    // Worker Share Modal listeners
    if (dom.cardWorkerShare) dom.cardWorkerShare.addEventListener("click", openWorkerShareModal);
    if (dom.closeWorkerModalBtn) dom.closeWorkerModalBtn.addEventListener("click", closeWorkerShareModal);
    if (dom.closeWorkerModalBtnFooter) dom.closeWorkerModalBtnFooter.addEventListener("click", closeWorkerShareModal);

    // Sales Modal listeners
    if (dom.cardSales) dom.cardSales.addEventListener("click", openSalesModal);
    if (dom.closeSalesModalBtn) dom.closeSalesModalBtn.addEventListener("click", closeSalesModal);
    if (dom.closeSalesModalBtnFooter) dom.closeSalesModalBtnFooter.addEventListener("click", closeSalesModal);

    // Bala Modal listeners
    if (dom.cardBala) dom.cardBala.addEventListener("click", openBalaModal);
    if (dom.closeBalaModalBtn) dom.closeBalaModalBtn.addEventListener("click", closeBalaModal);
    if (dom.closeBalaModalBtnFooter) dom.closeBalaModalBtnFooter.addEventListener("click", closeBalaModal);

    // Bags Modal listeners
    if (dom.cardBags) dom.cardBags.addEventListener("click", openBagsModal);
    if (dom.closeBagsModalBtn) dom.closeBagsModalBtn.addEventListener("click", closeBagsModal);
    if (dom.closeBagsModalBtnFooter) dom.closeBagsModalBtnFooter.addEventListener("click", closeBagsModal);

    // Today's Debts Modal listeners
    if (dom.cardShiftDebts) dom.cardShiftDebts.addEventListener("click", openTodayDebtsModal);
    if (dom.closeTodayDebtsModalBtn) dom.closeTodayDebtsModalBtn.addEventListener("click", closeTodayDebtsModal);
    if (dom.closeTodayDebtsModalBtnFooter) dom.closeTodayDebtsModalBtnFooter.addEventListener("click", closeTodayDebtsModal);

    // Today's Cash Forms Modal listeners
    if (dom.cardCashStats) dom.cardCashStats.addEventListener("click", openTodayCashModal);
    if (dom.closeTodayCashModalBtn) dom.closeTodayCashModalBtn.addEventListener("click", closeTodayCashModal);
    if (dom.closeTodayCashModalBtnFooter) dom.closeTodayCashModalBtnFooter.addEventListener("click", closeTodayCashModal);

    window.addEventListener("click", (e) => {
        if (e.target === dom.workerShareModal) {
            closeWorkerShareModal();
        }
        if (e.target === dom.salesModal) {
            closeSalesModal();
        }
        if (e.target === dom.balaModal) {
            closeBalaModal();
        }
        if (e.target === dom.bagsModal) {
            closeBagsModal();
        }
        if (e.target === dom.todayDebtsModal) {
            closeTodayDebtsModal();
        }
        if (e.target === dom.todayCashFormsModal) {
            closeTodayCashModal();
        }
    });

    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeWorkerShareModal();
            closeSalesModal();
            closeBalaModal();
            closeBagsModal();
            closeTodayDebtsModal();
            closeTodayCashModal();
        }
    });
}

// ── Worker Share Breakdown Modal Actions ──
function openWorkerShareModal() {
    if (!dom.workerShareModal) return;

    const listContainer = dom.workerShareGroupsList;
    if (listContainer) {
        const cur = getCurrency();
        const groups = (state.shiftStats && state.shiftStats.worker_share_groups) || [];

        if (groups.length === 0) {
            listContainer.innerHTML = `
                <div style="text-align:center; padding:30px 20px; color:var(--text-secondary);">
                    <i class="fa-solid fa-circle-info" style="font-size:32px; color:var(--text-muted); margin-bottom:10px;"></i>
                    <p>لا توجد بيانات لمجموعات حق العامل في هذه الوردية</p>
                </div>`;
        } else {
            listContainer.innerHTML = groups.map(group => `
                <div style="display:flex; justify-content:space-between; align-items:center; padding:12px 16px; background:var(--bg-input); border-radius:var(--radius-md); border:1.5px solid var(--border-color); transition:var(--transition);"
                     onmouseover="this.style.borderColor='var(--primary)'"
                     onmouseout="this.style.borderColor='var(--border-color)'">
                    <span style="font-weight:700; color:var(--text-primary); display:flex; align-items:center; gap:8px;">
                        <i class="fa-solid fa-hard-hat" style="color:var(--primary);"></i>
                        ${escapeHTML(group.type)}
                    </span>
                    <span style="font-weight:800; color:var(--success); font-size:15px; background:var(--success-light); padding:4px 12px; border-radius:20px;">
                        ${formatCurrency(group.amount)} ${cur}
                    </span>
                </div>
            `).join('');
        }
    }

    dom.workerShareModal.classList.add("open");
}

function closeWorkerShareModal() {
    if (dom.workerShareModal) {
        dom.workerShareModal.classList.remove("open");
    }
}

// ── Sales Breakdown Modal Actions ──
function openSalesModal() {
    if (!dom.salesModal) return;

    const listContainer = dom.salesGroupsList;
    if (listContainer) {
        const cur = getCurrency();
        const items = (state.shiftStats && state.shiftStats.sales_items) || [];

        const weightItems = items.filter(i => i.accounting_type === 'وزن * سعر');

        let html = '';

        html += `
            <div style="margin-bottom:12px; font-weight:800; color:var(--text-primary); font-size:14px; display:flex; align-items:center; gap:6px;">
                <i class="fa-solid fa-weight-hanging" style="color:var(--success); margin-left:6px;"></i>
                <span>تفاصيل مبيعات الوزن (الوزن * سعر):</span>
            </div>
        `;

        if (weightItems.length === 0) {
            html += `
                <div style="text-align:center; padding:30px 20px; color:var(--text-secondary); background:var(--bg-input); border-radius:var(--radius-md); border:1.5px solid var(--border-color);">
                    <i class="fa-solid fa-circle-info" style="font-size:32px; color:var(--text-muted); margin-bottom:10px;"></i>
                    <p>لا توجد مبيعات بالوزن في هذه الوردية</p>
                </div>
            `;
        } else {
            // Group by price
            const grouped = {};
            weightItems.forEach(item => {
                const price = Math.round(item.price);
                if (!grouped[price]) {
                    grouped[price] = {
                        totalWeight: 0,
                        totalAmount: 0
                    };
                }
                grouped[price].totalWeight += item.weight;
                grouped[price].totalAmount += item.total;
            });

            html += `<div style="display:flex; flex-direction:column; gap:10px; margin-bottom:15px;">`;
            Object.keys(grouped).forEach(price => {
                const group = grouped[price];
                html += `
                    <div style="padding:14px 18px; background:var(--bg-input); border-radius:var(--radius-md); border:1.5px solid var(--border-color); display:flex; justify-content:space-between; align-items:center; transition:var(--transition);"
                         onmouseover="this.style.borderColor='var(--success)'"
                         onmouseout="this.style.borderColor='var(--border-color)'">
                        <span style="font-weight:700; color:var(--text-primary); font-size:14px; display:flex; align-items:center; gap:8px;">
                            <i class="fa-solid fa-calculator" style="color:var(--success); margin-left:2px;"></i>
                            وزن * ${formatCurrency(price)} <span style="color:var(--success); font-weight:800;">(${group.totalWeight.toLocaleString('en-US', {minimumFractionDigits:0, maximumFractionDigits:2})})</span>
                        </span>
                        <span style="font-weight:900; color:var(--success); font-size:16px;">
                            ${formatCurrency(group.totalAmount)} ${cur}
                        </span>
                    </div>
                `;
            });
            html += `</div>`;

            // Calculate total weight sales
            const totalWeightSales = weightItems.reduce((sum, item) => sum + item.total, 0);
            html += `
                <div style="margin-top:10px; padding:12px 16px; background:rgba(16,185,129,0.08); border-radius:var(--radius-lg); display:flex; justify-content:space-between; align-items:center; border: 1.5px dashed var(--success);">
                    <span style="font-weight:800; color:var(--success); font-size:13px;">
                        <i class="fa-solid fa-calculator" style="margin-left:6px;"></i>مجموع (الوزن * السعر):
                    </span>
                    <span style="font-weight:900; color:var(--success); font-size:16px;">
                        ${formatCurrency(totalWeightSales)} ${cur}
                    </span>
                </div>
            `;
        }

        listContainer.innerHTML = html;
    }

    dom.salesModal.classList.add("open");
}

function closeSalesModal() {
    if (dom.salesModal) {
        dom.salesModal.classList.remove("open");
    }
}

// ── Bala Breakdown Modal Actions ──
function openBalaModal() {
    if (!dom.balaModal) return;

    const listContainer = dom.balaGroupsList;
    if (listContainer) {
        const cur = getCurrency();
        const items = (state.shiftStats && state.shiftStats.sales_items) || [];

        const qtyItems = items.filter(i => i.accounting_type !== 'وزن * سعر');

        let html = '';

        html += `
            <div style="margin-bottom:12px; font-weight:800; color:var(--text-primary); font-size:14px; display:flex; align-items:center; gap:6px;">
                <i class="fa-solid fa-layer-group" style="color:#a855f7; margin-left:6px;"></i>
                <span>تفاصيل مبيعات العدد (بلا - العدد * سعر):</span>
            </div>
        `;

        if (qtyItems.length === 0) {
            html += `
                <div style="text-align:center; padding:30px 20px; color:var(--text-secondary); background:var(--bg-input); border-radius:var(--radius-md); border:1.5px solid var(--border-color);">
                    <i class="fa-solid fa-circle-info" style="font-size:32px; color:var(--text-muted); margin-bottom:10px;"></i>
                    <p>لا توجد مبيعات بالعدد في هذه الوردية</p>
                </div>
            `;
        } else {
            // Group by price
            const grouped = {};
            qtyItems.forEach(item => {
                const price = Math.round(item.price);
                if (!grouped[price]) {
                    grouped[price] = {
                        totalQty: 0,
                        totalAmount: 0
                    };
                }
                grouped[price].totalQty += item.quantity;
                grouped[price].totalAmount += item.total;
            });

            html += `<div style="display:flex; flex-direction:column; gap:10px; margin-bottom:15px;">`;
            Object.keys(grouped).forEach(price => {
                const group = grouped[price];
                html += `
                    <div style="padding:14px 18px; background:var(--bg-input); border-radius:var(--radius-md); border:1.5px solid var(--border-color); display:flex; justify-content:space-between; align-items:center; transition:var(--transition);"
                         onmouseover="this.style.borderColor='#a855f7'"
                         onmouseout="this.style.borderColor='var(--border-color)'">
                        <span style="font-weight:700; color:var(--text-primary); font-size:14px; display:flex; align-items:center; gap:8px;">
                            <i class="fa-solid fa-calculator" style="color:#a855f7; margin-left:2px;"></i>
                            عدد * ${formatCurrency(price)} <span style="color:#a855f7; font-weight:800;">(${group.totalQty})</span>
                        </span>
                        <span style="font-weight:900; color:#a855f7; font-size:16px;">
                            ${formatCurrency(group.totalAmount)} ${cur}
                        </span>
                    </div>
                `;
            });
            html += `</div>`;

            // Calculate total quantity sales (Bala)
            const totalQtySales = qtyItems.reduce((sum, item) => sum + item.total, 0);
            html += `
                <div style="margin-top:10px; padding:12px 16px; background:rgba(168,85,247,0.08); border-radius:var(--radius-lg); display:flex; justify-content:space-between; align-items:center; border: 1.5px dashed #a855f7;">
                    <span style="font-weight:800; color:#a855f7; font-size:13px;">
                        <i class="fa-solid fa-calculator" style="margin-left:6px;"></i>مجموع (العدد * السعر):
                    </span>
                    <span style="font-weight:900; color:#a855f7; font-size:16px;">
                        ${formatCurrency(totalQtySales)} ${cur}
                    </span>
                </div>
            `;
        }

        listContainer.innerHTML = html;
    }

    dom.balaModal.classList.add("open");
}

function closeBalaModal() {
    if (dom.balaModal) {
        dom.balaModal.classList.remove("open");
    }
}

function openBagsModal() {
    if (!dom.bagsModal) return;

    const listContainer = dom.bagsGroupsList;
    if (listContainer) {
        const cur = getCurrency();
        const groups = (state.shiftStats && state.shiftStats.commission_groups) || [];

        // Clean and aggregate commission groups without percentage addition parts (e.g. 10%, 20%, etc.)
        const cleanedGroupsMap = {};
        groups.forEach(group => {
            let cleanedType = group.type
                .replace(/(?:إضافة|اضافة)?\s*\d+(?:\.\d+)?%\s*\+\s*/gi, '')
                .replace(/\s*\+\s*(?:إضافة|اضافة)?\s*\d+(?:\.\d+)?%/gi, '')
                .trim();
            
            if (/^(?:إضافة|اضافة)?\s*\d+(?:\.\d+)?%$/i.test(cleanedType) || cleanedType === '') {
                return; // ignore pure percentage addition
            }

            if (!cleanedGroupsMap[cleanedType]) {
                cleanedGroupsMap[cleanedType] = {
                    amount: 0,
                    qty: 0
                };
            }
            cleanedGroupsMap[cleanedType].amount += group.amount;
            cleanedGroupsMap[cleanedType].qty += (group.qty || 0);
        });

        // Convert map back to list
        const cleanedGroups = Object.keys(cleanedGroupsMap).map(type => ({
            type: type,
            amount: cleanedGroupsMap[type].amount,
            qty: cleanedGroupsMap[type].qty
        }));

        if (cleanedGroups.length === 0) {
            listContainer.innerHTML = `
                <div style="text-align:center; padding:30px 20px; color:var(--text-secondary);">
                    <i class="fa-solid fa-circle-info" style="font-size:32px; color:var(--text-muted); margin-bottom:10px;"></i>
                    <p>لا توجد بيانات لمجموعات العمولة في هذه الوردية</p>
                </div>`;
        } else {
            listContainer.innerHTML = cleanedGroups.map(group => `
                <div style="display:flex; justify-content:space-between; align-items:center; padding:12px 16px; background:var(--bg-input); border-radius:var(--radius-md); border:1.5px solid var(--border-color); transition:var(--transition);"
                     onmouseover="this.style.borderColor='var(--warning)'"
                     onmouseout="this.style.borderColor='var(--border-color)'">
                     <span style="font-weight:700; color:var(--text-primary); display:flex; align-items:center; gap:8px;">
                        <i class="fa-solid fa-bag-shopping" style="color:var(--warning);"></i>
                        ${escapeHTML(group.type)} <span style="color:var(--warning); font-weight:800;">(${group.qty})</span>
                    </span>
                    <span style="font-weight:800; color:var(--warning); font-size:15px; background:var(--warning-light); padding:4px 12px; border-radius:20px;">
                        ${formatCurrency(group.amount)} ${cur}
                    </span>
                </div>
            `).join('');
        }
    }

    dom.bagsModal.classList.add("open");
}

function closeBagsModal() {
    if (dom.bagsModal) {
        dom.bagsModal.classList.remove("open");
    }
}

// ── Today's Invoices Debts Modal Actions ──
function openTodayDebtsModal() {
    if (!dom.todayDebtsModal) return;

    const tableBody = document.getElementById("today-debts-list-table-body");
    if (tableBody) {
        const cur = getCurrency();
        const list = (state.shiftStats && state.shiftStats.today_invoice_debts_list) || [];

        if (list.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="6" style="text-align:center; padding:30px 20px; color:var(--text-secondary);">
                        <div style="font-size:32px; color:var(--text-muted); margin-bottom:10px;"><i class="fa-solid fa-circle-info"></i></div>
                        <p>لا توجد ديون استمارات منشأة اليوم</p>
                    </td>
                </tr>`;
        } else {
            tableBody.innerHTML = list.map(item => {
                let rowBg = "";
                let hoverBg = "";
                if (item.remaining_amount <= 0.01) {
                    rowBg = "rgba(16, 185, 129, 0.08)"; // Subtle green
                    hoverBg = "rgba(16, 185, 129, 0.14)";
                } else if (item.paid_amount > 0.01) {
                    rowBg = "rgba(245, 158, 11, 0.08)"; // Subtle orange
                    hoverBg = "rgba(245, 158, 11, 0.14)";
                } else {
                    rowBg = "rgba(239, 68, 68, 0.08)"; // Subtle red
                    hoverBg = "rgba(239, 68, 68, 0.14)";
                }

                return `
                <tr style="border-bottom:1px solid var(--border-color); color:var(--text-primary); background:${rowBg}; transition:var(--transition);"
                    onmouseover="this.style.background='${hoverBg}'"
                    onmouseout="this.style.background='${rowBg}'">
                    <td style="padding:12px 10px; font-weight:700;">#${escapeHTML(String(item.id))}</td>
                    <td style="padding:12px 10px;">${escapeHTML(item.customer_name)}</td>
                    <td style="padding:12px 10px; text-align:left; font-weight:700;">${formatCurrency(item.grand_total)} ${cur}</td>
                    <td style="padding:12px 10px; text-align:left; color:var(--success); font-weight:700;">${formatCurrency(item.paid_amount)} ${cur}</td>
                    <td style="padding:12px 10px; text-align:left; color:var(--danger); font-weight:700;">${formatCurrency(item.remaining_amount)} ${cur}</td>
                    <td style="padding:12px 10px; text-align:center;">
                        <button class="btn btn-primary" style="font-size:11px; padding:6px 12px; border-radius:var(--radius-sm);" onclick="window.location.href='forms.php?formId=${item.id}'">
                            <i class="fa-solid fa-eye"></i> عرض
                        </button>
                    </td>
                </tr>
                `;
            }).join('');
        }
    }

    dom.todayDebtsModal.classList.add("open");
}

function closeTodayDebtsModal() {
    if (dom.todayDebtsModal) {
        dom.todayDebtsModal.classList.remove("open");
    }
}

// ── Today's Cash Forms Modal Actions ──
function openTodayCashModal() {
    if (!dom.todayCashFormsModal) return;

    const tableBody = document.getElementById("today-cash-list-table-body");
    if (tableBody) {
        const cur = getCurrency();
        const list = (state.shiftStats && state.shiftStats.today_forms_list) || [];

        if (list.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="6" style="text-align:center; padding:30px 20px; color:var(--text-secondary);">
                        <div style="font-size:32px; color:var(--text-muted); margin-bottom:10px;"><i class="fa-solid fa-circle-info"></i></div>
                        <p>لا توجد استمارات مسجلة اليوم</p>
                    </td>
                </tr>`;
        } else {
            tableBody.innerHTML = list.map(item => {
                let rowBg = "";
                let hoverBg = "";
                if (item.remaining_amount <= 0.01) {
                    rowBg = "rgba(16, 185, 129, 0.08)"; // Subtle green
                    hoverBg = "rgba(16, 185, 129, 0.14)";
                } else if (item.paid_amount > 0.01) {
                    rowBg = "rgba(245, 158, 11, 0.08)"; // Subtle orange
                    hoverBg = "rgba(245, 158, 11, 0.14)";
                } else {
                    rowBg = "rgba(239, 68, 68, 0.08)"; // Subtle red
                    hoverBg = "rgba(239, 68, 68, 0.14)";
                }

                return `
                <tr style="border-bottom:1px solid var(--border-color); color:var(--text-primary); background:${rowBg}; transition:var(--transition);"
                    onmouseover="this.style.background='${hoverBg}'"
                    onmouseout="this.style.background='${rowBg}'">
                    <td style="padding:12px 10px; font-weight:700;">#${escapeHTML(String(item.id))}</td>
                    <td style="padding:12px 10px;">${escapeHTML(item.customer_name)}</td>
                    <td style="padding:12px 10px; text-align:left; font-weight:700;">${formatCurrency(item.grand_total)} ${cur}</td>
                    <td style="padding:12px 10px; text-align:left; color:var(--success); font-weight:700;">${formatCurrency(item.paid_amount)} ${cur}</td>
                    <td style="padding:12px 10px; text-align:left; color:var(--danger); font-weight:700;">${formatCurrency(item.remaining_amount)} ${cur}</td>
                    <td style="padding:12px 10px; text-align:center;">
                        <button class="btn btn-primary" style="font-size:11px; padding:6px 12px; border-radius:var(--radius-sm);" onclick="window.location.href='forms.php?formId=${item.id}'">
                            <i class="fa-solid fa-eye"></i> عرض
                        </button>
                    </td>
                </tr>
                `;
            }).join('');
        }
    }

    dom.todayCashFormsModal.classList.add("open");
}

function closeTodayCashModal() {
    if (dom.todayCashFormsModal) {
        dom.todayCashFormsModal.classList.remove("open");
    }
}
