// Business Logic and UI Interactions for Forms (الاستمارات) Page
// ✅ Connected to MySQL Database via api/forms.php

// -------------------------------------------------------------
// 1. App State
// -------------------------------------------------------------
let state = {
    forms: [],
    filteredForms: [],
    currentPage: 1,
    entriesPerPage: 6,
    searchTerm: "",
    deleteTargetId: null,
    currentActiveFormId: null,
    viewMode: "current", // default to current shift/day
    selectedFormIds: new Set()
};

// -------------------------------------------------------------
// 2. DOM Elements Selection
// -------------------------------------------------------------
const dom = {
    cardsContainer: document.getElementById("forms-cards-container"),
    emptyState: document.getElementById("empty-state-view"),

    // 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"),
    statTotalMaterials: document.getElementById("stat-total-materials"),
    statAvgMaterials: document.getElementById("stat-avg-materials"),

    // Pagination
    paginationInfo: document.getElementById("pagination-info-text"),
    paginationControls: document.getElementById("pagination-controls"),

    // Modals
    formModal: document.getElementById("form-modal"),
    deleteConfirmModal: document.getElementById("delete-confirm-modal"),

    // Form
    customerForm: document.getElementById("customer-form"),
    formIdInput: document.getElementById("form-id"),
    customerNameInput: document.getElementById("customer-name"),
    materialsCountInput: document.getElementById("materials-count"),
    statusSelect: document.getElementById("form-status"),
    modalTitle: document.getElementById("modal-title"),

    // Validation Errors
    nameError: document.getElementById("name-error"),

    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"),

    // Purchase List Modal
    purchaseModal: document.getElementById("purchase-list-modal"),
    closePurchaseModalBtn: document.getElementById("close-purchase-modal-btn"),
    closePurchaseModalBtnFooter: document.getElementById("close-purchase-modal-btn-footer"),
    purchaseMetaSerial: document.getElementById("purchase-meta-serial"),
    purchaseMetaName: document.getElementById("purchase-meta-name"),
    purchaseMetaDatetime: document.getElementById("purchase-meta-datetime"),
    purchaseItemsTbody: document.getElementById("purchase-items-tbody"),
    purchaseItemsEmpty: document.getElementById("purchase-items-empty"),
    purchaseGrandTotal:      document.getElementById("purchase-grand-total"),
    purchaseWorkerTotal:     document.getElementById("purchase-worker-total"),
    purchaseCommissionTotal: document.getElementById("purchase-commission-total"),
    purchaseCommission10Total: document.getElementById("purchase-commission-10-total"),

    // Purchase Item Slide-down Form
    purchaseItemFormContainer: document.getElementById("purchase-item-form-container"),
    purchaseItemForm: document.getElementById("purchase-item-form"),
    purchaseItemIdInput: document.getElementById("purchase-item-id"),
    purchaseItemNameInput: document.getElementById("p-item-name"),
    purchaseItemQuantityInput: document.getElementById("p-item-quantity"),
    purchaseItemWeightInput: document.getElementById("p-item-weight"),
    purchaseItemPriceInput: document.getElementById("p-item-price"),
    addPurchaseItemBtn: document.getElementById("add-purchase-item-btn"),
    cancelPurchaseItemBtn: document.getElementById("cancel-p-item-btn"),
    purchaseItemError: document.getElementById("p-item-error"),
    itemFormTitle: document.getElementById("item-form-title"),

    // Surplus elements
    surplusWarningContainer: document.getElementById("surplus-warning-container"),
    surplusPaidAmount: document.getElementById("surplus-paid-amount"),
    surplusGrandTotal: document.getElementById("surplus-grand-total"),
    surplusDiffAmount: document.getElementById("surplus-diff-amount"),
    btnRefundCash: document.getElementById("btn-refund-cash"),
    refundFormSub: document.getElementById("refund-form-sub"),
    refundSafeSelect: document.getElementById("refund-safe-select"),
    refundDate: document.getElementById("refund-date"),
    refundDesc: document.getElementById("refund-desc"),
    btnConfirmRefund: document.getElementById("btn-confirm-refund"),
    btnCancelRefund: document.getElementById("btn-cancel-refund"),
    surplusActionButtons: document.getElementById("surplus-action-buttons"),
    refundPurchaseBtn: document.getElementById("refund-purchase-btn")
};

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. App Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    initTheme();
    setupEventListeners();

    // Sync header banner setting
    fetch('api/settings.php?action=get')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.settings && res.settings.headerBanner) {
                localStorage.setItem("header_banner_path", res.settings.headerBanner);
            }
        })
        .catch(() => {});

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

    loadData(true);

    // Auto-refresh forms every 3 seconds silently in the background
    setInterval(() => {
        checkSystemStateAndRefresh(['forms'], () => loadData(false));
    }, 3000);

    // Deep Linking: open form details directly via URL ?formId=X or ?open_form=X
    const urlParams = new URLSearchParams(window.location.search);
    const formIdParam = urlParams.get('formId') || urlParams.get('open_form');
    if (formIdParam) {
        setTimeout(() => {
            if (typeof window.openPurchaseListModal === 'function') {
                window.openPurchaseListModal(formIdParam);
            }
        }, 600);
    }
});

// -------------------------------------------------------------
// 4. Data Loading from Database
// -------------------------------------------------------------
let lastFormsJson = "";

function loadData(force = false) {
    const shiftParam = state.viewMode === 'current' ? '&shift_only=1' : '';
    fetch('api/forms.php?action=list' + shiftParam + '&_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                const formsJson = JSON.stringify(res.data);
                let changed = (formsJson !== lastFormsJson) || force;
                
                if (changed) {
                    lastFormsJson = formsJson;
                    state.forms = res.data;
                    if (state.viewMode === 'previous') {
                        populateShiftDropdown();
                    }
                    applyFilters();
                }
                
                // If a form detail modal is open, also refresh its items (silently)
                if (state.currentActiveFormId && typeof window.renderPurchaseItems === 'function') {
                    window.renderPurchaseItems(true);
                }
            } else if (force) {
                showToast(res.message || 'فشل تحميل البيانات', 'danger');
            }
        })
        .catch(() => {
            if (force) showToast('فشل الاتصال بالخادم', 'danger');
        });
}

// -------------------------------------------------------------
// 5. 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");
    }
}

// -------------------------------------------------------------
// 6. 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(), 3500);
}

// -------------------------------------------------------------
// 7. Statistics Calculations
// -------------------------------------------------------------
function updateStatistics() {
    const totalForms = state.filteredForms.length;
    dom.statTotal.textContent = totalForms;

    const totalMaterials = state.filteredForms.reduce((sum, f) => sum + parseInt(f.materialsCount || 0), 0);
    dom.statTotalMaterials.textContent = totalMaterials;

    const avgMaterials = totalForms > 0 ? (totalMaterials / totalForms).toFixed(1) : 0;
    dom.statAvgMaterials.textContent = avgMaterials;
}

function formatDateString(dateInput) {
    const d = new Date(dateInput);
    if (isNaN(d.getTime())) return "---";
    const year  = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day   = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

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

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 year = adjusted.getFullYear();
    const month = String(adjusted.getMonth() + 1).padStart(2, '0');
    const day = String(adjusted.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function populateShiftDropdown() {
    const shiftSelect = document.getElementById("filter-shift-select");
    if (!shiftSelect) return;

    const currentVal = shiftSelect.value || "";

    const shiftRange = getCurrentShiftRange();
    const previousForms = state.forms.filter(item => {
        const time = new Date(item.createdAt).getTime();
        return time < shiftRange.start || time >= shiftRange.end;
    });

    const shiftMap = new Map();
    previousForms.forEach(item => {
        const shiftDate = getWorkDayDate(item.createdAt);
        if (shiftDate && !shiftMap.has(shiftDate)) {
            const d = new Date(shiftDate + 'T00:00:00');
            let formatted = shiftDate;
            if (!isNaN(d.getTime())) {
                const dayName = d.toLocaleDateString('ar-IQ', { weekday: 'long' });
                formatted = `وردية يوم ${dayName} (${shiftDate})`;
            }
            shiftMap.set(shiftDate, formatted);
        }
    });

    const sortedDates = Array.from(shiftMap.keys()).sort((a, b) => b.localeCompare(a));

    let optionsHtml = '<option value="">-- كافة الورديات السابقة --</option>';
    sortedDates.forEach(dateStr => {
        optionsHtml += `<option value="${dateStr}">${shiftMap.get(dateStr)}</option>`;
    });

    shiftSelect.innerHTML = optionsHtml;
    if (currentVal && (sortedDates.includes(currentVal) || currentVal === '')) {
        shiftSelect.value = currentVal;
    } else {
        shiftSelect.value = "";
    }
}

window.onShiftSelectChange = function() {
    const shiftSelect = document.getElementById("filter-shift-select");
    const shiftDate = document.getElementById("filter-shift-date");
    if (shiftSelect && shiftDate) {
        shiftDate.value = shiftSelect.value;
    }
    state.currentPage = 1;
    applyFilters();
};

window.onShiftDateInputChange = function() {
    const shiftSelect = document.getElementById("filter-shift-select");
    const shiftDate = document.getElementById("filter-shift-date");
    if (shiftSelect && shiftDate) {
        shiftSelect.value = shiftDate.value;
    }
    state.currentPage = 1;
    applyFilters();
};

window.resetPreviousFilters = function() {
    const shiftSelect = document.getElementById("filter-shift-select");
    const shiftDate = document.getElementById("filter-shift-date");
    const paymentType = document.getElementById("filter-payment-type");

    if (shiftSelect) shiftSelect.value = "";
    if (shiftDate) shiftDate.value = "";
    if (paymentType) paymentType.value = "all";

    state.currentPage = 1;
    applyFilters();
};

// ── Handle Toggle between Current Shift Forms and Previous Days Forms ──
window.setViewMode = function(mode) {
    state.viewMode = mode;
    state.currentPage = 1;
    
    const btnCurrent = document.getElementById("btn-view-current");
    const btnPrevious = document.getElementById("btn-view-previous");
    const prevFiltersRow = document.getElementById("previous-filters-row");
    
    if (btnCurrent && btnPrevious) {
        if (mode === 'current') {
            btnCurrent.style.background = "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)";
            btnCurrent.style.color = "#fff";
            btnCurrent.style.border = "none";
            btnCurrent.style.boxShadow = "0 2px 8px rgba(217, 119, 6, 0.2)";
            
            btnPrevious.style.background = "var(--bg-input)";
            btnPrevious.style.color = "var(--text-secondary)";
            btnPrevious.style.border = "1.5px solid var(--border-color)";
            btnPrevious.style.boxShadow = "none";

            if (prevFiltersRow) prevFiltersRow.style.display = "none";
        } else {
            btnPrevious.style.background = "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)";
            btnPrevious.style.color = "#fff";
            btnPrevious.style.border = "none";
            btnPrevious.style.boxShadow = "0 2px 8px rgba(217, 119, 6, 0.2)";
            
            btnCurrent.style.background = "var(--bg-input)";
            btnCurrent.style.color = "var(--text-secondary)";
            btnCurrent.style.border = "1.5px solid var(--border-color)";
            btnCurrent.style.boxShadow = "none";

            if (prevFiltersRow) prevFiltersRow.style.display = "flex";
            populateShiftDropdown();
        }
    }
    
    loadData(true);
};

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

    const shiftSelect = document.getElementById("filter-shift-select");
    const shiftDateInput = document.getElementById("filter-shift-date");
    const selectedShift = (shiftSelect && shiftSelect.value) ? shiftSelect.value : ((shiftDateInput && shiftDateInput.value) ? shiftDateInput.value : "");

    const paymentTypeSelect = document.getElementById("filter-payment-type");
    const paymentType = paymentTypeSelect ? paymentTypeSelect.value : "all";

    // 1. Filter by viewMode (current shift vs previous days)
    let baseForms = [...state.forms];
    const shiftRange = getCurrentShiftRange();
    
    if (state.viewMode === 'current') {
        baseForms = baseForms.filter(item => {
            const time = new Date(item.createdAt).getTime();
            return time >= shiftRange.start && time < shiftRange.end;
        });
    } else {
        baseForms = baseForms.filter(item => {
            const time = new Date(item.createdAt).getTime();
            return time < shiftRange.start || time >= shiftRange.end;
        });

        // 1b. Filter by specific shift date in Previous Days view
        if (selectedShift) {
            baseForms = baseForms.filter(item => {
                const itemShiftDate = getWorkDayDate(item.createdAt);
                return itemShiftDate === selectedShift;
            });
        }
    }

    // 2. Filter by Payment / Status Type (All, New, Cash, Debt, Cancelled)
    if (paymentType === 'cash') {
        baseForms = baseForms.filter(item => {
            const totalPaid = parseFloat(item.totalPaid || 0);
            const grandTotal = parseFloat(item.grandTotal || 0);
            return item.status === '1' || (grandTotal > 0 && totalPaid >= (grandTotal - 0.01));
        });
    } else if (paymentType === 'debt') {
        baseForms = baseForms.filter(item => {
            const totalPaid = parseFloat(item.totalPaid || 0);
            const grandTotal = parseFloat(item.grandTotal || 0);
            const isCash = item.status === '1' || (grandTotal > 0 && totalPaid >= (grandTotal - 0.01));
            return item.status === '2' || (!isCash && item.status !== 'cancelled');
        });
    } else if (paymentType === 'new') {
        baseForms = baseForms.filter(item => {
            return item.status === '0' || item.status === 'normal' || item.status === 'new';
        });
    } else if (paymentType === 'cancelled') {
        baseForms = baseForms.filter(item => {
            return item.status === 'cancelled';
        });
    }

    // 3. Filter by Search Term & Update Badge
    let activeFilterDesc = [];
    if (selectedShift) {
        activeFilterDesc.push(`وردية ${selectedShift}`);
    }
    if (paymentType === 'cash') {
        activeFilterDesc.push('مسددة بالكامل');
    } else if (paymentType === 'debt') {
        activeFilterDesc.push('ديون');
    } else if (paymentType === 'new') {
        activeFilterDesc.push('استمارات جديدة');
    } else if (paymentType === 'cancelled') {
        activeFilterDesc.push('استمارات ملغاة');
    }

    if (state.searchTerm === "") {
        state.filteredForms = baseForms;
        if (dom.searchResultsBadge) {
            if (activeFilterDesc.length > 0) {
                dom.searchResultsBadge.style.display = "inline-block";
                dom.searchResultsBadge.textContent = `تصفية (${activeFilterDesc.join(' | ')}): ${state.filteredForms.length} استمارة`;
            } else {
                dom.searchResultsBadge.style.display = "none";
            }
        }
    } else {
        state.filteredForms = baseForms.filter(item =>
            item.customerName.toLowerCase().includes(state.searchTerm)
        );
        if (dom.searchResultsBadge) {
            dom.searchResultsBadge.style.display = "inline-block";
            activeFilterDesc.unshift(`بحث: "${state.searchTerm}"`);
            dom.searchResultsBadge.textContent = `نتائج (${activeFilterDesc.join(' | ')}): ${state.filteredForms.length} استمارة`;
        }
    }

    state.entriesPerPage = parseInt(dom.entriesSelect.value);
    const totalPages = Math.ceil(state.filteredForms.length / state.entriesPerPage);
    if (state.currentPage > totalPages) state.currentPage = totalPages || 1;

    renderCards();
    updateStatistics();
}

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

window.clearSearchForms = function() {
    if (dom.searchInput) dom.searchInput.value = "";
    resetPreviousFilters();
};

// -------------------------------------------------------------
// 9. Dynamic DOM Rendering (Cards Grid)
// -------------------------------------------------------------
function renderCards() {
    dom.cardsContainer.innerHTML = "";
    const list  = state.filteredForms;
    const total = list.length;

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

    dom.cardsContainer.style.display = "grid";
    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 status = item.status || "0";

        let pricingActionHtml = '';
        const isUnpricedStatus = (status === '0' || status === 'normal' || status === 'new' || status === 'جديد');
        if (isUnpricedStatus || parseInt(item.isSentToPricing) === 1) {
            if (parseInt(item.isSentToPricing) === 1) {
                pricingActionHtml = `
                    <button class="card-action-btn btn-pricing" onclick="event.stopPropagation(); window.open('pricing.php?form_id=${item.id}', '_blank')" title="تسعير الاستمارة (فتح صفحة التسعير)" style="color: #f59e0b;">
                        <i class="fa-solid fa-sack-dollar"></i>
                    </button>
                    <span class="pricing-status-badge" style="font-size:10px; font-weight:700; color:#fbbf24; background:rgba(245,158,11,0.08); padding:4px 8px; border-radius:10px; display:inline-flex; align-items:center; gap:4px; border:1px solid rgba(245,158,11,0.15); margin-left: 4px;" title="تم إرسالها للمسعر"><i class="fa-solid fa-clock-rotate-left"></i>مرسلة</span>
                `;
            } else {
                pricingActionHtml = `
                    <button class="card-action-btn btn-send-pricing" onclick="event.stopPropagation(); sendToPricing('${item.id}')" title="إرسال للتسعير" style="color: #3b82f6;">
                        <i class="fa-solid fa-paper-plane"></i>
                    </button>
                `;
            }
        }

        const statusLabels = { 
            '0': 'جديدة (0)', 
            '1': 'مسددة بالكامل',
            '2': 'متبقي دين',
            'normal': 'جديدة (0)', 
            'completed': 'مسددة بالكامل', 
            'partial': 'متبقي دين',
            'cancelled': 'ملغاة'
        };
        const statusLabel  = statusLabels[status] || 'جديدة (0)';
        const statusColors = {
            '0':         'rgba(99,102,241,0.12)',
            '1':         'rgba(16,185,129,0.12)',
            '2':         'rgba(245,158,11,0.12)',
            'normal':    'rgba(99,102,241,0.12)',
            'completed': 'rgba(16,185,129,0.12)',
            'partial':   'rgba(239,68,68,0.12)',
            'cancelled': 'rgba(239,68,68,0.12)'
        };
        const statusTextColors = {
            '0':         '#6366f1',
            '1':         '#10b981',
            '2':         '#f59e0b',
            'normal':    '#6366f1',
            'completed': '#10b981',
            'partial':   '#ef4444',
            'cancelled': '#ef4444'
        };

        const totalPaidAmount = parseFloat(item.totalPaid || 0);
        const grandTotalAmount = parseFloat(item.grandTotal || 0);
        const isPaidInFull = status === '1' || status === 'completed' || (grandTotalAmount > 0 && totalPaidAmount >= (grandTotalAmount - 0.01));
        const isPartialPaid = !isPaidInFull && totalPaidAmount > 0.01;

        let paymentBadgeText = 'ديون';
        let paymentBadgeBg = 'rgba(239,68,68,0.15)';
        let paymentBadgeColor = '#ef4444';
        let paymentBadgeIcon = 'fa-file-invoice-dollar';

        if (isPaidInFull) {
            paymentBadgeText = 'مسددة بالكامل';
            paymentBadgeBg = 'rgba(16,185,129,0.15)';
            paymentBadgeColor = '#10b981';
            paymentBadgeIcon = 'fa-circle-check';
        } else if (isPartialPaid) {
            paymentBadgeText = 'مسددة جزئياً';
            paymentBadgeBg = 'rgba(245,158,11,0.15)';
            paymentBadgeColor = '#d97706';
            paymentBadgeIcon = 'fa-clock-rotate-left';
        }

        const isSurplus = (totalPaidAmount > grandTotalAmount + 0.01);
        if (!state.selectedFormIds) state.selectedFormIds = new Set();
        const isChecked = state.selectedFormIds.has(String(item.id));
        const card = document.createElement("div");
        card.className = `customer-card status-${status}`;
        card.setAttribute('onclick', `openPurchaseListModal('${item.id}')`);
        card.innerHTML = `
            <div class="customer-card-header">
                <div class="customer-avatar-wrap">
                    <input type="checkbox" class="form-select-checkbox" value="${item.id}" ${isChecked ? 'checked' : ''} onchange="window.onFormCheckboxChange(event, '${item.id}')" onclick="event.stopPropagation()" style="width:18px; height:18px; cursor:pointer; accent-color:var(--primary);" title="تحديد الاستمارة للطباعة المجمعة" />
                    <div class="customer-avatar"><i class="fa-solid fa-file-signature"></i></div>
                    <div class="customer-name">${escapeHTML(item.customerName)}</div>
                </div>
                <div style="display:flex; align-items:center; gap:6px;">
                    ${isSurplus ? '<span class="surplus-badge" title="يوجد زيادة في المبالغ المدفوعة (فائض)" style="background:#10b981; color:white; width:22px; height:22px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:11px; animation: pulse-green 1.5s infinite;"><i class="fa-solid fa-hand-holding-dollar"></i></span>' : ''}
                    <div class="form-serial-badge">#${serial}</div>
                </div>
            </div>
            <div class="customer-card-body">
                <div class="info-item">
                    <span class="info-label">عدد المواد:</span>
                    <span class="info-value" style="color:var(--primary); font-size:15px; font-weight:700;">${item.materialsCount} مادة</span>
                </div>
                <div class="info-item">
                    <span class="info-label">حالة السداد:</span>
                    <span class="info-value">
                        <span style="display:inline-block;padding:2px 10px;border-radius:20px;font-size:11px;font-weight:800;background:${paymentBadgeBg};color:${paymentBadgeColor};">
                            <i class="fa-solid ${paymentBadgeIcon}" style="margin-left:3px;"></i>
                            ${paymentBadgeText}
                        </span>
                    </span>
                </div>
                <div class="info-item">
                    <span class="info-label">الحالة:</span>
                    <span class="info-value">
                        <span style="display:inline-block;padding:2px 10px;border-radius:20px;font-size:11px;font-weight:700;background:${statusColors[status]};color:${statusTextColors[status]};">
                            ${statusLabel}
                        </span>
                    </span>
                </div>
                <div class="info-item">
                    <span class="info-label">تاريخ الإنشاء:</span>
                    <span class="info-value"><i class="fa-regular fa-calendar" style="margin-left:4px;"></i>${formatDateString(item.createdAt)}</span>
                </div>
            </div>
            <div class="customer-card-actions">
                <button class="card-action-btn" onclick="event.stopPropagation(); openEditModal('${item.id}')" title="تعديل">
                    <i class="fa-solid fa-pen-to-square"></i>
                </button>
                <button class="card-action-btn" onclick="event.stopPropagation(); printCurrentForm('${item.id}')" title="طباعة الاستمارة" style="color:var(--primary);">
                    <i class="fa-solid fa-print"></i>
                </button>
                ${pricingActionHtml}
                <button class="card-action-btn btn-delete" onclick="event.stopPropagation(); openDeleteModal('${item.id}')" title="حذف">
                    <i class="fa-solid fa-trash-can"></i>
                </button>
            </div>
        `;
        dom.cardsContainer.appendChild(card);
    });

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

function renderPagination(totalItems) {
    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--; renderCards(); } });
    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; renderCards(); });
        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++; renderCards(); } });
    dom.paginationControls.appendChild(nextBtn);
}

// -------------------------------------------------------------
// 10. Modals Open / Close Control
// -------------------------------------------------------------
window.openEditModal = function(id) {
    const item = state.forms.find(x => x.id === id);
    if (!item) return;

    clearValidationErrors();
    dom.modalTitle.textContent = "تعديل بيانات الاستمارة";
    dom.formIdInput.value = item.id;
    dom.customerNameInput.value = item.customerName;
    if (dom.statusSelect) dom.statusSelect.value = item.status || "0";

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

function openAddModal() {
    clearValidationErrors();
    dom.modalTitle.textContent = "إضافة استمارة جديدة";
    dom.customerForm.reset();
    dom.formIdInput.value = "";
    if (dom.statusSelect) dom.statusSelect.value = "0";
    dom.formModal.classList.add("open");
}

function closeModal() {
    dom.formModal.classList.remove("open");
    dom.customerForm.reset();
    clearValidationErrors();
}

window.openDeleteModal = function(id) {
    const item = state.forms.find(x => x.id === id);
    if (!item) return;
    state.deleteTargetId = id;
    dom.deleteItemName.textContent = item.customerName;
    dom.deleteConfirmModal.classList.add("open");
};

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

// -------------------------------------------------------------
// 11. Form Validation & Submission
// -------------------------------------------------------------
function clearValidationErrors() {
    if (dom.customerNameInput) dom.customerNameInput.closest(".form-group").classList.remove("has-error");
}

function validateForm(name) {
    let isValid = true;
    clearValidationErrors();
    if (!name || name.trim().length < 2) {
        dom.customerNameInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }
    return isValid;
}

function handleFormSubmit(e) {
    e.preventDefault();

    const id     = dom.formIdInput.value;
    const name   = dom.customerNameInput.value.trim();
    const status = dom.statusSelect ? dom.statusSelect.value : "0";

    if (!validateForm(name)) {
        showToast("يرجى إدخال اسم الزبون بشكل صحيح", "warning");
        return;
    }

    const saveBtn = dom.customerForm.querySelector('[type="submit"]');
    if (saveBtn) { saveBtn.disabled = true; }

    fetch('api/forms.php?action=save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, customerName: name, status })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || 'تم الحفظ بنجاح');
            closeModal();
            loadData();
        } else {
            showToast(res.message || 'فشل الحفظ', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم', 'danger'))
    .finally(() => { if (saveBtn) saveBtn.disabled = false; });
}

window.sendToPricing = function(formId) {
    if (!formId) return;

    fetch('api/forms.php?action=send_to_pricing', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ form_id: parseInt(formId) })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || 'تم إرسال الاستمارة للتسعير بنجاح');
            loadData(true);
        } else {
            showToast(res.message || 'فشل إرسال الاستمارة للتسعير', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم', 'danger'));
};

window.sendSelectedFormsToPricing = function() {
    if (!state.selectedFormIds || state.selectedFormIds.size === 0) {
        showToast('يرجى تحديد استمارة واحدة على الأقل لإرسالها للتسعير', 'warning');
        return;
    }

    const formIds = Array.from(state.selectedFormIds);
    fetch('api/forms.php?action=send_to_pricing', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ form_ids: formIds })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || 'تم إرسال الاستمارات المحددة للتسعير بنجاح');
            state.selectedFormIds.clear();
            loadData(true);
        } else {
            showToast(res.message || 'فشل إرسال الاستمارات للتسعير', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم', 'danger'));
};

window.sendCurrentFormToPricing = function() {
    const formId = state.currentActiveFormId;
    if (!formId) return;

    const form = state.forms.find(f => f.id === formId);
    if (form && parseInt(form.isSentToPricing) === 1) {
        window.open(`pricing.php?form_id=${formId}`, '_blank');
        return;
    }

    sendToPricing(formId);
    if (dom.purchaseModal) dom.purchaseModal.classList.remove("open");
};

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

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

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

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

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

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

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

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

    dom.customerForm.addEventListener("submit", handleFormSubmit);

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

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

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

    dom.closePurchaseModalBtn.addEventListener("click", closePurchaseListModal);
    dom.closePurchaseModalBtnFooter.addEventListener("click", closePurchaseListModal);
    dom.addPurchaseItemBtn.addEventListener("click", () => toggleItemForm(true));
    dom.cancelPurchaseItemBtn.addEventListener("click", () => toggleItemForm(false));
    dom.purchaseItemForm.addEventListener("submit", savePurchaseItem);

    // Payment Form Listeners
    const payBtn = document.getElementById("pay-purchase-btn");
    if (payBtn) payBtn.addEventListener("click", () => togglePaymentForm(true));

    const cancelPaymentBtn = document.getElementById("cancel-payment-btn");
    if (cancelPaymentBtn) cancelPaymentBtn.addEventListener("click", () => togglePaymentForm(false));

    const paymentForm = document.getElementById("payment-form");
    if (paymentForm) paymentForm.addEventListener("submit", submitPaymentForm);

    // Format p-item-price with commas dynamically
    if (dom.purchaseItemPriceInput) {
        dom.purchaseItemPriceInput.addEventListener("input", function (e) {
            let cursorPosition = this.selectionStart;
            let originalLength = this.value.length;

            let value = this.value.replace(/,/g, '');
            let parts = value.split('.');
            parts[0] = parts[0].replace(/\D/g, '');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            
            if (parts.length > 1) {
                parts[1] = parts[1].replace(/\D/g, '').substring(0, 2);
                this.value = parts[0] + '.' + parts[1];
            } else {
                this.value = parts[0];
            }

            let newLength = this.value.length;
            cursorPosition = cursorPosition + (newLength - originalLength);
            this.setSelectionRange(cursorPosition, cursorPosition);
            if (window.liveCalcPreview) window.liveCalcPreview();
        });
    }

    // Format pay-amount with commas dynamically
    const payAmountInput = document.getElementById("pay-amount");
    if (payAmountInput) {
        payAmountInput.addEventListener("input", function (e) {
            let cursorPosition = this.selectionStart;
            let originalLength = this.value.length;

            let value = this.value.replace(/,/g, '');
            let parts = value.split('.');
            parts[0] = parts[0].replace(/\D/g, '');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            
            if (parts.length > 1) {
                parts[1] = parts[1].replace(/\D/g, '').substring(0, 2);
                this.value = parts[0] + '.' + parts[1];
            } else {
                this.value = parts[0];
            }

            let newLength = this.value.length;
            cursorPosition = cursorPosition + (newLength - originalLength);
            this.setSelectionRange(cursorPosition, cursorPosition);
        });
    }

    // Surplus/Refund action listeners
    if (dom.btnRefundCash) {
        dom.btnRefundCash.addEventListener("click", () => {
            dom.surplusActionButtons.style.display = "none";
            dom.refundFormSub.style.display = "block";
            loadRefundSafesDropdown();
            dom.refundDate.value = new Date().toISOString().split('T')[0];
            
            const form = state.forms.find(f => f.id === state.currentActiveFormId);
            const formIndex = state.forms.findIndex(f => f.id === state.currentActiveFormId);
            const formNumber = state.forms.length - formIndex;
            
            const grandTotal = parseFloat(dom.purchaseGrandTotal.textContent.replace(/[^\d.]/g, '')) || 0;
            const paidTotal = parseFloat(document.getElementById("purchase-paid-total").textContent.replace(/[^\d.]/g, '')) || 0;
            const surplusAmt = Math.abs(grandTotal - paidTotal);
            
            state.currentRefundAmount = surplusAmt;
            
            // Restore default text
            const titleElem = dom.surplusWarningContainer.querySelector("h5");
            if (titleElem) titleElem.innerHTML = `<i class="fa-solid fa-triangle-exclamation"></i> تنبيه: يوجد زيادة في المبالغ المدفوعة لهذه الاستمارة!`;
            
            const descElem = dom.surplusWarningContainer.querySelector("p");
            if (descElem) descElem.textContent = `المبلغ المدفوع سابقاً للاستمارة هو (${formatCurrency(paidTotal)} د.ع) بينما المجموع الكلي الحالي هو (${formatCurrency(grandTotal)} د.ع). الفارق المالي الزائد هو (${formatCurrency(surplusAmt)} د.ع).`;
            
            dom.refundDesc.value = `إرجاع فائض مالي للاستمارة رقم #${formNumber} للزبون: ${form ? form.customerName : ''} بقيمة: ${surplusAmt}`;
        });
    }

    if (dom.refundPurchaseBtn) {
        dom.refundPurchaseBtn.addEventListener("click", () => {
            dom.surplusWarningContainer.style.display = "block";
            dom.surplusActionButtons.style.display = "none";
            dom.refundFormSub.style.display = "block";
            loadRefundSafesDropdown();
            dom.refundDate.value = new Date().toISOString().split('T')[0];
            
            const form = state.forms.find(f => f.id === state.currentActiveFormId);
            const formIndex = state.forms.findIndex(f => f.id === state.currentActiveFormId);
            const formNumber = state.forms.length - formIndex;
            
            const paidTotal = parseFloat(document.getElementById("purchase-paid-total").textContent.replace(/[^\d.]/g, '')) || 0;
            state.currentRefundAmount = paidTotal;
            
            // Set refund text
            const titleElem = dom.surplusWarningContainer.querySelector("h5");
            if (titleElem) titleElem.innerHTML = `<i class="fa-solid fa-triangle-exclamation"></i> إجراء إرجاع مالي وتحويل للاستمارة إلى ديون`;
            
            const descElem = dom.surplusWarningContainer.querySelector("p");
            if (descElem) descElem.textContent = `قمت بطلب إرجاع المبلغ المدفوع سابقاً للاستمارة بقيمة (${formatCurrency(paidTotal)} د.ع). يرجى تعبئة حقول السحب أدناه لتسجيل الإرجاع في الصندوق وتحديث حالة الاستمارة إلى دين (حالة 2).`;
            
            dom.refundDesc.value = `إرجاع مالي كامل للاستمارة رقم #${formNumber} للزبون: ${form ? form.customerName : ''} بقيمة: ${paidTotal}`;
        });
    }

    if (dom.btnCancelRefund) {
        dom.btnCancelRefund.addEventListener("click", () => {
            dom.refundFormSub.style.display = "none";
            
            const grandTotal = parseFloat(dom.purchaseGrandTotal.textContent.replace(/[^\d.]/g, '')) || 0;
            const paidTotal = parseFloat(document.getElementById("purchase-paid-total").textContent.replace(/[^\d.]/g, '')) || 0;
            const remaining = grandTotal - paidTotal;
            
            if (remaining < -0.01) {
                dom.surplusActionButtons.style.display = "flex";
            } else {
                dom.surplusWarningContainer.style.display = "none";
            }
        });
    }

    if (dom.btnConfirmRefund) {
        dom.btnConfirmRefund.addEventListener("click", () => {
            const safeId = dom.refundSafeSelect.value;
            const date = dom.refundDate.value;
            const description = dom.refundDesc.value;
            const refundAmt = state.currentRefundAmount || 0;

            if (refundAmt <= 0) {
                showToast('المبلغ المراد إرجاعه يجب أن يكون أكبر من صفر', 'warning');
                return;
            }

            if (!safeId) {
                showToast('يرجى اختيار الصندوق المراد السحب منه', 'warning');
                return;
            }

            dom.btnConfirmRefund.disabled = true;
            fetch('api/forms.php?action=refund_surplus', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    form_id: state.currentActiveFormId,
                    safe_id: safeId,
                    amount: refundAmt,
                    date: date,
                    description: description
                })
            })
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    showToast(res.message);
                    dom.refundFormSub.style.display = "none";
                    dom.surplusWarningContainer.style.display = "none";
                    renderPurchaseItems();
                    loadData();
                } else {
                    showToast(res.message || 'فشلت العملية', 'danger');
                }
            })
            .catch(() => showToast('فشل الاتصال بالخادم', 'danger'))
            .finally(() => { dom.btnConfirmRefund.disabled = false; });
        });
    }

    function loadRefundSafesDropdown() {
        const select = dom.refundSafeSelect;
        if (!select) return;

        fetch('api/safes.php?action=list')
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success' && res.safes) {
                    select.innerHTML = '';
                    res.safes.forEach(safe => {
                        const option = document.createElement("option");
                        option.value = safe.id;
                        option.textContent = safe.name;
                        select.appendChild(option);
                    });
                }
            })
            .catch(() => {});
    }

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

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

// -------------------------------------------------------------
// 15. Purchase List Modal — DB-connected
// -------------------------------------------------------------
window.openPurchaseListModal = function(formId) {
    const form = state.forms.find(f => f.id === formId);
    if (!form) return;

    state.currentActiveFormId = formId;

    const formIndex  = state.forms.findIndex(f => f.id === formId);
    const formNumber = state.forms.length - formIndex;

    dom.purchaseMetaSerial.textContent = `#${formNumber}`;
    dom.purchaseMetaName.textContent   = form.customerName;
    dom.purchaseMetaDatetime.innerHTML = `<i class="fa-regular fa-calendar-days" style="margin-left:4px;"></i>${formatDateString(form.createdAt)} ${new Date(form.createdAt).toLocaleTimeString('en-US', { timeZone: 'Asia/Baghdad', hour: '2-digit', minute: '2-digit' })}`;

    const modalSendPricingText = document.getElementById("modal-send-pricing-text");
    const modalSendPricingBtn = document.getElementById("modal-send-pricing-btn");
    if (modalSendPricingText && modalSendPricingBtn) {
        if (parseInt(form.isSentToPricing) === 1) {
            modalSendPricingText.textContent = "فتح صفحة التسعير (مرسلة)";
            modalSendPricingBtn.title = "فتح صفحة تسعير الاستمارة";
            modalSendPricingBtn.style.background = "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)";
        } else {
            modalSendPricingText.textContent = "إرسال للتسعير";
            modalSendPricingBtn.title = "إرسال هذه الاستمارة لصفحة التسعير";
            modalSendPricingBtn.style.background = "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)";
        }
    }

    toggleItemForm(false);
    togglePaymentForm(false);
    lastItemsJson = "";
    renderPurchaseItems(); // will fetch from DB
    loadMaterialsDatalist(); // populate material name suggestions

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

// Load materials of the current shift into the select dropdown for autocomplete
function loadMaterialsDatalist() {
    const select = document.getElementById("p-item-name-select");
    if (!select) return;

    fetch('api/materials.php?action=list')
        .then(r => r.json())
        .then(res => {
            // Keep the first two fixed options
            select.innerHTML = `
                <option value="">-- اختر من مواد الوردية --</option>
                <option value="__manual__">✏️ إدخال اسم يدوي...</option>
            `;
            if (res.status === 'success' && res.materials && res.materials.length > 0) {
                state.materialsList = res.materials;
                // Insert material options before the manual option
                const manualOpt = select.querySelector('option[value="__manual__"]');
                const seenNames = new Set();
                res.materials.forEach(mat => {
                    if (mat.name) {
                        const nameTrimmed = mat.name.trim();
                        if (nameTrimmed && !seenNames.has(nameTrimmed)) {
                            seenNames.add(nameTrimmed);
                            const option = document.createElement("option");
                            option.value = nameTrimmed;
                            option.textContent = nameTrimmed;
                            select.insertBefore(option, manualOpt);
                        }
                    }
                });
            }
        })
        .catch(() => {}); // silent fail — still works manually
}

// Handle switching between select and manual text input
window.handleMaterialSelect = function(val) {
    const manualInput = document.getElementById("p-item-name");
    if (!manualInput) return;

    const accTypeInput = document.getElementById("p-item-accounting-type");
    const commTypeInput = document.getElementById("p-item-commission-type");
    const workerTypeInput = document.getElementById("p-item-worker-share-type");

    const pInfo = document.getElementById("p-item-material-info");
    const pAcc = document.getElementById("p-item-accounting-chip");
    const pComm = document.getElementById("p-item-commission-chip");
    const pWork = document.getElementById("p-item-worker-chip");

    const priceInput = document.getElementById("p-item-price");
    const weightInput = document.getElementById("p-item-weight");
    const weightCol = weightInput ? weightInput.closest("div").parentElement : null;

    if (val === "__manual__") {
        // Show manual text input
        manualInput.style.display = "block";
        manualInput.value = "";
        manualInput.focus();

        // Clear hidden & chips
        if (accTypeInput) accTypeInput.value = "";
        if (commTypeInput) commTypeInput.value = "";
        if (workerTypeInput) workerTypeInput.value = "";
        if (pInfo) pInfo.style.display = "none";
        if (priceInput) priceInput.value = "";
        if (weightCol) weightCol.style.display = "block";
        if (weightInput) weightInput.setAttribute("required", "true");
    } else {
        // Hide manual input and use selected value
        manualInput.style.display = "none";
        manualInput.value = val;

        // Lookup material in state
        const mat = state.materialsList ? state.materialsList.find(m => m.name && m.name.trim() === val.trim()) : null;
        if (mat) {
            const accType = mat.accountingType || mat.accounting_type || "";
            const commType = mat.commissionType || mat.commission_type || "";
            const workerType = mat.workerShareType || mat.worker_share_type || "";

            if (accTypeInput) accTypeInput.value = accType;
            if (commTypeInput) commTypeInput.value = commType;
            if (workerTypeInput) workerTypeInput.value = workerType;

            if (pAcc) pAcc.textContent = accType;
            if (pComm) pComm.textContent = "العمولة: " + commType;
            if (pWork) pWork.textContent = "حق العامل: " + workerType;
            if (pInfo) pInfo.style.display = "flex";

            if (priceInput) priceInput.value = mat.price || "";

            // Toggle weight column visibility
            if (mat.accounting_type === "عدد * سعر") {
                if (weightCol) weightCol.style.display = "none";
                if (weightInput) {
                    weightInput.removeAttribute("required");
                    weightInput.value = "";
                }
            } else {
                if (weightCol) weightCol.style.display = "block";
                if (weightInput) weightInput.setAttribute("required", "true");
            }
        } else {
            if (accTypeInput) accTypeInput.value = "";
            if (commTypeInput) commTypeInput.value = "";
            if (workerTypeInput) workerTypeInput.value = "";
            if (pInfo) pInfo.style.display = "none";
            if (priceInput) priceInput.value = "";
            if (weightCol) weightCol.style.display = "block";
            if (weightInput) weightInput.setAttribute("required", "true");
        }
    }
    if (window.liveCalcPreview) window.liveCalcPreview();
};

window.liveCalcPreview = function() {
    const qtyInput = document.getElementById("p-item-quantity");
    const weightInput = document.getElementById("p-item-weight");
    const priceInput = document.getElementById("p-item-price");
    
    const qty = parseInt(qtyInput ? qtyInput.value : 0) || 0;
    const weight = parseFloat(weightInput ? weightInput.value : 0) || 0;
    const price = parseFloat(priceInput ? priceInput.value.replace(/,/g, '') : 0) || 0;

    const accTypeInput = document.getElementById("p-item-accounting-type");
    const commTypeInput = document.getElementById("p-item-commission-type");
    const workerTypeInput = document.getElementById("p-item-worker-share-type");

    const accountingType = accTypeInput ? accTypeInput.value : "";
    const commissionType = commTypeInput ? commTypeInput.value : "";
    const workerShareType = workerTypeInput ? workerTypeInput.value : "";

    const previewContainer = document.getElementById("live-calc-preview");
    if (!previewContainer) return;

    if (qty > 0 && price >= 0) {
        const subtotal = accountingType === "وزن * سعر" ? weight * price : qty * price;
        const workerShare = calcFormula(workerShareType, qty, weight, price, accountingType);
        
        const commParts = calculateCommissionParts(commissionType, qty, weight, price, accountingType);
        const commission = commParts.commission;
        const commission_10 = commParts.commission_10;
        
        const itemTotal = subtotal + commission + commission_10;

        const subEl = document.getElementById("preview-subtotal");
        const workEl = document.getElementById("preview-worker");
        const commEl = document.getElementById("preview-commission");
        const comm10El = document.getElementById("preview-commission-10");

        if (subEl) subEl.textContent = formatCurrency(itemTotal);
        if (workEl) workEl.textContent = formatCurrency(workerShare);
        if (commEl) commEl.textContent = formatCurrency(commission);
        if (comm10El) comm10El.textContent = formatCurrency(commission_10);

        previewContainer.style.display = "block";
    } else {
        previewContainer.style.display = "none";
    }
};

window.closePurchaseListModal = function() {
    dom.purchaseModal.classList.remove("open");
    state.currentActiveFormId = null;
    lastItemsJson = "";
};

// Toggle the inline Add/Edit item form
window.toggleItemForm = function(show, itemId = null) {
    const nameSelect = document.getElementById("p-item-name-select");
    const manualInput = document.getElementById("p-item-name");

    const accTypeInput = document.getElementById("p-item-accounting-type");
    const commTypeInput = document.getElementById("p-item-commission-type");
    const workerTypeInput = document.getElementById("p-item-worker-share-type");

    const pInfo = document.getElementById("p-item-material-info");
    const pAcc = document.getElementById("p-item-accounting-chip");
    const pComm = document.getElementById("p-item-commission-chip");
    const pWork = document.getElementById("p-item-worker-chip");

    const weightInput = document.getElementById("p-item-weight");
    const weightCol = weightInput ? weightInput.closest("div").parentElement : null;

    if (show) {
        togglePaymentForm(false);
        dom.purchaseItemError.style.display = "none";
        dom.purchaseItemForm.reset();
        dom.purchaseItemIdInput.value = "";

        // Reset select & manual input
        if (nameSelect) nameSelect.value = "";
        if (manualInput) { manualInput.style.display = "none"; manualInput.value = ""; }

        // Clear hidden & chips
        if (accTypeInput) accTypeInput.value = "";
        if (commTypeInput) commTypeInput.value = "";
        if (workerTypeInput) workerTypeInput.value = "";
        if (pInfo) pInfo.style.display = "none";
        if (weightCol) weightCol.style.display = "block";
        if (weightInput) weightInput.setAttribute("required", "true");

        if (itemId) {
            dom.itemFormTitle.innerHTML = `<i class="fa-solid fa-pen-to-square"></i> تعديل مادة في قائمة الشراء`;
            // Find item in current form's items cache
            const form = state.forms.find(f => f.id === state.currentActiveFormId);
            if (form && form.items) {
                const item = form.items.find(i => i.id === itemId);
                if (item) {
                    dom.purchaseItemIdInput.value       = item.id;
                    dom.purchaseItemQuantityInput.value = item.quantity;
                    dom.purchaseItemWeightInput.value   = item.weight || "";
                    dom.purchaseItemPriceInput.value    = item.price;

                    // Re-populate types from matching material in state.materialsList
                    const matchingMaterial = state.materialsList ? state.materialsList.find(m => m.name && item.name && m.name.trim() === item.name.trim()) : null;
                    if (matchingMaterial) {
                        const accType = matchingMaterial.accountingType || matchingMaterial.accounting_type || "";
                        const commType = matchingMaterial.commissionType || matchingMaterial.commission_type || "";
                        const workerType = matchingMaterial.workerShareType || matchingMaterial.worker_share_type || "";

                        if (accTypeInput) accTypeInput.value = accType;
                        if (commTypeInput) commTypeInput.value = commType;
                        if (workerTypeInput) workerTypeInput.value = workerType;
                        
                        if (pAcc) pAcc.textContent = accType;
                        if (pComm) pComm.textContent = "العمولة: " + commType;
                        if (pWork) pWork.textContent = "حق العامل: " + workerType;
                        if (pInfo) pInfo.style.display = "flex";

                        // Toggle weight column visibility
                        if (matchingMaterial.accounting_type === "عدد * سعر") {
                            if (weightCol) weightCol.style.display = "none";
                            if (weightInput) weightInput.removeAttribute("required");
                        } else {
                            if (weightCol) weightCol.style.display = "block";
                            if (weightInput) weightInput.setAttribute("required", "true");
                        }
                    }

                    // Try to select from dropdown, else show manual input
                    if (nameSelect) {
                        const matchOpt = Array.from(nameSelect.options).find(o => o.value === item.name);
                        if (matchOpt) {
                            nameSelect.value = item.name;
                            if (manualInput) { manualInput.style.display = "none"; manualInput.value = item.name; }
                        } else {
                            // Not in list — switch to manual
                            nameSelect.value = "__manual__";
                            if (manualInput) { manualInput.style.display = "block"; manualInput.value = item.name; }
                        }
                    }
                    
                    if (window.liveCalcPreview) window.liveCalcPreview();
                }
            }
        } else {
            dom.itemFormTitle.innerHTML = `<i class="fa-solid fa-circle-plus"></i> إضافة مادة جديدة لقائمة الشراء`;
        }
        dom.purchaseItemFormContainer.style.display = "block";
        if (nameSelect) nameSelect.focus();
    } else {
        dom.purchaseItemFormContainer.style.display = "none";
        dom.purchaseItemForm.reset();
        if (nameSelect) nameSelect.value = "";
        if (manualInput) { manualInput.style.display = "none"; manualInput.value = ""; }

        // Clear hidden & chips
        if (accTypeInput) accTypeInput.value = "";
        if (commTypeInput) commTypeInput.value = "";
        if (workerTypeInput) workerTypeInput.value = "";
        if (pInfo) pInfo.style.display = "none";
        if (weightCol) weightCol.style.display = "block";
        if (weightInput) weightInput.setAttribute("required", "true");

        dom.purchaseItemIdInput.value = "";
        const previewContainer = document.getElementById("live-calc-preview");
        if (previewContainer) previewContainer.style.display = "none";
    }
};

// Render items — fetch from database each time
// ── Helper: parse a formula like "عدد * 1000" or "الوزن * 30" ──
// Supported patterns:
//   عدد * X    → qty * X
//   العدد * X  → qty * X
//   وزن * X    → weight * X
//   الوزن * X  → weight * X
function calculateCommissionParts(formula, qty, weight, price, accountingType = '') {
    if (formula === null || formula === undefined) return { commission: 0, commission_10: 0 };
    const strFormula = String(formula).trim();
    if (strFormula === '' || strFormula === '---' || strFormula === '0') {
        return { commission: 0, commission_10: 0 };
    }
    
    let parts = strFormula.split('+');
    let commission = 0;
    let commission_10 = 0;
    
    parts.forEach(part => {
        const trimmed = part.trim();
        const pctMatch = trimmed.match(/(\d+(?:\.\d+)?)\s*%/);
        if (pctMatch) {
            const pct = parseFloat(pctMatch[1]);
            let base = 0;
            if (accountingType === "وزن * سعر") {
                base = weight * price;
            } else if (accountingType === "عدد * سعر") {
                base = qty * price;
            } else {
                base = (weight > 0) ? (weight * price) : (qty * price);
            }
            commission_10 += base * pct / 100;
        } else {
            commission += calcFormula(trimmed, qty, weight, price, accountingType);
        }
    });
    
    return { commission, commission_10 };
}

function calcFormula(formula, qty, weight, price, accountingType = '') {
    if (formula === null || formula === undefined) return 0;
    const strFormula = String(formula).trim();
    if (strFormula === '' || strFormula === '---' || strFormula === '0') return 0;
    
    if (strFormula.includes('+')) {
        return strFormula.split('+').reduce((sum, part) => sum + calcFormula(part, qty, weight, price, accountingType), 0);
    }
    
    const f = strFormula;

    const pctMatch = f.match(/(\d+(?:\.\d+)?)\s*%/);
    if (pctMatch) {
        const subtotal = accountingType === "وزن * سعر" ? weight * price : (accountingType === "عدد * سعر" ? qty * price : (weight > 0 ? weight * price : qty * price));
        return subtotal * parseFloat(pctMatch[1]) / 100;
    }

    const qtyMatch = f.match(/(?:عدد|العدد)\s*[*×]\s*(\d+(?:\.\d+)?)/);
    if (qtyMatch) return qty * parseFloat(qtyMatch[1]);

    const wgtMatch = f.match(/(?:وزن|الوزن)\s*[*×]\s*(\d+(?:\.\d+)?)/);
    if (wgtMatch) return (weight || qty) * parseFloat(wgtMatch[1]);

    const numMatch = f.match(/^(\d+(?:\.\d+)?)$/);
    if (numMatch) return parseFloat(numMatch[1]);

    return 0;
}

// ─── Inline quick-update: يُستدعى عند مغادرة حقل السعر / الوزن أو تغيير العدد ───
window.inlineUpdateItem = function(itemId, field, rawValue) {
    if (typeof rawValue === 'string') {
        rawValue = rawValue.replace(/,/g, '');
    }
    const parsed = parseFloat(rawValue);
    let value = isNaN(parsed) ? 0 : parsed;

    if (field === 'quantity' && value < 1) {
        value = 1;
        const inp = document.getElementById(`qty-inp-${itemId}`);
        if (inp) inp.value = 1;
    }

    const qtyInp   = document.getElementById(`qty-inp-${itemId}`);
    const wgtInp   = document.getElementById(`wgt-inp-${itemId}`);
    const priceInp = document.getElementById(`price-inp-${itemId}`);

    const row = qtyInp?.closest('tr');
    if (!row) return;

    const accType  = row.dataset.accType  || '';
    const commType = row.dataset.commType || '';
    const workType = row.dataset.workType || '';
    const itemName = row.dataset.itemName || '';
    const formId   = row.dataset.formId   || state.currentActiveFormId;

    const qty    = parseInt(qtyInp?.value)    || 1;
    const weight = parseFloat(wgtInp?.value)  || 0;
    const price  = parseFloat(priceInp?.value ? priceInp.value.replace(/,/g, '') : 0) || 0;

    const subtotal      = accType === 'وزن * سعر' ? weight * price : qty * price;
    const commParts     = calculateCommissionParts(commType, qty, weight, price, accType);
    const commission    = commParts.commission;
    const commission_10 = commParts.commission_10;
    const worker_share  = calcFormula(workType, qty, weight, price, accType);
    const total         = subtotal + commission + commission_10;

    // تحديث المعاينة والحسابات على الواجهة فوراً دون الانتظار
    inlineLiveCalc(itemId);
    recalcFormTotals();

    // إرسال التحديث في الخلفية بدون إعادة مسح الجدول
    fetch('api/forms.php?action=save_item', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            id:            itemId,
            form_id:       formId,
            name:          itemName,
            quantity:      qty,
            weight:        weight || null,
            price:         price,
            worker_share:  worker_share,
            commission:    commission,
            commission_10: commission_10,
            total:         total
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res && res.status === 'success') {
            const form = state.forms ? state.forms.find(f => f.id === formId) : null;
            if (form && Array.isArray(form.items)) {
                const it = form.items.find(i => String(i.id) === String(itemId));
                if (it) {
                    it.quantity = qty;
                    it.weight = weight;
                    it.price = price;
                    it.worker_share = worker_share;
                    it.commission = commission;
                    it.commission_10 = commission_10;
                    it.total = total;
                }
            }
            recalcFormTotals();
        } else if (res) {
            showToast('فشل تحديث القيمة', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم', 'danger'));
};

// ─── زيادة/إنقاص العدد بزر + و - ───
window.inlineStepQty = function(itemId, step) {
    const inp = document.getElementById(`qty-inp-${itemId}`);
    if (!inp) return;
    const newVal = Math.max(1, (parseInt(inp.value) || 1) + step);
    inp.value = newVal;
    inlineLiveCalc(itemId); // معاينة فورية
    inlineUpdateItem(itemId, 'quantity', newVal);
};

// ─── تحديث لحظي للخلايا المحسوبة دون حفظ ───
window.inlineLiveCalc = function(itemId) {
    const qtyInp   = document.getElementById(`qty-inp-${itemId}`);
    const wgtInp   = document.getElementById(`wgt-inp-${itemId}`);
    const priceInp = document.getElementById(`price-inp-${itemId}`);

    const qty    = parseInt(qtyInp?.value)    || 0;
    const weight = parseFloat(wgtInp?.value)  || 0;
    const price  = parseFloat(priceInp?.value ? priceInp.value.replace(/,/g, '') : 0) || 0;

    // جلب بيانات المادة من data-attributes مخزنة في الصف
    const row = qtyInp?.closest('tr');
    const accType  = row?.dataset.accType  || '';
    const commType = row?.dataset.commType || '';
    const workType = row?.dataset.workType || '';
    const cur      = getCurrency();

    const subtotal      = accType === 'وزن * سعر' ? weight * price : qty * price;
    const commParts     = calculateCommissionParts(commType, qty, weight, price, accType);
    const commission    = commParts.commission;
    const commission_10 = commParts.commission_10;
    const workerShare   = calcFormula(workType, qty, weight, price, accType);
    const total         = subtotal + commission + commission_10;

    // تحديث خلايا هذا الصف
    const wCell   = document.getElementById(`worker-cell-${itemId}`);
    const cCell   = document.getElementById(`comm-cell-${itemId}`);
    const c10Cell = document.getElementById(`comm10-cell-${itemId}`);
    const tCell   = document.getElementById(`total-cell-${itemId}`);

    if (wCell)   wCell.textContent   = workerShare   > 0 ? `${formatCurrency(workerShare)} ${cur}`   : '---';
    if (cCell)   cCell.textContent   = commission    > 0 ? `${formatCurrency(commission)} ${cur}`    : '---';
    if (c10Cell) c10Cell.textContent = commission_10 > 0 ? `${formatCurrency(commission_10)} ${cur}` : '---';
    if (tCell)   tCell.textContent   = `${formatCurrency(total)} ${cur}`;

    // تحديث الإجماليات الكلية للاستمارة
    recalcFormTotals();
};

// ─── إعادة حساب وتحديث إجماليات الاستمارة من DOM لحظياً ───
window.recalcFormTotals = function() {
    const FORM_FEE = 1000;
    const cur = getCurrency();

    let totWorker = 0, totComm = 0, totComm10 = 0, totSubtotal = 0;

    // قراءة كل الصفوف التي تحتوي على data-acc-type (صفوف المواد الحقيقية)
    const tbody = dom.purchaseItemsTbody;
    if (!tbody) return;

    tbody.querySelectorAll('tr[data-acc-type]').forEach(row => {
        const itemId   = row.querySelector('[id^="qty-inp-"]')?.id?.replace('qty-inp-', '');
        if (!itemId) return;

        const qtyVal   = document.getElementById(`qty-inp-${itemId}`)?.value || '0';
        const wgtVal   = document.getElementById(`wgt-inp-${itemId}`)?.value || '0';
        const priceVal = document.getElementById(`price-inp-${itemId}`)?.value || '0';

        const qty    = parseInt(qtyVal.replace(/,/g, ''))   || 0;
        const weight = parseFloat(wgtVal.replace(/,/g, '')) || 0;
        const price  = parseFloat(priceVal.replace(/,/g, ''))|| 0;

        const accType  = row.dataset.accType  || '';
        const commType = row.dataset.commType || '';
        const workType = row.dataset.workType || '';

        const subtotal      = accType === 'وزن * سعر' ? weight * price : qty * price;
        const commParts     = calculateCommissionParts(commType, qty, weight, price, accType);
        const commission    = commParts.commission;
        const commission_10 = commParts.commission_10;
        const workerShare   = calcFormula(workType, qty, weight, price, accType);

        totSubtotal += subtotal;
        totWorker   += workerShare;
        totComm     += commission;
        totComm10   += commission_10;
    });

    const grandTotal = totSubtotal + totComm + totComm10 + FORM_FEE;

    // جلب المدفوع من الحالة المحلية
    const formObj   = state.forms.find(f => f.id === state.currentActiveFormId);
    const totalPaid = formObj ? (formObj.totalPaid || 0) : 0;
    const remaining = grandTotal - totalPaid;

    // تحديث عناصر الإجماليات
    if (dom.purchaseGrandTotal)
        dom.purchaseGrandTotal.textContent = `${formatCurrency(grandTotal)} ${cur}`;
    if (dom.purchaseWorkerTotal)
        dom.purchaseWorkerTotal.textContent = `${formatCurrency(totWorker)} ${cur}`;
    if (dom.purchaseCommissionTotal)
        dom.purchaseCommissionTotal.textContent = `${formatCurrency(totComm)} ${cur}`;
    if (dom.purchaseCommission10Total)
        dom.purchaseCommission10Total.textContent = `${formatCurrency(totComm10)} ${cur}`;

    // المدفوع لا يتغير بتغيير السعر — يظل ثابتاً
    const paidElem = document.getElementById('purchase-paid-total');
    if (paidElem) paidElem.textContent = `${formatCurrency(totalPaid)} ${cur}`;

    // المتبقي
    const remainingElem = document.getElementById('purchase-remaining-total');
    if (remainingElem) {
        remainingElem.textContent = `${formatCurrency(Math.abs(remaining))} ${cur}`;
        remainingElem.style.color = remaining < -0.01 ? '#10b981' : '#ef4444';
    }

    // تحديث حقل المبلغ المدفوع في نموذج التحصيل (إن كان مفتوحاً)
    const payGrandTotal = document.getElementById('pay-grand-total');
    if (payGrandTotal) payGrandTotal.textContent = `${formatCurrency(grandTotal)} ${cur}`;

    const payRemaining = document.getElementById('pay-remaining-amount');
    if (payRemaining) {
        const safeRemaining = Math.max(0, remaining);
        payRemaining.textContent = `${formatCurrency(safeRemaining)} ${cur}`;
    }

    const payAmountInp = document.getElementById('pay-amount');
    if (payAmountInp && payAmountInp.max !== undefined) {
        payAmountInp.max = Math.max(0, remaining);
    }
};

// Render items — fetch from database each time
let lastItemsJson = "";
window.renderPurchaseItems = function(isSilent = false) {
    if (!state.currentActiveFormId) return;

    const COLS = 10; // total columns in new table

    if (!isSilent && dom.purchaseItemsTbody.children.length === 0) {
        dom.purchaseItemsTbody.innerHTML = `
            <tr><td colspan="${COLS}" style="text-align:center;padding:20px;color:var(--text-muted);">
                <i class="fa-solid fa-spinner fa-spin" style="margin-left:8px;"></i> جاري تحميل المواد...
            </td></tr>`;
    }

    fetch(`api/forms.php?action=get_items&form_id=${state.currentActiveFormId}`)
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') {
                if (!isSilent) showToast('فشل تحميل مواد الاستمارة', 'danger');
                return;
            }
            const items = res.data;
            const itemsJson = JSON.stringify({ items, totalPaid: res.totalPaid });

            const activeEl = document.activeElement;
            const isEditingInTable = activeEl && dom.purchaseItemsTbody.contains(activeEl);

            if (isSilent && (itemsJson === lastItemsJson || isEditingInTable)) {
                return; // Do not interrupt active editing or re-render if identical
            }
            lastItemsJson = itemsJson;

            // Cache items in state
            const form = state.forms.find(f => f.id === state.currentActiveFormId);
            if (form) {
                form.items = items;
                form.totalPaid = res.totalPaid || 0;
            }

            dom.purchaseItemsTbody.innerHTML = "";
            dom.purchaseItemsTbody.closest("table").style.display = "table";
            dom.purchaseItemsEmpty.style.display = "none";

            const FORM_FEE = 1000;
            const cur = getCurrency();

            if (items.length === 0) {
                // Empty state but still show fee row
                const emptyRow = document.createElement("tr");
                emptyRow.innerHTML = `
                    <td colspan="${COLS - 1}" style="text-align:center;padding:20px;color:var(--text-muted);">
                        <i class="fa-solid fa-basket-shopping" style="font-size:28px;display:block;margin-bottom:6px;color:var(--text-muted);"></i>
                        لا توجد مواد مضافة بعد
                    </td><td></td>`;
                dom.purchaseItemsTbody.appendChild(emptyRow);

                // Fee row
                appendFeeRow(dom.purchaseItemsTbody, FORM_FEE, cur, COLS);
                dom.purchaseGrandTotal.textContent = `${formatCurrency(FORM_FEE)} ${cur}`;
                return;
            }

            let totQty = 0, totWeight = 0, totWorker = 0, totCommission = 0, totCommission10 = 0, totSubtotal = 0;

            items.forEach((item, index) => {
                const weight  = parseFloat(item.weight)   || 0;
                const qty     = parseInt(item.quantity)   || 0;
                const price   = parseFloat(item.price)    || 0;

                // المجموع الكلي للمادة (حساب حسب نوع المحاسبة للمادة)
                const subtotal = item.accountingType === "وزن * سعر" ? weight * price : qty * price;

                // حق العامل
                const workerShare  = (item.workerShare !== undefined && item.workerShare !== null) ? parseFloat(item.workerShare) : calcFormula(item.workerShareType,  qty, weight, price, item.accountingType);

                // عمولة المادة و عمولة 10%
                let commission = 0;
                let commission_10 = 0;
                if (item.commission !== undefined && item.commission !== null && item.commission_10 !== undefined && item.commission_10 !== null) {
                    commission = parseFloat(item.commission);
                    commission_10 = parseFloat(item.commission_10);
                } else {
                    const commParts = calculateCommissionParts(item.commissionType, qty, weight, price, item.accountingType);
                    commission = commParts.commission;
                    commission_10 = commParts.commission_10;
                }

                const itemTotal = (item.total !== undefined && item.total !== null) ? parseFloat(item.total) : subtotal + commission + commission_10;
                const finalSubtotal = (item.total !== undefined && item.total !== null) ? (itemTotal - commission - commission_10) : subtotal;

                totQty          += qty;
                totWeight       += weight;
                totWorker       += workerShare;
                totCommission   += commission;
                totCommission10 += commission_10;
                totSubtotal     += finalSubtotal;

                const weightStr  = weight  > 0 ? Number(weight.toFixed(2)) + " كجم" : "---";

                // Row color alternation
                const rowBg = index % 2 === 0 ? "transparent" : "rgba(59,130,246,0.025)";

                const tr = document.createElement("tr");
                tr.style.cssText = `background:${rowBg}; transition: background 0.15s;`;
                tr.onmouseover = () => tr.style.background = "rgba(59,130,246,0.06)";
                tr.onmouseout  = () => tr.style.background = rowBg;

                // ─── Inline input styles ───
                const inpBase = `font-family:var(--font-family); font-size:14px; font-weight:700; border-radius:6px; border:1.5px solid var(--border-color); background:var(--bg-input); color:var(--text-primary); outline:none; text-align:center; padding:6px 8px; transition:border-color 0.2s, box-shadow 0.2s;`;
                const qtyInpStyle = `${inpBase} width:80px;`;
                const wgtInpStyle = `${inpBase} width:100px;`;
                const priceInpStyle = `${inpBase} width:120px; color:var(--primary); border-color:rgba(59,130,246,0.35); background:rgba(59,130,246,0.04);`;
                const btnStyle = (color) => `width:26px; height:26px; border:none; border-radius:5px; background:${color}; color:#fff; font-size:15px; font-weight:800; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; line-height:1; transition:opacity .15s;`;

                tr.dataset.accType  = item.accountingType  || '';
                tr.dataset.commType = item.commissionType  || '';
                tr.dataset.workType = item.workerShareType || '';
                tr.dataset.itemName = item.name || '';
                tr.dataset.formId   = item.form_id || state.currentActiveFormId;

                tr.innerHTML = `
                    <td style="text-align:center; font-weight:700; color:var(--primary); font-size:14px; padding:12px 10px;">${index + 1}</td>
                    <td style="font-weight:700; font-size:15px; padding:12px 16px;">${escapeHTML(item.name)}</td>

                    <!-- العدد: أزرار + و - مباشرة -->
                    <td style="text-align:center; padding:8px 6px;">
                        <div style="display:flex; align-items:center; justify-content:center; gap:4px;">
                            <button style="${btnStyle('rgba(239,68,68,0.8)')}" title="إنقاص" onclick="inlineStepQty('${item.id}', -1)">−</button>
                            <input type="number" id="qty-inp-${item.id}" value="${qty}" min="1" style="${qtyInpStyle}"
                                onfocus="this.style.borderColor='var(--primary)'; this.style.boxShadow='0 0 0 3px rgba(59,130,246,0.12)'"
                                oninput="inlineLiveCalc('${item.id}')"
                                onblur="this.style.borderColor='var(--border-color)'; this.style.boxShadow='none'; inlineUpdateItem('${item.id}', 'quantity', this.value)"
                                onkeydown="if(event.key==='Enter'){this.blur();}"
                            >
                            <button style="${btnStyle('rgba(16,185,129,0.8)')}" title="زيادة" onclick="inlineStepQty('${item.id}', 1)">+</button>
                        </div>
                    </td>

                    <!-- الوزن: input مباشر -->
                    <td style="text-align:center; padding:8px 6px;">
                        <input type="number" id="wgt-inp-${item.id}" value="${weight > 0 ? weight : ''}" min="0" step="0.01" placeholder="---" style="${wgtInpStyle}"
                            onfocus="this.style.borderColor='var(--primary)'; this.style.boxShadow='0 0 0 3px rgba(59,130,246,0.12)'"
                            oninput="inlineLiveCalc('${item.id}')"
                            onblur="this.style.borderColor='var(--border-color)'; this.style.boxShadow='none'; inlineUpdateItem('${item.id}', 'weight', this.value)"
                            onkeydown="if(event.key==='Enter'){this.blur();}"
                        >
                    </td>

                    <!-- السعر: input مباشر -->
                    <td style="text-align:center; padding:8px 6px;">
                        <input type="text" id="price-inp-${item.id}" value="${price > 0 ? formatCurrency(price) : ''}" placeholder="0" style="${priceInpStyle}"
                            onfocus="this.style.borderColor='var(--primary)'; this.style.boxShadow='0 0 0 3px rgba(59,130,246,0.2)'"
                            oninput="formatInlinePriceInput(this); inlineLiveCalc('${item.id}')"
                            onblur="this.style.borderColor='rgba(59,130,246,0.35)'; this.style.boxShadow='none'; inlineUpdateItem('${item.id}', 'price', this.value)"
                            onkeydown="if(event.key==='Enter'){this.blur();}"
                        >
                    </td>

                    <td style="text-align:center; font-weight:700; color:#10b981; font-size:14px; padding:12px 10px;">
                        <span id="worker-cell-${item.id}">${workerShare > 0 ? formatCurrency(workerShare) + ' ' + cur : '---'}</span>
                        ${item.workerShareType ? '<br><span style="font-size:10px;font-weight:400;color:var(--text-muted);">' + escapeHTML(item.workerShareType) + '</span>' : ''}
                    </td>
                    <td style="text-align:center; font-weight:700; color:#f59e0b; font-size:14px; padding:12px 10px;">
                        <span id="comm-cell-${item.id}">${commission > 0 ? formatCurrency(commission) + ' ' + cur : '---'}</span>
                        ${(() => {
                            if (!item.commissionType) return '';
                            const cleaned = item.commissionType.replace(/(?:إضافة|اضافة)?\s*\d+(?:\.\d+)?%\s*\+?/gi, '').replace(/\+\s*$/, '').trim();
                            return cleaned ? '<br><span style="font-size:10px;font-weight:400;color:var(--text-muted);">' + escapeHTML(cleaned) + '</span>' : '';
                        })()}
                    </td>
                    <td style="text-align:center; font-weight:700; color:#f59e0b; font-size:14px; padding:12px 10px;">
                        <span id="comm10-cell-${item.id}">${commission_10 > 0 ? formatCurrency(commission_10) + ' ' + cur : '---'}</span>
                        ${(() => {
                            if (!item.commissionType) return '';
                            const matches = item.commissionType.match(/(?:إضافة|اضافة)?\s*\d+(?:\.\d+)?%/gi);
                            return matches ? '<br><span style="font-size:10px;font-weight:400;color:var(--text-muted);">' + escapeHTML(matches.join(' + ')) + '</span>' : '';
                        })()}
                    </td>
                    <td style="text-align:center; font-weight:800; color:var(--primary); font-size:15px; padding:12px 10px;">
                        <span id="total-cell-${item.id}">${formatCurrency(itemTotal)} ${cur}</span>
                    </td>
                    <td style="text-align:center; padding:12px 8px;">
                        <div style="display:flex;gap:5px;justify-content:center;">
                            <button class="btn-icon btn-icon-delete" onclick="deletePurchaseItem('${item.id}')" title="حذف" style="width:32px;height:32px;font-size:14px;">
                                <i class="fa-solid fa-trash-can"></i>
                            </button>
                        </div>
                    </td>
                `;
                dom.purchaseItemsTbody.appendChild(tr);
            });

            // ── Totals Row ──
            const totalsRow = document.createElement("tr");
            totalsRow.style.cssText = "background: rgba(59,130,246,0.08); border-top: 2px solid rgba(59,130,246,0.2); font-weight:800;";
            totalsRow.innerHTML = `
                <td style="text-align:center; padding:10px 8px;">
                    <i class="fa-solid fa-sigma" style="color:var(--primary);font-size:13px;"></i>
                </td>
                <td style="padding:10px 14px; font-size:12px; color:var(--text-secondary);">المجاميع</td>
                <td style="text-align:center; font-size:13px; color:var(--primary); padding:10px 8px;">${totQty}</td>
                <td style="text-align:center; font-size:12px; color:var(--text-secondary); padding:10px 8px;">${totWeight > 0 ? Number(totWeight.toFixed(2)) + " كجم" : "---"}</td>
                <td style="padding:10px 8px;"></td>
                <td style="text-align:center; font-size:13px; color:#10b981; padding:10px 8px;">${formatCurrency(totWorker)} ${cur}</td>
                <td style="text-align:center; font-size:13px; color:#f59e0b; padding:10px 8px;">${formatCurrency(totCommission)} ${cur}</td>
                <td style="text-align:center; font-size:13px; color:#f59e0b; padding:10px 8px;">${formatCurrency(totCommission10)} ${cur}</td>
                <td style="text-align:center; font-size:14px; color:var(--primary); padding:10px 8px;">${formatCurrency(totSubtotal + totCommission + totCommission10)} ${cur}</td>
                <td style="padding:10px 8px;"></td>
            `;
            dom.purchaseItemsTbody.appendChild(totalsRow);

            // ── رسوم الاستمارة ──
            appendFeeRow(dom.purchaseItemsTbody, FORM_FEE, cur, COLS);

            const grandTotal = totSubtotal + totCommission + totCommission10 + FORM_FEE;
            dom.purchaseGrandTotal.textContent      = `${formatCurrency(grandTotal)} ${cur}`;
            if (dom.purchaseWorkerTotal)     dom.purchaseWorkerTotal.textContent     = `${formatCurrency(totWorker)} ${cur}`;
            if (dom.purchaseCommissionTotal) dom.purchaseCommissionTotal.textContent = `${formatCurrency(totCommission)} ${cur}`;
            if (dom.purchaseCommission10Total) dom.purchaseCommission10Total.textContent = `${formatCurrency(totCommission10)} ${cur}`;

            // Calc Paid and Remaining Totals
            const totalPaid = res.totalPaid || 0;
            const remaining = grandTotal - totalPaid;

            // Sync with local state.forms to ensure absolute accuracy in sub-forms
            const formObj = state.forms.find(f => f.id === state.currentActiveFormId);
            if (formObj) {
                formObj.totalPaid = totalPaid;
                formObj.grandTotal = grandTotal;
                if (res.items) formObj.items = res.items;
            }

            const paidElem = document.getElementById("purchase-paid-total");
            const remainingElem = document.getElementById("purchase-remaining-total");
            if (paidElem) paidElem.textContent = `${formatCurrency(totalPaid)} ${cur}`;
            
            if (remainingElem) {
                if (remaining < -0.01) {
                    remainingElem.textContent = `${formatCurrency(Math.abs(remaining))} ${cur}`;
                    remainingElem.style.color = "#10b981"; // Green for surplus
                    remainingElem.closest("div").style.background = "rgba(16,185,129,0.07)";
                    remainingElem.closest("div").style.borderColor = "rgba(16,185,129,0.2)";
                    const remainingLabel = remainingElem.closest("div").querySelector("div");
                    if (remainingLabel) remainingLabel.innerHTML = `<i class="fa-solid fa-hand-holding-dollar" style="margin-left:6px; color:#10b981;"></i>المتبقي (له)`;
                    
                    // Show surplus warning box
                    if (dom.surplusWarningContainer) {
                        dom.surplusWarningContainer.style.display = "block";
                        dom.surplusPaidAmount.textContent = `${formatCurrency(totalPaid)} ${cur}`;
                        dom.surplusGrandTotal.textContent = `${formatCurrency(grandTotal)} ${cur}`;
                        dom.surplusDiffAmount.textContent = `${formatCurrency(Math.abs(remaining))} ${cur}`;
                    }
                } else {
                    remainingElem.textContent = `${formatCurrency(Math.max(0, remaining))} ${cur}`;
                    remainingElem.style.color = "#ef4444"; // Red for debt
                    remainingElem.closest("div").style.background = "rgba(239,68,68,0.07)";
                    remainingElem.closest("div").style.borderColor = "rgba(239,68,68,0.2)";
                    const remainingLabel = remainingElem.closest("div").querySelector("div");
                    if (remainingLabel) remainingLabel.innerHTML = `<i class="fa-solid fa-hand-holding-dollar" style="margin-left:6px; color:#ef4444;"></i>المتبقي غير المدفوع`;
                    
                    // Hide surplus warning box
                    if (dom.surplusWarningContainer) {
                        dom.surplusWarningContainer.style.display = "none";
                    }
                }
            }

            // Control the Pay Button state
            const payBtn = document.getElementById("pay-purchase-btn");
            if (payBtn) {
                if (remaining <= 0.01) {
                    payBtn.disabled = true;
                    payBtn.style.opacity = "0.6";
                    payBtn.style.cursor = "not-allowed";
                    payBtn.innerHTML = `<i class="fa-solid fa-circle-check"></i> تم تحصيل الاستمارة بالكامل`;
                } else {
                    payBtn.disabled = false;
                    payBtn.style.opacity = "1";
                    payBtn.style.cursor = "pointer";
                    payBtn.innerHTML = `<i class="fa-solid fa-cash-register"></i> دفع وتحصيل الاستمارة`;
                }
            }

            if (dom.refundPurchaseBtn) {
                if (totalPaid > 0.01) {
                    dom.refundPurchaseBtn.style.display = "flex";
                    if (remaining <= 0.01) {
                        dom.refundPurchaseBtn.innerHTML = `<i class="fa-solid fa-arrow-rotate-left"></i> إرجاع المبلغ وتحويلها لديون`;
                    } else {
                        dom.refundPurchaseBtn.innerHTML = `<i class="fa-solid fa-arrow-rotate-left"></i> إرجاع الدفعة المستحصلة`;
                    }
                } else {
                    dom.refundPurchaseBtn.style.display = "none";
                }
            }
        })
        .catch(() => showToast('فشل الاتصال بالخادم', 'danger'));
};

// Helper: append the fixed form fee row
function appendFeeRow(tbody, fee, cur, cols) {
    const feeRow = document.createElement("tr");
    feeRow.style.cssText = "background: rgba(245,158,11,0.07); border-top: 2px dashed rgba(245,158,11,0.3);";
    feeRow.innerHTML = `
        <td style="text-align:center; padding:10px 8px; color:#d97706; font-size:14px;">
            <i class="fa-solid fa-receipt"></i>
        </td>
        <td colspan="${cols - 4}" style="padding:10px 14px; font-weight:700; color:#d97706; font-size:13px;">
            رسوم الاستمارة
        </td>
        <td style="text-align:center; font-weight:800; color:#d97706; font-size:14px; padding:10px 8px;">
            ${formatCurrency(fee)} ${cur}
        </td>
        <td colspan="2" style="padding:10px 8px;"></td>
    `;
    tbody.appendChild(feeRow);
}



// Save Item (Add or Edit)
window.savePurchaseItem = function(e) {
    e.preventDefault();

    const itemId  = dom.purchaseItemIdInput.value;
    const form_id = state.currentActiveFormId;

    // Determine name: from select dropdown OR manual text input
    const nameSelect = document.getElementById("p-item-name-select");
    const manualInput = document.getElementById("p-item-name");
    let name = "";
    if (nameSelect && nameSelect.value && nameSelect.value !== "__manual__") {
        name = nameSelect.value.trim();
    } else if (manualInput && manualInput.value.trim()) {
        name = manualInput.value.trim();
    }

    const qty     = parseInt(dom.purchaseItemQuantityInput.value);
    const pieces  = null;
    const weight  = dom.purchaseItemWeightInput.value !== "" ? parseFloat(dom.purchaseItemWeightInput.value) : null;
    const price   = parseFloat(dom.purchaseItemPriceInput.value.replace(/,/g, ''));

    if (!name || isNaN(qty) || qty <= 0 || isNaN(price) || price < 0) {
        dom.purchaseItemError.style.display = "block";
        return;
    }
    dom.purchaseItemError.style.display = "none";

    // Calculate worker_share, commission, and total
    const accTypeInput = document.getElementById("p-item-accounting-type");
    const commTypeInput = document.getElementById("p-item-commission-type");
    const workerTypeInput = document.getElementById("p-item-worker-share-type");

    const accountingType = accTypeInput ? accTypeInput.value : "";
    const commissionType = commTypeInput ? commTypeInput.value : "";
    const workerShareType = workerTypeInput ? workerTypeInput.value : "";

    const subtotal = accountingType === "وزن * سعر" ? (weight || 0) * price : qty * price;
    const worker_share = calcFormula(workerShareType, qty, weight || 0, price, accountingType);

    // فصل العمولة إلى: commission (بقية الأنواع) و commission_10 (نسبة الـ 10% فقط)
    const commParts = calculateCommissionParts(commissionType, qty, weight || 0, price, accountingType);
    const commission    = commParts.commission;
    const commission_10 = commParts.commission_10;
    const total = subtotal + commission + commission_10;

    const saveBtn = dom.purchaseItemForm.querySelector('[type="submit"]');
    if (saveBtn) saveBtn.disabled = true;

    fetch('api/forms.php?action=save_item', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
            id: itemId, 
            form_id, 
            name, 
            quantity: qty, 
            pieces, 
            weight, 
            price,
            worker_share,
            commission,
            commission_10,
            total
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || 'تم حفظ المادة بنجاح');
            toggleItemForm(false);
            renderPurchaseItems();
            loadData(); // refresh cards stats
        } else {
            showToast(res.message || 'فشل الحفظ', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم', 'danger'))
    .finally(() => { if (saveBtn) saveBtn.disabled = false; });
};

// Delete Item
window.deletePurchaseItem = function(itemId) {
    if (!confirm("هل أنت متأكد من حذف هذه المادة؟")) return;

    fetch('api/forms.php?action=delete_item', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: itemId, form_id: state.currentActiveFormId })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast('تم حذف المادة بنجاح', 'danger');
            renderPurchaseItems();
            loadData(); // refresh cards stats
        } else {
            showToast(res.message || 'فشل الحذف', 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم', 'danger'));
};

// -------------------------------------------------------------
// 16. Form Payment & Safe Integration
// -------------------------------------------------------------
function loadSafesDropdown() {
    const select = document.getElementById("pay-safe-id");
    if (!select) return;

    fetch('api/safes.php?action=list')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.safes) {
                select.innerHTML = '';
                res.safes.forEach(safe => {
                    const option = document.createElement("option");
                    option.value = safe.id;
                    option.textContent = safe.name;
                    select.appendChild(option);
                });
            }
        })
        .catch(() => {});
}

function getLiveFormTotalAndPaid() {
    const grandTotalElem = document.getElementById('purchase-grand-total');
    const paidTotalElem = document.getElementById('purchase-paid-total');
    
    let grandTotal = 0;
    let totalPaid = 0;
    
    if (grandTotalElem && paidTotalElem) {
        grandTotal = parseFloat(grandTotalElem.textContent.replace(/[^\d.]/g, '')) || 0;
        totalPaid = parseFloat(paidTotalElem.textContent.replace(/[^\d.]/g, '')) || 0;
    }
    
    if (grandTotal <= 0) {
        const form = state.forms.find(f => f.id === state.currentActiveFormId);
        if (form) {
            const items = form.items || [];
            const FORM_FEE = 1000;
            let totSubtotal = 0;
            let totComm = 0;
            let totComm10 = 0;
            items.forEach(item => {
                const weight = parseFloat(item.weight) || 0;
                const qty = parseInt(item.quantity) || 0;
                const price = parseFloat(item.price) || 0;
                const subtotal = item.accountingType === "وزن * سعر" ? weight * price : qty * price;
                const commParts = calculateCommissionParts(item.commissionType, qty, weight, price, item.accountingType);
                totSubtotal += subtotal;
                totComm += commParts.commission;
                totComm10 += commParts.commission_10;
            });
            grandTotal = totSubtotal + totComm + totComm10 + FORM_FEE;
            totalPaid = parseFloat(form.totalPaid) || 0;
        }
    }
    
    const remaining = Math.max(0, grandTotal - totalPaid);
    return { grandTotal, totalPaid, remaining };
}

window.togglePaymentForm = function(show) {
    const formContainer = document.getElementById("payment-form-container");
    if (!formContainer) return;

    if (show) {
        // Hide the purchase item form if open
        toggleItemForm(false);
        
        // Fetch and populate fields
        const form = state.forms.find(f => f.id === state.currentActiveFormId);
        if (!form) return;

        // Load safes dropdown
        loadSafesDropdown();

        // Defaults
        const payDateInput = document.getElementById("pay-date");
        if (payDateInput) payDateInput.value = new Date().toISOString().split('T')[0];

        const payDescInput = document.getElementById("pay-description");
        if (payDescInput) {
            const formIndex = state.forms.findIndex(f => f.id === state.currentActiveFormId);
            const formNumber = state.forms.length - formIndex;
            const formDate = form.createdAt ? form.createdAt.substring(0, 10) : '';
            payDescInput.value = `تحصيل دفعة من استمارة الزبون: ${form.customerName} رقم: #${formNumber} بتاريخ: ${formDate}`;
        }

        const { grandTotal, remaining } = getLiveFormTotalAndPaid();

        const payAmountInput = document.getElementById("pay-amount");
        if (payAmountInput) {
            // يترك الحقل فارغاً ليدخل المستخدم المبلغ يدوياً
            payAmountInput.value = "";

            // التحقق اللحظي عند الكتابة
            payAmountInput.oninput = function() {
                let cursorPosition = this.selectionStart;
                let originalLength = this.value.length;

                let valStr = this.value.replace(/,/g, '');
                let parts = valStr.split('.');
                parts[0] = parts[0].replace(/\D/g, '');
                parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                
                if (parts.length > 1) {
                    parts[1] = parts[1].replace(/\D/g, '').substring(0, 2);
                    this.value = parts[0] + '.' + parts[1];
                } else {
                    this.value = parts[0];
                }

                let newLength = this.value.length;
                cursorPosition = cursorPosition + (newLength - originalLength);
                this.setSelectionRange(cursorPosition, cursorPosition);

                const entered = parseFloat(this.value.replace(/,/g, ''));
                const payRemainingAmount = document.getElementById("pay-remaining-amount");
                const errEl = document.getElementById("payment-form-error");

                // منع القيم السالبة
                if (!isNaN(entered) && entered < 0) {
                    this.value = "";
                    this.style.borderColor = "rgba(239,68,68,0.6)";
                    this.style.background = "rgba(239,68,68,0.04)";
                    this.style.color = "#ef4444";
                    if (errEl) { errEl.textContent = "لا يمكن أن يكون المبلغ المدفوع أقل من صفر."; errEl.style.display = "block"; }
                    return;
                }

                // القيمة صحيحة — إعادة اللون الأخضر
                this.style.borderColor = "rgba(16,185,129,0.4)";
                this.style.background = "rgba(16,185,129,0.04)";
                this.style.color = "#10b981";
                if (errEl) errEl.style.display = "none";

                const liveInfo = getLiveFormTotalAndPaid();
                const safeEntered = isNaN(entered) ? 0 : entered;
                const leftAfterPay = Math.max(0, liveInfo.remaining - safeEntered);
                if (payRemainingAmount) {
                    payRemainingAmount.textContent = `${formatCurrency(leftAfterPay)} ${getCurrency()}`;
                }
            };
        }

        // زر تحصيل كامل: يعبئ السعر المتبقي الكلي الحي تلقائياً
        const btnPayFull = document.getElementById("btn-pay-full");
        if (btnPayFull) {
            btnPayFull.onclick = function() {
                if (payAmountInput) {
                    const liveInfo = getLiveFormTotalAndPaid();
                    payAmountInput.value = formatCurrency(Math.round(liveInfo.remaining));
                    payAmountInput.dispatchEvent(new Event("input"));
                }
            };
        }

        // زر ديون (آجل): يضع المبلغ المدفوع = 0 وتصبح الاستمارة بالكامل ديناً على الزبون
        const btnPayDebt = document.getElementById("btn-pay-debt");
        if (btnPayDebt) {
            btnPayDebt.onclick = function() {
                if (payAmountInput) {
                    payAmountInput.value = "0";
                    payAmountInput.dispatchEvent(new Event("input"));
                    
                    const descInp = document.getElementById("pay-description");
                    if (descInp && !descInp.value.trim()) {
                        descInp.value = "تسجيل دين آجل على الزبون";
                    }
                }
            };
        }

        // زر مسح: يفرغ حقل المبلغ
        const btnPayClear = document.getElementById("btn-pay-clear");
        if (btnPayClear) {
            btnPayClear.onclick = function() {
                if (payAmountInput) {
                    payAmountInput.value = "";
                    payAmountInput.dispatchEvent(new Event("input"));
                }
            };
        }

        const payRemainingAmount = document.getElementById("pay-remaining-amount");
        if (payRemainingAmount) payRemainingAmount.textContent = `${formatCurrency(remaining)} ${getCurrency()}`;

        const payGrandTotal = document.getElementById("pay-grand-total");
        if (payGrandTotal) payGrandTotal.textContent = `${formatCurrency(grandTotal)} ${getCurrency()}`;

        formContainer.style.display = "block";
        
        // Focus safe select
        const select = document.getElementById("pay-safe-id");
        if (select) select.focus();
    } else {
        formContainer.style.display = "none";
    }
};

window.submitPaymentForm = function(e) {
    e.preventDefault();

    const formId = state.currentActiveFormId;
    const safeId = document.getElementById("pay-safe-id").value;
    const date = document.getElementById("pay-date").value;
    const amount = parseFloat(document.getElementById("pay-amount").value.replace(/,/g, ''));
    const description = document.getElementById("pay-description").value.trim();
    const errorMsg = document.getElementById("payment-form-error");

    const liveInfo = getLiveFormTotalAndPaid();
    const remaining = liveInfo.remaining;

    // التحقق: الحقول الإلزامية (الخزنة، التاريخ، البيان)
    if (!safeId || !date || !description) {
        if (errorMsg) {
            errorMsg.textContent = "يرجى ملء جميع الحقول الإلزامية (الخزنة، التاريخ، البيان).";
            errorMsg.style.display = "block";
        }
        return;
    }

    // المبلغ: إذا كان فارغاً نعتبره 0 (مقبول)، الممنوع فقط السالب أو الأكبر من الدين المتبقي
    const safeAmount = isNaN(amount) ? 0 : amount;
    if (safeAmount < 0) {
        if (errorMsg) {
            errorMsg.textContent = "لا يمكن أن يكون المبلغ المدفوع أقل من صفر.";
            errorMsg.style.display = "block";
        }
        return;
    }

    if (remaining > 0 && safeAmount > (remaining + 0.01)) {
        if (errorMsg) {
            errorMsg.textContent = `عذراً، المبلغ المدفوع (${formatCurrency(safeAmount)}) أكبر من قيمة الدين المتبقي للفاتورة (${formatCurrency(remaining)}). لا يمكن تسديد مبلغ أكبر من قيمة الدين.`;
            errorMsg.style.display = "block";
        }
        return;
    }

    if (errorMsg) errorMsg.style.display = "none";

    const confirmBtn = document.getElementById("confirm-payment-btn");
    if (confirmBtn) confirmBtn.disabled = true;

    fetch('api/forms.php?action=pay_form', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ formId, safeId, date, amount: safeAmount, description })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message);
            togglePaymentForm(false);
            closePurchaseListModal();
            loadData(); // refresh forms status on cards
        } else {
            showToast(res.message, 'danger');
        }
    })
    .catch(() => showToast('فشل الاتصال بالخادم لإجراء الدفع', 'danger'))
    .finally(() => {
        if (confirmBtn) confirmBtn.disabled = false;
    });
};

window.formatInlinePriceInput = function(input) {
    let cursorPosition = input.selectionStart;
    let originalLength = input.value.length;

    let value = input.value.replace(/,/g, '');
    let parts = value.split('.');
    parts[0] = parts[0].replace(/\D/g, '');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    
    if (parts.length > 1) {
        parts[1] = parts[1].replace(/\D/g, '').substring(0, 2);
        input.value = parts[0] + '.' + parts[1];
    } else {
        input.value = parts[0];
    }

    let newLength = input.value.length;
    cursorPosition = cursorPosition + (newLength - originalLength);
    input.setSelectionRange(cursorPosition, cursorPosition);
};

function printContentInSamePage(htmlContent) {
    let iframe = document.getElementById("hidden-print-frame");
    if (!iframe) {
        iframe = document.createElement("iframe");
        iframe.id = "hidden-print-frame";
        iframe.style.position = "fixed";
        iframe.style.right = "0";
        iframe.style.bottom = "0";
        iframe.style.width = "0px";
        iframe.style.height = "0px";
        iframe.style.border = "none";
        iframe.style.zIndex = "-9999";
        document.body.appendChild(iframe);
    }

    const doc = iframe.contentWindow.document;
    doc.open();
    doc.write(htmlContent);
    doc.close();

    setTimeout(() => {
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
    }, 450);
}

// -------------------------------------------------------------
// 17. Printing Functions (طباعة كشف وقائمة الاستمارة)
// -------------------------------------------------------------
window.printCurrentForm = function(targetFormId = null) {
    const fid = targetFormId || state.currentActiveFormId;
    if (!fid) {
        showToast("يرجى اختيار استمارة أولاً لطباعتها", "warning");
        return;
    }

    const formObj = state.forms.find(f => String(f.id) === String(fid));
    const customerName = formObj ? formObj.customerName : '---';
    const formIndex = state.forms.findIndex(f => String(f.id) === String(fid));
    const formNumber = formIndex !== -1 ? (state.forms.length - formIndex) : fid;

    let formDate = '---';
    let formTime = '---';
    if (formObj && formObj.createdAt) {
        const d = new Date(formObj.createdAt);
        if (!isNaN(d.getTime())) {
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            formDate = `${year}-${month}-${day}`;

            let hours = d.getHours();
            const minutes = String(d.getMinutes()).padStart(2, '0');
            const ampm = hours >= 12 ? 'م' : 'ص';
            hours = hours % 12;
            hours = hours ? hours : 12;
            formTime = `${String(hours).padStart(2, '0')}:${minutes} ${ampm}`;
        } else {
            const parts = String(formObj.createdAt).split(' ');
            formDate = parts[0] || '---';
            formTime = parts[1] ? parts[1].substring(0, 5) : '---';
        }
    }

    fetch(`api/forms.php?action=get_items&form_id=${fid}`)
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') {
                showToast('فشل جلب بيانات الاستمارة للطباعة', 'danger');
                return;
            }

            const items = res.data || [];
            const totalPaid = res.totalPaid || 0;
            const previousDebt = res.previousDebt || 0;
            const cur = getCurrency();
            const FORM_FEE = 1000;

            let totQty = 0, totWeight = 0, totSubtotal = 0, totWorker = 0, totCommission = 0, totCommission10 = 0;

            const bannerPath = localStorage.getItem("header_banner_path") || 'images/header_banner.png';

            let itemsRowsHtml = items.map((item, idx) => {
                const qty = parseInt(item.quantity) || 0;
                const weight = parseFloat(item.weight) || 0;
                const price = parseFloat(item.price) || 0;
                const subtotal = item.accountingType === "وزن * سعر" ? weight * price : qty * price;
                const workerShare = calcFormula(item.workerShareType, qty, weight, price, item.accountingType);
                const commParts = calculateCommissionParts(item.commissionType, qty, weight, price, item.accountingType);
                const commission = commParts.commission;
                const commission_10 = commParts.commission_10;
                const itemTotal = subtotal + commission + commission_10;

                totQty += qty;
                totWeight += weight;
                totSubtotal += subtotal;
                totWorker += workerShare;
                totCommission += commission;
                totCommission10 += commission_10;

                return `
                    <tr>
                        <td style="text-align:center;">${idx + 1}</td>
                        <td style="font-weight:700;">${escapeHTML(item.name)}</td>
                        <td style="text-align:center;">${qty}</td>
                        <td style="text-align:center;">${weight > 0 ? weight + ' كجم' : '---'}</td>
                        <td style="text-align:center;">${formatCurrency(price)} ${cur}</td>
                        <td style="text-align:center; font-weight:700;">${formatCurrency(itemTotal)} ${cur}</td>
                    </tr>
                `;
            }).join("");

            const grandTotal = totSubtotal + totCommission + totCommission10 + FORM_FEE;
            const remaining = Math.max(0, grandTotal - totalPaid);
            const hideDebtsInfo = (remaining <= 0 && previousDebt <= 0);

            const printHtml = `
                <html lang="ar" dir="rtl">
                <head>
                    <title>قائمة شراء استمارة #${formNumber} - ${escapeHTML(customerName)}</title>
                    <link href="css/cairo.css" rel="stylesheet">
                    <link rel="stylesheet" href="css/fontawesome/css/all.min.css">
                    <style>
                        @page { size: A5 portrait; margin: 0; }
                        * { box-sizing: border-box; }
                        body { font-family: 'Cairo', sans-serif; margin: 0; padding: 0; background: #fff; color: #0f172a; direction: rtl; text-align: right; font-size: 11px; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                        
                        .banner-full-width { width: 100%; margin: 0; padding: 0; }
                        .banner-full-width img { width: 100%; height: auto; display: block; }
                        
                        .print-body-content { padding: 8px 14px 14px 14px; }
                        
                        .meta-grid { 
                            display: grid; 
                            grid-template-columns: repeat(4, 1fr); 
                            gap: 5px; 
                            background: #f8fafc; 
                            padding: 4px; 
                            border-radius: 6px; 
                            border: 1px solid #e2e8f0; 
                            margin-bottom: 8px;
                        }
                        .meta-item { 
                            display: flex; 
                            flex-direction: column; 
                            align-items: center; 
                            justify-content: center;
                            text-align: center;
                            background: #ffffff;
                            padding: 3px 2px;
                            border-radius: 5px;
                            border: 1px solid #cbd5e1;
                            line-height: 1.1;
                        }
                        .meta-item .meta-label {
                            font-size: 8.5px;
                            color: #64748b;
                            font-weight: 700;
                            margin-bottom: 1px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 3px;
                            line-height: 1;
                        }
                        .meta-item .meta-label i { font-size: 9px; color: #2563eb; }
                        .meta-item strong { color: #0f172a; font-weight: 800; font-size: 10px; line-height: 1.1; }
                        .status-badge-inline { display: inline-block; padding: 1px 8px; border-radius: 12px; font-weight: 800; font-size: 10px; }
                        .status-paid { background: #dcfce7; color: #15803d; border: 1px solid #bbf7d0; }
                        .status-debt { background: #fee2e2; color: #b91c1c; border: 1px solid #fecaca; }
                        
                        /* Modern Table */
                        table { width: 100%; border-collapse: separate; border-spacing: 0; margin-bottom: 10px; border-radius: 8px; overflow: hidden; border: 1px solid #cbd5e1; }
                        th { background: #1e293b; color: #ffffff; font-weight: 800; padding: 7px 8px; font-size: 10.5px; text-align: center; border-bottom: 2px solid #0f172a; }
                        td { border-bottom: 1px solid #e2e8f0; padding: 6px 8px; font-size: 10.5px; color: #1e293b; }
                        tr:nth-child(even) { background-color: #f8fafc; }
                        tr:last-child td { border-bottom: none; }
                        
                        /* Totals Rows */
                        tr.row-items-total { background: #f1f5f9; font-weight: 800; }
                        tr.row-fixed-fee { background: #ffffff; font-weight: 800; }
                        
                        /* 2 Side-by-Side Sections Container */
                        .bottom-summary-container { 
                            display: grid; 
                            grid-template-columns: 1fr 2fr; 
                            gap: 8px; 
                            margin-top: 10px; 
                            align-items: stretch;
                        }
                        .status-section-box {
                            background: #f8fafc;
                            border: 1.5px solid #cbd5e1;
                            border-radius: 6px;
                            padding: 10px;
                            display: flex;
                            flex-direction: column;
                            justify-content: center;
                            align-items: center;
                            text-align: center;
                        }
                        .status-section-box .status-title {
                            font-size: 11px;
                            color: #475569;
                            font-weight: 700;
                            margin-bottom: 6px;
                        }
                        .status-section-box .status-badge-big {
                            font-size: 12.5px;
                            font-weight: 900;
                            padding: 5px 14px;
                            border-radius: 20px;
                            display: inline-block;
                        }
                        .status-badge-big.paid {
                            background: #dcfce7;
                            color: #15803d;
                            border: 1.5px solid #86efac;
                        }
                        .status-badge-big.debt {
                            background: #fee2e2;
                            color: #b91c1c;
                            border: 1.5px solid #fca5a5;
                        }

                        .totals-section-box {
                            display: flex;
                            flex-direction: column;
                            gap: 5px;
                        }
                        .summary-card { 
                            background: #ffffff; 
                            border: 1.5px solid #cbd5e1; 
                            border-radius: 6px; 
                            padding: 6px 10px; 
                            display: flex; 
                            justify-content: space-between; 
                            align-items: center; 
                        }
                        .summary-card span.card-title { font-size: 10.5px; color: #475569; font-weight: 700; }
                        .summary-card span.card-val { font-size: 11.5px; font-weight: 800; }
                        
                        .summary-card.highlight { background: #f0fdf4; border-color: #86efac; color: #166534; }
                        .summary-card.danger { background: #fef2f2; border-color: #fca5a5; color: #991b1b; }
                        .summary-card.grand-total { background: #eff6ff; border-color: #93c5fd; color: #1e40af; }
                        
                        /* Signatures Area */
                        .signatures-area { 
                            display: flex; 
                            justify-content: space-between; 
                            align-items: center; 
                            margin-top: 16px; 
                            padding: 4px 20px 0 20px; 
                            font-size: 10px; 
                            font-weight: 700; 
                            color: #475569; 
                        }
                        
                        .footer-note { text-align: center; margin-top: 12px; font-size: 9.5px; color: #94a3b8; border-top: 1px dashed #e2e8f0; padding-top: 6px; }
                        
                        @media print {
                            @page { size: A5 portrait; margin: 0; }
                            body { margin: 0; padding: 0; }
                            .print-body-content { padding: 6px 10px 10px 10px; }
                        }
                    </style>
                </head>
                <body>
                    <div class="banner-full-width">
                        <img src="${escapeHTML(bannerPath)}" alt="بنر الترويسة" />
                    </div>
                    <div class="print-body-content">
                        <div class="meta-grid">
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-file-invoice" style="color:#2563eb;"></i> رقم الاستمارة</span>
                                <strong>#${formNumber}</strong>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-user" style="color:#2563eb;"></i> اسم الزبون</span>
                                <strong>${escapeHTML(customerName)}</strong>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-calendar-days" style="color:#2563eb;"></i> التاريخ</span>
                                <strong>${formDate}</strong>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-clock" style="color:#2563eb;"></i> الوقت</span>
                                <strong>${formTime}</strong>
                            </div>
                        </div>

                        <table>
                            <thead>
                                <tr>
                                    <th style="width:32px;">#</th>
                                    <th style="text-align:right;">اسم المادة</th>
                                    <th style="width:50px;">العدد</th>
                                    <th style="width:65px;">الوزن</th>
                                    <th style="width:85px;">السعر</th>
                                    <th style="width:115px;">المبلغ الإجمالي </th>
                                </tr>
                            </thead>
                            <tbody>
                                ${itemsRowsHtml || '<tr><td colspan="6" style="text-align:center; color:#94a3b8;">لا توجد مواد في الاستمارة</td></tr>'}
                                <tr class="row-fixed-fee">
                                    <td colspan="5" style="text-align:right; color:#475569;">رسوم الاستمارة الثابتة</td>
                                    <td style="text-align:center; color:#475569;">${formatCurrency(FORM_FEE)} ${cur}</td>
                                </tr>
                            </tbody>
                        </table>

                        <div class="bottom-summary-container">
                            <!-- القسم الأول: نوع الاستمارة -->
                            <div class="status-section-box">
                                <div class="status-badge-big ${remaining <= 0 ? 'paid' : 'debt'}">
                                    ${remaining <= 0 ? 'نقدي' : (totalPaid > 0 ? 'مسددة جزئياً' : 'ديون')}
                                </div>
                            </div>

                            <!-- القسم الثاني: المبالغ والديون -->
                            <div class="totals-section-box">
                                <div class="summary-card grand-total">
                                    <span class="card-title" style="font-size:11px; font-weight:800; color:#1e40af;">صافي الاستمارة مع العمولة:</span>
                                    <span class="card-val" style="font-size:13px; font-weight:900; color:#1e40af;">${formatCurrency(grandTotal)} ${cur}</span>
                                </div>
                                ${(remaining > 0 || previousDebt > 0) ? `
                                <div class="summary-card danger">
                                    <span class="card-title">الديون السابقة:</span>
                                    <span class="card-val" style="color:#b91c1c;">${formatCurrency(previousDebt)} ${cur}</span>
                                </div>
                                <div class="summary-card grand-total" style="background:#fef2f2; border-color:#fca5a5;">
                                    <span class="card-title" style="font-size:11px; font-weight:800; color:#991b1b;">مجموع الديون:</span>
                                    <span class="card-val" style="font-size:13px; font-weight:900; color:#991b1b;">${formatCurrency(remaining + previousDebt)} ${cur}</span>
                                </div>
                                ` : ''}
                            </div>
                        </div>

                        <div class="legal-note" style="text-align:center; margin-top:10px; font-size:11.5px; font-weight:900; color:#dc2626; border:1.5px solid #fca5a5; background:#fef2f2; padding:5px 10px; border-radius:6px;">
                            تعتبر هذه القائمة سنداً قانونياً
                        </div>

                        <div class="footer-note">
                            طُبعت من نظام إدارة العلاوي والمخازن • ${new Date().toLocaleString('ar-EG')}
                        </div>
                    </div>
                </body>
                </html>
            `;
            printContentInSamePage(printHtml);
        })
        .catch(() => showToast('حدث خطأ أثناء إعداد كشف الطباعة', 'danger'));
};

window.printAllForms = function() {
    const list = state.filteredForms;
    if (!list || list.length === 0) {
        showToast("لا توجد استمارات متاحة للطباعة", "warning");
        return;
    }

    const cur = getCurrency();
    let rowsHtml = list.map((item, idx) => {
        const serial = idx + 1;
        const totalPaid = item.totalPaid || 0;
        const grandTotal = item.grandTotal || 0;
        const remaining = Math.max(0, grandTotal - totalPaid);
        return `
            <tr>
                <td style="text-align:center;">${serial}</td>
                <td style="font-weight:700;">${escapeHTML(item.customerName)}</td>
                <td style="text-align:center;">${item.materialsCount} مادة</td>
                <td style="text-align:center;">${formatCurrency(grandTotal)} ${cur}</td>
                <td style="text-align:center; color:#10b981;">${formatCurrency(totalPaid)} ${cur}</td>
                <td style="text-align:center; color:#ef4444;">${formatCurrency(remaining)} ${cur}</td>
                <td style="text-align:center;">${formatDateString(item.createdAt)}</td>
            </tr>
        `;
    }).join("");

    const printHtml = `
        <html lang="ar" dir="rtl">
        <head>
            <title>كشف الاستمارات</title>
            <link href="css/cairo.css" rel="stylesheet">
            <style>
                body { font-family: 'Cairo', sans-serif; padding: 25px; background: #fff; color: #1e293b; direction: rtl; text-align: right; }
                .header-box { text-align: center; border-bottom: 2.5px solid #1e293b; padding-bottom: 12px; margin-bottom: 20px; }
                h1 { font-size: 20px; font-weight: 800; margin: 0 0 6px 0; }
                p { font-size: 13px; color: #64748b; margin: 0; }
                table { width: 100%; border-collapse: collapse; margin-top: 15px; }
                th, td { border: 1px solid #cbd5e1; padding: 9px 12px; font-size: 13px; text-align: right; }
                th { background: #f1f5f9; color: #334155; font-weight: 700; text-align: center; }
            </style>
        </head>
        <body>
            <div style="text-align:center; margin-bottom:15px;">
                <img src="images/header_banner.png" alt="بنر مكتب الهادي" style="max-width:100%; width:100%; max-height:160px; object-fit:contain; border-radius:6px;" />
            </div>
            <div class="header-box" style="border-bottom:2px solid #e2e8f0; padding-bottom:10px; margin-bottom:15px;">
                <p style="font-size:14px; font-weight:700; color:#1e293b;">كشف الاستمارات (${state.viewMode === 'current' ? 'الوردية الحالية' : 'الأيام السابقة'}) - تاريخ التقرير: ${new Date().toLocaleDateString('ar-EG')}</p>
            </div>
            <table>
                <thead>
                    <tr>
                        <th style="width:40px;">ت</th>
                        <th>اسم الزبون</th>
                        <th>عدد المواد</th>
                        <th>المبلغ الكلي</th>
                        <th>المدفوع</th>
                        <th>المتبقي</th>
                        <th>التاريخ</th>
                    </tr>
                </thead>
                <tbody>
                    ${rowsHtml}
                </tbody>
            </table>
        </body>
        </html>
    `;
    printContentInSamePage(printHtml);
};

// -------------------------------------------------------------
// 18. Multi-Selection & Batch Print Functions
// -------------------------------------------------------------
window.onFormCheckboxChange = function(event, fid) {
    if (!state.selectedFormIds) state.selectedFormIds = new Set();
    const strId = String(fid);
    if (event.target.checked) {
        state.selectedFormIds.add(strId);
    } else {
        state.selectedFormIds.delete(strId);
    }
    updateSelectedCountBadge();
};

window.toggleSelectAllForms = function() {
    if (!state.selectedFormIds) state.selectedFormIds = new Set();
    const displayedForms = state.filteredForms || [];
    const allSelected = displayedForms.length > 0 && displayedForms.every(f => state.selectedFormIds.has(String(f.id)));
    
    if (allSelected) {
        displayedForms.forEach(f => state.selectedFormIds.delete(String(f.id)));
    } else {
        displayedForms.forEach(f => state.selectedFormIds.add(String(f.id)));
    }
    renderCards(state.filteredForms);
    updateSelectedCountBadge();
};

function updateSelectedCountBadge() {
    const countEl = document.getElementById("selected-forms-count");
    if (countEl) {
        countEl.textContent = state.selectedFormIds ? state.selectedFormIds.size : 0;
    }
}

window.printSelectedForms = function() {
    const selectedIds = Array.from(state.selectedFormIds || []);
    if (selectedIds.length === 0) {
        showToast("يرجى تحديد استمارة واحدة على الأقل لطباعتها", "warning");
        return;
    }

    showToast("جاري تجهيز كشف الطباعة المجمع للاستمارات المحددة...", "info");

    const promises = selectedIds.map(fid => {
        return fetch(`api/forms.php?action=get_items&form_id=${fid}`)
            .then(r => r.json())
            .then(res => ({ fid, res }));
    });

    Promise.all(promises).then(results => {
        let allPagesHtml = [];
        const cur = getCurrency();
        const FORM_FEE = 1000;

        results.forEach(({ fid, res }, index) => {
            if (!res || res.status !== 'success') return;

            const formObj = state.forms.find(f => String(f.id) === String(fid));
            const customerName = formObj ? formObj.customerName : '---';
            const formIndex = state.forms.findIndex(f => String(f.id) === String(fid));
            const formNumber = formIndex !== -1 ? (state.forms.length - formIndex) : fid;

            let formDate = '---';
            let formTime = '---';
            if (formObj && formObj.createdAt) {
                const d = new Date(formObj.createdAt);
                if (!isNaN(d.getTime())) {
                    const year = d.getFullYear();
                    const month = String(d.getMonth() + 1).padStart(2, '0');
                    const day = String(d.getDate()).padStart(2, '0');
                    formDate = `${year}-${month}-${day}`;

                    let hours = d.getHours();
                    const minutes = String(d.getMinutes()).padStart(2, '0');
                    const ampm = hours >= 12 ? 'م' : 'ص';
                    hours = hours % 12;
                    hours = hours ? hours : 12;
                    formTime = `${String(hours).padStart(2, '0')}:${minutes} ${ampm}`;
                } else {
                    const parts = String(formObj.createdAt).split(' ');
                    formDate = parts[0] || '---';
                    formTime = parts[1] ? parts[1].substring(0, 5) : '---';
                }
            }

            const items = res.data || [];
            const totalPaid = res.totalPaid || 0;
            const previousDebt = res.previousDebt || 0;

            let totQty = 0, totWeight = 0, totSubtotal = 0, totWorker = 0, totCommission = 0, totCommission10 = 0;

            let itemsRowsHtml = items.map((item, idx) => {
                const qty = parseInt(item.quantity) || 0;
                const weight = parseFloat(item.weight) || 0;
                const price = parseFloat(item.price) || 0;
                const subtotal = item.accountingType === "وزن * سعر" ? weight * price : qty * price;
                const workerShare = calcFormula(item.workerShareType, qty, weight, price, item.accountingType);
                const commParts = calculateCommissionParts(item.commissionType, qty, weight, price, item.accountingType);
                const commission = commParts.commission;
                const commission_10 = commParts.commission_10;
                const itemTotal = subtotal + commission + commission_10;

                totQty += qty;
                totWeight += weight;
                totSubtotal += subtotal;
                totWorker += workerShare;
                totCommission += commission;
                totCommission10 += commission_10;

                return `
                    <tr>
                        <td style="text-align:center;">${idx + 1}</td>
                        <td style="font-weight:700;">${escapeHTML(item.name)}</td>
                        <td style="text-align:center;">${qty}</td>
                        <td style="text-align:center;">${weight > 0 ? weight + ' كجم' : '---'}</td>
                        <td style="text-align:center;">${formatCurrency(price)} ${cur}</td>
                        <td style="text-align:center; font-weight:700;">${formatCurrency(itemTotal)} ${cur}</td>
                    </tr>
                `;
            }).join("");

            const grandTotal = totSubtotal + totCommission + totCommission10 + FORM_FEE;
            const remaining = Math.max(0, grandTotal - totalPaid);
            const hideDebtsInfo = (remaining <= 0 && previousDebt <= 0);

            const singleFormHtml = `
                <div class="single-receipt-page ${index < results.length - 1 ? 'page-break' : ''}">
                    <div class="banner-full-width">
                        <img src="images/header_banner.png" alt="بنر مكتب الهادي" />
                    </div>
                    <div class="print-body-content">
                        <div class="meta-grid">
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-file-invoice" style="color:#2563eb;"></i> رقم الاستمارة</span>
                                <strong>#${formNumber}</strong>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-user" style="color:#2563eb;"></i> اسم الزبون</span>
                                <strong>${escapeHTML(customerName)}</strong>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-calendar-days" style="color:#2563eb;"></i> التاريخ</span>
                                <strong>${formDate}</strong>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label"><i class="fa-solid fa-clock" style="color:#2563eb;"></i> الوقت</span>
                                <strong>${formTime}</strong>
                            </div>
                        </div>

                        <table>
                            <thead>
                                <tr>
                                    <th style="width:32px;">#</th>
                                    <th style="text-align:right;">اسم المادة</th>
                                    <th style="width:50px;">العدد</th>
                                    <th style="width:65px;">الوزن</th>
                                    <th style="width:85px;">السعر</th>
                                    <th style="width:115px;">المبلغ الإجمالي للمادة</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${itemsRowsHtml || '<tr><td colspan="6" style="text-align:center; color:#94a3b8;">لا توجد مواد في الاستمارة</td></tr>'}
                                <tr class="row-fixed-fee">
                                    <td colspan="5" style="text-align:right; color:#475569;">رسوم الاستمارة الثابتة</td>
                                    <td style="text-align:center; color:#475569;">${formatCurrency(FORM_FEE)} ${cur}</td>
                                </tr>
                            </tbody>
                        </table>

                        <div class="bottom-summary-container">
                            <div class="status-section-box">
                                <div class="status-title">نوع الاستمارة</div>
                                <div class="status-badge-big ${remaining <= 0 ? 'paid' : 'debt'}">
                                    ${remaining <= 0 ? 'نقدي' : 'ديون'}
                                </div>
                            </div>

                            <div class="totals-section-box">
                                <div class="summary-card highlight">
                                    <span class="card-title">صافي الاستمارة:</span>
                                    <span class="card-val">${formatCurrency(remaining)} ${cur}</span>
                                </div>
                                ${!hideDebtsInfo ? `
                                <div class="summary-card ${previousDebt > 0 ? 'danger' : ''}">
                                    <span class="card-title">الديون السابقة:</span>
                                    <span class="card-val">${formatCurrency(previousDebt)} ${cur}</span>
                                </div>
                                <div class="summary-card grand-total">
                                    <span class="card-title" style="font-size:11.5px; font-weight:800; color:#1e40af;">مجموع الديون الكلية:</span>
                                    <span class="card-val" style="font-size:13px; font-weight:900; color:#1e40af;">${formatCurrency(remaining + previousDebt)} ${cur}</span>
                                </div>
                                ` : ''}
                            </div>
                        </div>

                        <div class="legal-note" style="text-align:center; margin-top:10px; font-size:11.5px; font-weight:900; color:#dc2626; border:1.5px solid #fca5a5; background:#fef2f2; padding:5px 10px; border-radius:6px;">
                            تعتبر هذه القائمة سنداً قانونياً
                        </div>

                        <div class="footer-note">
                            طُبعت من نظام إدارة العلاوي والمخازن • ${new Date().toLocaleString('ar-EG')}
                        </div>
                    </div>
                </div>
            `;
            allPagesHtml.push(singleFormHtml);
        });

        const batchPrintDocumentHtml = `
            <html lang="ar" dir="rtl">
            <head>
                <title>طباعة الاستمارات المحددة (${results.length})</title>
                <link href="css/cairo.css" rel="stylesheet">
                <link rel="stylesheet" href="css/fontawesome/css/all.min.css">
                <style>
                    @page { size: A5 portrait; margin: 0; }
                    * { box-sizing: border-box; }
                    body { font-family: 'Cairo', sans-serif; margin: 0; padding: 0; background: #fff; color: #0f172a; direction: rtl; text-align: right; font-size: 11px; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                    
                    .single-receipt-page { width: 100%; page-break-after: always; break-after: page; }
                    .single-receipt-page:last-child { page-break-after: avoid; break-after: avoid; }

                    .banner-full-width { width: 100%; margin: 0; padding: 0; }
                    .banner-full-width img { width: 100%; height: auto; display: block; }
                    
                    .print-body-content { padding: 8px 14px 14px 14px; }
                    
                    .meta-grid { 
                        display: grid; 
                        grid-template-columns: repeat(4, 1fr); 
                        gap: 5px; 
                        background: #f8fafc; 
                        padding: 4px; 
                        border-radius: 6px; 
                        border: 1px solid #e2e8f0; 
                        margin-bottom: 8px;
                    }
                    .meta-item { 
                        display: flex; 
                        flex-direction: column; 
                        align-items: center; 
                        justify-content: center;
                        text-align: center;
                        background: #ffffff;
                        padding: 3px 2px;
                        border-radius: 5px;
                        border: 1px solid #cbd5e1;
                        line-height: 1.1;
                    }
                    .meta-item .meta-label {
                        font-size: 8.5px;
                        color: #64748b;
                        font-weight: 700;
                        margin-bottom: 1px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        gap: 3px;
                        line-height: 1;
                    }
                    .meta-item .meta-label i { font-size: 9px; color: #2563eb; }
                    .meta-item strong { color: #0f172a; font-weight: 800; font-size: 10px; line-height: 1.1; }
                    
                    table { width: 100%; border-collapse: separate; border-spacing: 0; margin-bottom: 10px; border-radius: 8px; overflow: hidden; border: 1px solid #cbd5e1; }
                    th { background: #1e293b; color: #ffffff; font-weight: 800; padding: 7px 8px; font-size: 10.5px; text-align: center; border-bottom: 2px solid #0f172a; }
                    td { border-bottom: 1px solid #e2e8f0; padding: 6px 8px; font-size: 10.5px; color: #1e293b; }
                    tr:nth-child(even) { background-color: #f8fafc; }
                    tr:last-child td { border-bottom: none; }
                    
                    tr.row-fixed-fee { background: #ffffff; font-weight: 800; }
                    
                    .bottom-summary-container { 
                        display: grid; 
                        grid-template-columns: 1fr 2fr; 
                        gap: 8px; 
                        margin-top: 10px; 
                        align-items: stretch;
                    }
                    .status-section-box {
                        background: #f8fafc;
                        border: 1.5px solid #cbd5e1;
                        border-radius: 6px;
                        padding: 10px;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        text-align: center;
                    }
                    .status-section-box .status-title {
                        font-size: 11px;
                        color: #475569;
                        font-weight: 700;
                        margin-bottom: 6px;
                    }
                    .status-section-box .status-badge-big {
                        font-size: 12.5px;
                        font-weight: 900;
                        padding: 5px 14px;
                        border-radius: 20px;
                        display: inline-block;
                    }
                    .status-badge-big.paid {
                        background: #dcfce7;
                        color: #15803d;
                        border: 1.5px solid #86efac;
                    }
                    .status-badge-big.debt {
                        background: #fee2e2;
                        color: #b91c1c;
                        border: 1.5px solid #fca5a5;
                    }

                    .totals-section-box {
                        display: flex;
                        flex-direction: column;
                        gap: 5px;
                    }
                    .summary-card { 
                        background: #ffffff; 
                        border: 1.5px solid #cbd5e1; 
                        border-radius: 6px; 
                        padding: 6px 10px; 
                        display: flex; 
                        justify-content: space-between; 
                        align-items: center; 
                    }
                    .summary-card span.card-title { font-size: 10.5px; color: #475569; font-weight: 700; }
                    .summary-card span.card-val { font-size: 11.5px; font-weight: 800; }
                    
                    .summary-card.highlight { background: #f0fdf4; border-color: #86efac; color: #166534; }
                    .summary-card.danger { background: #fef2f2; border-color: #fca5a5; color: #991b1b; }
                    .summary-card.grand-total { background: #eff6ff; border-color: #93c5fd; color: #1e40af; }

                    .footer-note { text-align: center; margin-top: 12px; font-size: 9.5px; color: #94a3b8; border-top: 1px dashed #e2e8f0; padding-top: 6px; }
                    
                    @media print {
                        @page { size: A5 portrait; margin: 0; }
                        body { margin: 0; padding: 0; }
                        .print-body-content { padding: 6px 10px 10px 10px; }
                        .page-break { page-break-after: always; break-after: page; }
                    }
                </style>
            </head>
            <body>
                ${allPagesHtml.join("")}
            </body>
            </html>
        `;

        printContentInSamePage(batchPrintDocumentHtml);
    }).catch(err => {
        showToast("حدث خطأ أثناء تجميع الاستمارات للطباعة", "danger");
    });
};

