// Business Logic and UI Interactions for Safes/Cash Boxes Management Page

// -------------------------------------------------------------
// 1. Initial Seeding and State Management
// -------------------------------------------------------------
const INITIAL_SAFES = [
    { id: "s1", name: "الخزنة المركزية (المقر الرئيسي)", type: "primary" },
    { id: "s2", name: "صندوق مبيعات فرع البصرة", type: "secondary" },
    { id: "s3", name: "صندوق عهدة المشتريات النثرية", type: "secondary" }
];

const INITIAL_TRANSACTIONS = [
    { id: "tx001", safeId: "s1", description: "تغذية الحساب الجاري ورصيد افتتاحي", type: "deposit", date: "2026-06-01", createdAt: new Date().toISOString(), amount: 75000.00 },
    { id: "tx002", safeId: "s1", description: "تحويل جزء من السيولة لصندوق مبيعات البصرة", type: "withdrawal", date: "2026-06-02", createdAt: new Date().toISOString(), amount: 15000.00 },
    { id: "tx003", safeId: "s2", description: "استلام دفعة السيولة التأسيسية من الخزنة المركزية", type: "deposit", date: "2026-06-02", createdAt: new Date().toISOString(), amount: 15000.00 },
    { id: "tx004", safeId: "s1", description: "تحويل عهدة نقدية للمشتريات النثرية", type: "withdrawal", date: "2026-06-03", createdAt: new Date().toISOString(), amount: 3000.00 },
    { id: "tx005", safeId: "s3", description: "استلام عهدة نقدية أولى", type: "deposit", date: "2026-06-03", createdAt: new Date().toISOString(), amount: 3000.00 },
    { id: "tx006", safeId: "s3", description: "شراء قرطاسية ومستلزمات نظافة للمقر", type: "withdrawal", date: "2026-06-04", createdAt: new Date().toISOString(), amount: 285.50 },
    { id: "tx007", safeId: "s2", description: "إيداع مبيعات اليوم الأول النقدية", type: "deposit", date: "2026-06-05", createdAt: new Date().toISOString(), amount: 4850.00 },
    { id: "tx008", safeId: "s1", description: "دفع دفعة أولى من إيجار مستودع التخزين", type: "withdrawal", date: "2026-06-06", createdAt: new Date().toISOString(), amount: 12000.00 }
];

// App State
let state = {
    safes: [],
    transactions: [],
    filteredSafes: [],
    activeSafeId: null,
    searchTerm: "",
    deleteTargetId: null,
    txFromDate: "",
    txToDate: ""
};

// -------------------------------------------------------------
// 2. DOM Elements Selection
// -------------------------------------------------------------
const dom = {
    // Containers
    safesCardsContainer: document.getElementById("safes-cards-container"),
    transactionsFeed: document.getElementById("transactions-feed"),

    // Empty States
    emptyStateSafes: document.getElementById("empty-state-view"),
    emptyStateTransactions: document.getElementById("empty-state-transactions"),
    transactionsEmptyTitle: document.getElementById("transactions-empty-title"),
    transactionsEmptyDesc: document.getElementById("transactions-empty-desc"),

    // Search
    searchInput: document.getElementById("search-input"),
    searchBtn: document.getElementById("search-btn"),
    searchClearBtn: document.getElementById("search-clear-btn"),
    panelResultsInfo: document.getElementById("panel-results-info"),
    panelResultsCount: document.getElementById("panel-results-count"),

    // Stats
    statTotalBalance: document.getElementById("stat-total-balance"),
    statPrimaryBalance: document.getElementById("stat-primary-balance"),
    statSecondaryBalance: document.getElementById("stat-secondary-balance"),

    // Title
    transactionsLogTitle: document.getElementById("transactions-log-title"),

    // Modals
    safeModal: document.getElementById("safe-modal"),
    transactionModal: document.getElementById("transaction-modal"),
    deleteConfirmModal: document.getElementById("delete-confirm-modal"),

    // Safe Form
    safeForm: document.getElementById("safe-form"),
    safeIdInput: document.getElementById("safe-id"),
    safeNameInput: document.getElementById("safe-name"),
    safeTypeSelect: document.getElementById("safe-type"),
    safeNameError: document.getElementById("safe-name-error"),
    safeModalTitle: document.getElementById("modal-title"),

    // Transaction Form
    transactionForm: document.getElementById("transaction-form"),
    txTypeSelect: document.getElementById("tx-type"),
    txDescriptionInput: document.getElementById("tx-description"),
    txDateInput: document.getElementById("tx-date"),
    txAmountInput: document.getElementById("tx-amount"),
    txDescriptionError: document.getElementById("tx-description-error"),
    txDateError: document.getElementById("tx-date-error"),
    txAmountError: document.getElementById("tx-amount-error"),
    txIsDebtRepaymentCheckbox: document.getElementById("tx-is-debt-repayment"),
    txDebtorGroup: document.getElementById("tx-debtor-group"),
    txDebtorIdSelect: document.getElementById("tx-debtor-id"),
    txDebtorError: document.getElementById("tx-debtor-error"),
    txIsFormPaymentCheckbox: document.getElementById("tx-is-form-payment"),
    txFormSelectGroup: document.getElementById("tx-form-select-group"),
    txFormIdSelect: document.getElementById("tx-form-id"),
    txFormError: document.getElementById("tx-form-error"),
    debtDetailsModal: document.getElementById("debt-details-modal"),
    closeDebtDetailsModalBtn: document.getElementById("close-debt-details-modal-btn"),
    closeDebtDetailsBtn: document.getElementById("close-debt-details-btn"),
    formPaymentDetailsModal: document.getElementById("form-payment-details-modal"),
    closeFormPaymentDetailsModalBtn: document.getElementById("close-form-payment-details-modal-btn"),
    closeFormPaymentDetailsBtn: document.getElementById("close-form-payment-details-btn"),

    // Buttons
    openAddSafeBtn: document.getElementById("open-add-modal-btn"),
    emptyStateAddSafeBtn: document.getElementById("empty-state-add-btn"),
    openAddTxBtn: document.getElementById("open-transaction-modal-btn"),
    resetSafeBtn: document.getElementById("reset-safe-btn"),

    closeSafeModalBtn: document.getElementById("close-safe-modal-btn"),
    cancelSafeModalBtn: document.getElementById("cancel-safe-modal-btn"),
    closeTxModalBtn: document.getElementById("close-tx-modal-btn"),
    cancelTxModalBtn: document.getElementById("cancel-tx-modal-btn"),

    cancelDeleteBtn: document.getElementById("cancel-delete-btn"),
    confirmDeleteBtn: document.getElementById("confirm-delete-btn"),
    deleteItemName: document.getElementById("delete-item-name"),

    // Reset Safe Modal
    resetSafeModal: document.getElementById("reset-safe-modal"),
    closeResetModalBtn: document.getElementById("close-reset-modal-btn"),
    cancelResetModalBtn: document.getElementById("cancel-reset-modal-btn"),
    resetSafeForm: document.getElementById("reset-safe-form"),
    resetReceiverNameInput: document.getElementById("reset-receiver-name"),

    // Theme Toggle
    themeToggle: document.getElementById("theme-toggle"),

    // Toast Container
    toastContainer: document.getElementById("toast-container")
};

let lastStates = {};
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                let hasChanges = false;
                targetTables.forEach(t => {
                    const newTs = res.states[t] || 0;
                    if (lastStates[t] !== undefined && lastStates[t] !== newTs) {
                        hasChanges = true;
                    }
                    lastStates[t] = newTs;
                });
                if (hasChanges) {
                    refreshCallback();
                }
            }
        })
        .catch(err => console.error("Error checking states:", err));
}

// -------------------------------------------------------------
// 3. App Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    // Populate initial states
    fetch('api/check_state.php')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => { });

    loadData();
    setInterval(() => {
        checkSystemStateAndRefresh(['safe_transactions'], loadData);
    }, 3000);
    initTheme();
    setupEventListeners();
    applyFilters();
});

// Load data from MySQL database
let lastSafesJson = "";
let lastTransactionsJson = "";
let lastFormsJson = "";
let lastDebtorsJson = "";
let lastMaterialsJson = "";

function loadData() {
    Promise.all([
        fetch('api/safes.php?action=list').then(r => r.json()).catch(() => null),
        fetch('api/forms.php?action=list').then(r => r.json()).catch(() => null),
        fetch('api/debts.php?action=list_debtors').then(r => r.json()).catch(() => null),
        fetch('api/materials.php?action=list').then(r => r.json()).catch(() => null)
    ])
        .then(([safeRes, formRes, debtRes, matRes]) => {
            let changed = false;

            if (safeRes && safeRes.status === 'success') {
                const sj = JSON.stringify(safeRes.safes);
                const tj = JSON.stringify(safeRes.transactions);
                if (sj !== lastSafesJson || tj !== lastTransactionsJson) {
                    lastSafesJson = sj;
                    lastTransactionsJson = tj;
                    state.safes = safeRes.safes;
                    state.transactions = safeRes.transactions;
                    changed = true;
                }
            }
            if (formRes && formRes.status === 'success') {
                const fj = JSON.stringify(formRes.data);
                if (fj !== lastFormsJson) {
                    lastFormsJson = fj;
                    state.forms = formRes.data;
                    changed = true;
                }
            }
            if (debtRes && debtRes.status === 'success') {
                const dj = JSON.stringify(debtRes.debtors);
                if (dj !== lastDebtorsJson) {
                    lastDebtorsJson = dj;
                    state.debtors = debtRes.debtors;
                    changed = true;
                }
            }
            if (matRes && matRes.status === 'success') {
                const mj = JSON.stringify(matRes.materials);
                if (mj !== lastMaterialsJson) {
                    lastMaterialsJson = mj;
                    state.materials = matRes.materials;
                    changed = true;
                }
            }

            if (changed) {
                applyFilters();

                // Keep the active safe selected if it still exists
                if (state.activeSafeId) {
                    const safeExists = state.safes.some(s => String(s.id) === String(state.activeSafeId));
                    if (safeExists) {
                        selectSafe(state.activeSafeId);
                    } else {
                        resetActiveSafeView();
                    }
                }
            }
        })
        .catch(err => {
            console.error(err);
        });
}

function resetActiveSafeView() {
    state.activeSafeId = null;
    dom.openAddTxBtn.setAttribute("disabled", "true");
    if (dom.resetSafeBtn) dom.resetSafeBtn.setAttribute("disabled", "true");
    const filterBar = document.getElementById("safe-tx-filter-bar");
    if (filterBar) filterBar.style.display = "none";
    dom.transactionsLogTitle.textContent = "حركات الصندوق: (اختر صندوقاً لعرض حركاته)";
    dom.transactionsFeed.style.display = "none";
    dom.emptyStateTransactions.style.display = "flex";
    dom.transactionsEmptyTitle.textContent = "لم يتم اختيار أي صندوق";
    dom.transactionsEmptyDesc.textContent = "الرجاء النقر على زر 'عرض الحركات' بجانب اسم الصندوق لعرض العمليات المالية الخاصة به.";
}

// -------------------------------------------------------------
// 4. Dark/Light Theme Management
// -------------------------------------------------------------
function initTheme() {
    const savedTheme = localStorage.getItem("dashboard_theme");
    if (savedTheme === "dark") {
        document.body.classList.add("dark-theme");
        dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
    } else {
        document.body.classList.remove("dark-theme");
        dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
    }
}

function toggleTheme() {
    if (document.body.classList.contains("dark-theme")) {
        document.body.classList.remove("dark-theme");
        dom.themeToggle.innerHTML = '<i class="fa-solid fa-moon"></i>';
        localStorage.setItem("dashboard_theme", "light");
        showToast("تم تفعيل الوضع المضيء", "info");
    } else {
        document.body.classList.add("dark-theme");
        dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
        localStorage.setItem("dashboard_theme", "dark");
        showToast("تم تفعيل الوضع الداكن", "info");
    }
}

// -------------------------------------------------------------
// 5. Toast Notification System
// -------------------------------------------------------------
function showToast(message, type = "success") {
    const toast = document.createElement("div");
    toast.className = `toast toast-${type}`;

    let iconClass = "fa-circle-check";
    if (type === "danger") iconClass = "fa-circle-xmark";
    if (type === "warning") iconClass = "fa-circle-exclamation";
    if (type === "info") iconClass = "fa-circle-info";

    toast.innerHTML = `
        <i class="fa-solid ${iconClass} toast-icon"></i>
        <span class="toast-message">${message}</span>
    `;

    dom.toastContainer.appendChild(toast);

    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// -------------------------------------------------------------
// 6. Dynamic Balance & Stats Calculations
// -------------------------------------------------------------
// Returns balance of a single safe based on transaction history
function calculateSafeBalance(safeId) {
    const safeTx = state.transactions.filter(t => t.safeId === safeId);
    return safeTx.reduce((balance, tx) => {
        const amt = parseFloat(tx.amount);
        return tx.type === "deposit" ? balance + amt : (tx.type === "withdrawal" ? balance - amt : balance);
    }, 0);
}

function updateStatistics() {
    let total = 0;
    let primary = 0;
    let secondary = 0;

    state.safes.forEach(safe => {
        const balance = calculateSafeBalance(safe.id);
        total += balance;
        if (safe.type === "primary") {
            primary += balance;
        } else {
            secondary += balance;
        }
    });

    dom.statTotalBalance.textContent = `${formatCurrency(total)} ${getCurrency()}`;
    dom.statPrimaryBalance.textContent = `${formatCurrency(primary)} ${getCurrency()}`;
    dom.statSecondaryBalance.textContent = `${formatCurrency(secondary)} ${getCurrency()}`;
}

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

// Helper to get low balance threshold from settings
function getLowBalanceThreshold() {
    const settings = localStorage.getItem("dashboard_settings");
    if (settings) {
        try {
            const parsed = JSON.parse(settings);
            return parsed.lowBalanceThreshold !== undefined ? parseFloat(parsed.lowBalanceThreshold) : 1000000;
        } catch (e) {
            return 1000000;
        }
    }
    return 1000000;
}

// 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 determine the work day date string (YYYY-MM-DD) for a given date object or string
function getWorkDayDate(dateInput) {
    const d = new Date(dateInput);
    if (isNaN(d.getTime())) {
        return dateInput; // Fallback for raw YYYY-MM-DD strings without time
    }

    // If it's a date string like "2026-06-21" without a time component, treat it as is
    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}`;
}

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

// -------------------------------------------------------------
// 7. Search and Filtering Logic
// -------------------------------------------------------------
function applyFilters() {
    state.searchTerm = dom.searchInput.value.trim().toLowerCase();

    if (state.searchTerm === "") {
        state.filteredSafes = [...state.safes];
        if (dom.panelResultsInfo) {
            dom.panelResultsInfo.classList.remove("visible");
        }
    } else {
        state.filteredSafes = state.safes.filter(safe => {
            return safe.name.toLowerCase().includes(state.searchTerm) ||
                (safe.type === "primary" ? "أساسي" : "ثانوي").includes(state.searchTerm);
        });
        if (dom.panelResultsInfo && dom.panelResultsCount) {
            dom.panelResultsInfo.classList.add("visible");
            dom.panelResultsCount.textContent = state.filteredSafes.length;
        }
    }

    renderSafesCards();
    updateStatistics();
}

// Search action
window.doSearchSafes = function () {
    applyFilters();
    if (dom.searchInput) dom.searchInput.focus();
};

// Clear search
window.clearSearchSafes = function () {
    if (dom.searchInput) dom.searchInput.value = "";
    if (dom.panelResultsInfo) dom.panelResultsInfo.classList.remove("visible");
    applyFilters();
};

// -------------------------------------------------------------
// 8. Dynamic DOM Rendering (Safes Digital Cards)
// -------------------------------------------------------------
function renderSafesCards() {
    dom.safesCardsContainer.innerHTML = "";
    const list = state.filteredSafes;

    if (list.length === 0) {
        dom.safesCardsContainer.style.display = "none";
        dom.emptyStateSafes.style.display = "flex";
        return;
    }

    dom.safesCardsContainer.style.display = "grid";
    dom.emptyStateSafes.style.display = "none";

    list.forEach((safe, index) => {
        const balance = calculateSafeBalance(safe.id);
        const isActive = String(state.activeSafeId) === String(safe.id);
        const isMainSafe = String(safe.id) === "1" || safe.name.includes("الرئيسية") || safe.name.includes("المركزية");

        const lowBalanceLimit = getLowBalanceThreshold();
        const isLowBalance = balance < lowBalanceLimit;

        const cardDiv = document.createElement("div");
        cardDiv.className = `safe-digital-card ${isActive ? 'active' : ''} ${isLowBalance ? 'warning-glow' : ''}`;
        cardDiv.id = `safe-card-${safe.id}`;

        // Gradient color sets
        const gradientClass = safe.type === "primary" ? "card-gradient-primary" : "card-gradient-secondary";
        cardDiv.classList.add(gradientClass);

        cardDiv.innerHTML = `
            <div class="card-chip"></div>
            <div class="card-brand"><i class="fa-solid fa-vault"></i></div>
            <div class="card-info-header">
                <span class="card-type-chip ${safe.type === 'primary' ? 'primary' : 'secondary'}">
                    ${safe.type === 'primary' ? 'صندوق أساسي' : 'صندوق ثانوي'}
                </span>
                ${isLowBalance ? '<span class="card-type-chip warning" style="background-color: var(--danger-light); color: var(--danger); font-weight: 700; border: 1px solid var(--danger);"><i class="fa-solid fa-triangle-exclamation"></i> رصيد منخفض</span>' : ''}
                <span class="card-serial">#${index + 1}</span>
            </div>
            <h3 class="card-name" title="${escapeHTML(safe.name)}">${escapeHTML(safe.name)}</h3>
            <div class="card-balance">
                <span class="currency-label">الرصيد المتوفر</span>
                <h2 class="balance-value">${formatCurrency(balance)} <span class="sar">${getCurrency()}</span></h2>
            </div>
            <div class="card-actions">
                <button class="card-action-btn btn-edit" onclick="event.stopPropagation(); openEditSafeModal('${safe.id}')" title="تعديل">
                    <i class="fa-solid fa-pen-to-square"></i>
                </button>
                ${isMainSafe ? '' : `
                <button class="card-action-btn btn-delete" onclick="event.stopPropagation(); openDeleteSafeModal('${safe.id}')" title="حذف">
                    <i class="fa-solid fa-trash-can"></i>
                </button>
                `}
            </div>
            <div class="card-quick-actions" style="margin-top: 14px; display: flex; gap: 6px; border-top: 1px solid rgba(255,255,255,0.15); padding-top: 10px;">
                <button class="btn btn-sm" onclick="event.stopPropagation(); window.openAddTxForSafe('${safe.id}')" style="flex:1; background: rgba(255,255,255,0.2); color: #fff; border: 1px solid rgba(255,255,255,0.3); padding: 6px 8px; font-size: 11px; font-weight: 700; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 4px; font-family: var(--font-family);" title="إضافة حركة مالية لهذه القاصة">
                    <i class="fa-solid fa-plus-circle"></i> إضافة حركة
                </button>
                <button class="btn btn-sm" onclick="event.stopPropagation(); window.openResetSafeForSafe('${safe.id}')" style="flex:1; background: rgba(239, 68, 68, 0.3); color: #fff; border: 1px solid rgba(239, 68, 68, 0.5); padding: 6px 8px; font-size: 11px; font-weight: 700; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 4px; font-family: var(--font-family);" title="تصفير رصيد هذه القاصة">
                    <i class="fa-solid fa-rotate-left"></i> تصفير
                </button>
            </div>
            ${isActive ? '<div class="card-active-indicator"><i class="fa-solid fa-circle-check"></i> نشط</div>' : ''}
        `;

        cardDiv.addEventListener("click", () => selectSafe(safe.id));
        dom.safesCardsContainer.appendChild(cardDiv);
    });
}

// Global helpers for safe card quick actions
window.openAddTxForSafe = function (safeId) {
    selectSafe(safeId);
    openAddTxModal();
};

window.openResetSafeForSafe = function (safeId) {
    selectSafe(safeId);
    const balance = calculateSafeBalance(safeId);
    if (balance <= 0.01) {
        showToast("رصيد القاصة مساوٍ للصفر بالفعل أو سالب، لا يمكن تصفيره", "warning");
        return;
    }
    if (dom.resetReceiverNameInput) dom.resetReceiverNameInput.value = "";
    if (dom.resetSafeModal) dom.resetSafeModal.classList.add("open");
};

// Select safe to load transaction journal
function selectSafe(safeId) {
    const safe = state.safes.find(s => String(s.id) === String(safeId));
    if (!safe) return;

    // Remove active class from all cards
    document.querySelectorAll(".safe-digital-card").forEach(card => {
        card.classList.remove("active");
        // Remove the active indicator element if exists
        const indicator = card.querySelector(".card-active-indicator");
        if (indicator) indicator.remove();
    });

    // Add active class and indicator to selected card
    const card = document.getElementById(`safe-card-${safeId}`);
    if (card) {
        card.classList.add("active");
        const indicator = document.createElement("div");
        indicator.className = "card-active-indicator";
        indicator.innerHTML = '<i class="fa-solid fa-circle-check"></i> نشط';
        card.appendChild(indicator);
    }

    state.activeSafeId = safeId;
    dom.openAddTxBtn.removeAttribute("disabled");
    if (dom.resetSafeBtn) dom.resetSafeBtn.removeAttribute("disabled");
    const filterBar = document.getElementById("safe-tx-filter-bar");
    if (filterBar) filterBar.style.display = "flex";
    dom.transactionsLogTitle.textContent = `حركات صندوق: ${safe.name}`;

    renderTransactionsFeed(safeId);
}

// -------------------------------------------------------------
// 9. Dynamic DOM Rendering (Transactions Activity Feed & Filters)
// -------------------------------------------------------------
window.applyTxDateFilter = function () {
    const fromEl = document.getElementById("tx-from-date");
    const toEl = document.getElementById("tx-to-date");
    state.txFromDate = fromEl ? fromEl.value : "";
    state.txToDate = toEl ? toEl.value : "";
    if (state.activeSafeId) {
        renderTransactionsFeed(state.activeSafeId);
    }
};

window.setQuickTxDate = function (preset) {
    const fromEl = document.getElementById("tx-from-date");
    const toEl = document.getElementById("tx-to-date");
    if (preset === 'today') {
        const today = new Date().toISOString().substring(0, 10);
        if (fromEl) fromEl.value = today;
        if (toEl) toEl.value = today;
        state.txFromDate = today;
        state.txToDate = today;
    } else {
        if (fromEl) fromEl.value = "";
        if (toEl) toEl.value = "";
        state.txFromDate = "";
        state.txToDate = "";
    }
    if (state.activeSafeId) {
        renderTransactionsFeed(state.activeSafeId);
    }
};

window.exportSafeTransactionsToExcel = function () {
    if (!state.activeSafeId) {
        showToast("يرجى اختيار صندوق أولاً لتصدير حركاته", "warning");
        return;
    }
    const safe = state.safes.find(s => String(s.id) === String(state.activeSafeId));
    let txList = state.transactions.filter(t => String(t.safeId) === String(state.activeSafeId));
    if (state.txFromDate) txList = txList.filter(t => (t.date || "").substring(0, 10) >= state.txFromDate);
    if (state.txToDate) txList = txList.filter(t => (t.date || "").substring(0, 10) <= state.txToDate);
    txList.sort((a, b) => new Date(b.date) - new Date(a.date));

    if (txList.length === 0) {
        showToast("لا توجد حركات مالية مطابقة لتصديرها", "warning");
        return;
    }

    let csv = "\uFEFFت,اسم الصندوق,نوع الحركة,المبلغ (د.ع),البيان,تاريخ الحركة\n";
    txList.forEach((t, index) => {
        const typeText = t.type === 'deposit' ? 'إيداع' : 'سحب';
        const safeName = safe ? safe.name : '';
        const desc = (t.description || '').replace(/"/g, '""');
        csv += `${index + 1},"${safeName}","${typeText}",${t.amount},"${desc}","${t.date}"\n`;
    });

    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = `حركات_صندوق_${safe ? safe.name : 'مالي'}_${new Date().toISOString().substring(0, 10)}.csv`;
    link.click();
    showToast("تم تصدير ملف Excel بنجاح", "success");
};

window.printSafeTransactionsReport = function () {
    let safeId = state.activeSafeId;
    if (!safeId && state.safes && state.safes.length > 0) {
        safeId = state.safes[0].id;
        state.activeSafeId = safeId;
    }
    if (!safeId) {
        showToast("لا توجد صناديق مفرزة لطباعة كشف الحركات", "warning");
        return;
    }
    const safe = state.safes.find(s => String(s.id) === String(safeId));
    let txList = state.transactions.filter(t => String(t.safeId) === String(safeId));
    if (state.txFromDate) txList = txList.filter(t => (t.date || "").substring(0, 10) >= state.txFromDate);
    if (state.txToDate) txList = txList.filter(t => (t.date || "").substring(0, 10) <= state.txToDate);
    txList.sort((a, b) => new Date(b.date) - new Date(a.date));

    const orgName = getOrgName();
    const cur = getCurrency();
    const today = new Date().toLocaleDateString('ar-IQ', { year: 'numeric', month: 'long', day: 'numeric' });

    let totalDepositSum = 0;
    let totalWithdrawalSum = 0;

    let rowsHtml = txList.map((t, idx) => {
        const amt = parseFloat(t.amount || 0);
        if (t.type === 'deposit') {
            totalDepositSum += amt;
        } else {
            totalWithdrawalSum += amt;
        }
        const typeBadge = t.type === 'deposit'
            ? '<span style="color:#059669; font-weight:800; background:#ecfdf5; padding:2px 8px; border-radius:4px;">إيداع (+)</span>'
            : '<span style="color:#dc2626; font-weight:800; background:#fef2f2; padding:2px 8px; border-radius:4px;">سحب (-)</span>';

        return `
            <tr>
                <td style="text-align:center; font-weight:700; color:#64748b;">${idx + 1}</td>
                <td style="text-align:center;">${escapeHTML(t.date)}</td>
                <td style="text-align:center;">${typeBadge}</td>
                <td style="text-align:center; font-weight:900; direction:ltr; color:${t.type === 'deposit' ? '#059669' : '#dc2626'};">${amt.toLocaleString('ar-IQ')} ${cur}</td>
                <td>${escapeHTML(t.description)}</td>
            </tr>
        `;
    }).join("");

    if (txList.length === 0) {
        rowsHtml = `<tr><td colspan="5" style="text-align:center; padding:20px; color:#64748b;">لا توجد حركات مالية مسجلة في هذه الفترة</td></tr>`;
    }

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

    const netBal = totalDepositSum - totalWithdrawalSum;

    printWin.document.write(`<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>تقرير كشف حركات صندوق – ${safe ? escapeHTML(safe.name) : ''}</title>
<style>
    @page { size: A4 portrait; margin: 12mm 10mm; }
    @media print {
        body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        .no-print { display: none !important; }
        thead { display: table-header-group; }
        tfoot { display: table-footer-group; }
        tr { page-break-inside: avoid; }
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
        font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
        font-size: 11.5px;
        color: #0f172a;
        background: #ffffff;
        direction: rtl;
        padding: 10px;
    }
    .report-card {
        border: 1.5px solid #cbd5e1;
        border-radius: 12px;
        padding: 20px 24px;
        max-width: 920px;
        margin: 0 auto;
    }
    .report-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #0f172a;
        padding-bottom: 14px;
        margin-bottom: 16px;
    }
    .brand-box {
        display: flex;
        align-items: center;
        gap: 12px;
    }
    .brand-icon {
        width: 48px; height: 48px;
        border-radius: 12px;
        background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%);
        color: #ffffff;
        font-size: 24px;
        display: flex; align-items: center; justify-content: center;
    }
    .brand-name {
        font-size: 20px;
        font-weight: 900;
        color: #0f172a;
        margin: 0 0 2px 0;
    }
    .brand-sub {
        font-size: 11px;
        color: #64748b;
        font-weight: 600;
    }
    .report-title-box {
        text-align: right;
    }
    .report-title {
        font-size: 18px;
        font-weight: 900;
        color: #0284c7;
        margin-bottom: 4px;
    }
    .report-meta {
        font-size: 11px;
        color: #475569;
        line-height: 1.5;
    }

    .kpi-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
        margin-bottom: 16px;
    }
    .kpi-box {
        background: #f8fafc;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        padding: 10px 14px;
        text-align: center;
    }
    .kpi-label { font-size: 10.5px; color: #64748b; font-weight: 700; margin-bottom: 4px; }
    .kpi-val { font-size: 14px; font-weight: 900; color: #0f172a; }
    .kpi-val.green { color: #059669; }
    .kpi-val.red { color: #dc2626; }
    .kpi-val.sky { color: #0284c7; }

    table.report-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 16px;
        font-size: 11.5px;
    }
    table.report-table th {
        background: #0f172a;
        color: #ffffff;
        font-weight: 800;
        padding: 9px 10px;
        border: 1px solid #0f172a;
        text-align: center;
    }
    table.report-table td {
        padding: 8px 10px;
        border: 1px solid #cbd5e1;
        vertical-align: middle;
    }
    table.report-table tbody tr:nth-child(even) {
        background: #f8fafc;
    }

    .report-footer {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        border-top: 1.5px dashed #94a3b8;
        padding-top: 14px;
        margin-top: 16px;
    }
    .sig-block {
        text-align: center;
        width: 170px;
    }
    .sig-title { font-size: 11px; font-weight: 700; color: #475569; margin-bottom: 30px; }
    .sig-line { border-bottom: 1px solid #64748b; }
    .stamp-text { font-size: 10px; color: #94a3b8; text-align: center; }
</style>
</head>
<body>
<div class="report-card">
    <table style="width:100%; border-collapse:collapse; border:none;">
        <thead>
            <tr>
                <td style="border:none; padding:0; background:transparent; text-align:right; font-weight:normal;">
                    <div class="report-header">
                        <div class="brand-box">
                            <div class="brand-icon">🏦</div>
                            <div>
                                <h1 class="brand-name">${escapeHTML(orgName)}</h1>
                                <div class="brand-sub">سجل حركة الصناديق والخزائن المالية</div>
                            </div>
                        </div>
                        <div class="report-title-box">
                            <div class="report-title">كشف حركات الصندوق</div>
                            <div class="report-meta">
                                <div>تاريخ التقرير: <strong>${today}</strong></div>
                                <div>اسم الصندوق: <strong>${safe ? escapeHTML(safe.name) : ''}</strong></div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="border:none; padding:0;">
                    <div class="kpi-grid">
                        <div class="kpi-box">
                            <div class="kpi-label">عدد الحركات بالتقرير</div>
                            <div class="kpi-val">${txList.length} حركة</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">إجمالي الإيداعات</div>
                            <div class="kpi-val green">+${totalDepositSum.toLocaleString('ar-IQ')} ${cur}</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">إجمالي السحوبات</div>
                            <div class="kpi-val red">-${totalWithdrawalSum.toLocaleString('ar-IQ')} ${cur}</div>
                        </div>
                        <div class="kpi-box">
                            <div class="kpi-label">صافي الحركة بالفترة</div>
                            <div class="kpi-val sky">${netBal >= 0 ? '+' : ''}${netBal.toLocaleString('ar-IQ')} ${cur}</div>
                        </div>
                    </div>

                    <table class="report-table">
                        <thead>
                            <tr>
                                <th style="width:40px;">ت</th>
                                <th style="width:110px;">تاريخ الحركة</th>
                                <th style="width:100px;">نوع الحركة</th>
                                <th style="width:140px;">المبلغ</th>
                                <th>البيان (الوصف)</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${rowsHtml}
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td style="border:none; padding:0;">
                    <div class="report-footer">
                        <div class="sig-block">
                            <div class="sig-title">اعتماد أمين الصندوق</div>
                            <div class="sig-line"></div>
                        </div>
                        <div class="stamp-text">
                            تم استخراج التقرير إلكترونياً من نظام ${escapeHTML(orgName)}
                        </div>
                        <div class="sig-block">
                            <div class="sig-title">توقيع المحاسب الرئيسي</div>
                            <div class="sig-line"></div>
                        </div>
                    </div>
                </td>
            </tr>
        </tfoot>
    </table>
</div>
<script>
    window.onload = function() {
        setTimeout(function() { window.print(); }, 400);
    };
<\/script>
</body>
</html>`);
    printWin.document.close();
};

function renderTransactionsFeed(safeId) {
    dom.transactionsFeed.innerHTML = "";

    // Fetch and sort transactions for safe (newest first)
    let txList = state.transactions
        .filter(t => String(t.safeId) === String(safeId));

    if (state.txFromDate) {
        txList = txList.filter(t => (t.date || "").substring(0, 10) >= state.txFromDate);
    }
    if (state.txToDate) {
        txList = txList.filter(t => (t.date || "").substring(0, 10) <= state.txToDate);
    }

    txList.sort((a, b) => new Date(b.date) - new Date(a.date));

    if (txList.length === 0) {
        dom.transactionsFeed.style.display = "none";
        dom.emptyStateTransactions.style.display = "flex";
        dom.transactionsEmptyTitle.textContent = "لا يوجد حركات مالية مسجلة";
        dom.transactionsEmptyDesc.textContent = "هذا الصندوق فارغ حالياً. اضغط على زر 'إضافة حركة مالية' لبدء عمليات الإيداع والسحب.";
        return;
    }

    dom.transactionsFeed.style.display = "flex";
    dom.emptyStateTransactions.style.display = "none";

    // Load forms to check payment completion status
    let forms = state.forms || [];

    txList.forEach((tx, index) => {
        const itemDiv = document.createElement("div");
        itemDiv.className = "activity-item";

        let iconClass, typeClass, prefix;
        const isRepayment = tx.debtorId && tx.debtorId !== "";
        const isFormPayment = tx.formId && tx.formId !== "";

        let displayDesc = tx.description;
        if (isFormPayment) {
            const form = forms.find(f => String(f.id) === String(tx.formId));
            if (form) {
                const formIndex = forms.findIndex(f => String(f.id) === String(tx.formId));
                const formNumber = forms.length - formIndex;
                const formDate = form.createdAt ? form.createdAt.substring(0, 10) : '';
                displayDesc = `تحصيل دفعة من استمارة الزبون: ${form.customerName} رقم: #${formNumber} بتاريخ: ${formDate}`;
            }

            const formTotal = calculateFormTotal(form);
            const formTxList = state.transactions.filter(t => String(t.formId) === String(tx.formId));
            const totalPaid = formTxList.reduce((sum, t) => sum + parseFloat(t.amount), 0);

            const isFull = (totalPaid >= formTotal - 0.01);
            if (isFull) {
                itemDiv.classList.add("form-payment-full");
                iconClass = "fa-file-circle-check";
                typeClass = "form-payment-full";
            } else {
                itemDiv.classList.add("form-payment-partial");
                iconClass = "fa-file-invoice-dollar";
                typeClass = "form-payment-partial";
            }
            prefix = "+";
            itemDiv.style.cursor = "pointer";
            itemDiv.addEventListener("click", () => viewFormPaymentDetails(tx));
        } else if (isRepayment) {
            const isWithdrawal = tx.type === "withdrawal" || tx.type === "debt";
            itemDiv.classList.add(isWithdrawal ? "withdrawal" : "repayment");
            iconClass = "fa-hand-holding-dollar";
            typeClass = isWithdrawal ? "withdrawal" : "repayment";
            prefix = isWithdrawal ? "-" : "+";
            itemDiv.style.cursor = "pointer";
            itemDiv.addEventListener("click", () => viewDebtDetails(tx));
        } else {
            if (tx.type === "deposit") {
                itemDiv.classList.add("deposit");
                iconClass = "fa-circle-down";
                typeClass = "deposit";
                prefix = "+";
            } else {
                itemDiv.classList.add("withdrawal");
                iconClass = "fa-arrow-up-from-bracket";
                typeClass = "withdrawal";
                prefix = "-";
            }
        }

        const isResetTx = displayDesc && displayDesc.includes("تصفير");

        itemDiv.innerHTML = `
            <div class="activity-icon ${typeClass}">
                <i class="fa-solid ${iconClass}"></i>
            </div>
            <div class="activity-details">
                <h4 class="activity-desc">${escapeHTML(displayDesc)}</h4>
                <span class="activity-date"><i class="fa-regular fa-calendar"></i> ${escapeHTML(tx.date)}</span>
            </div>
            <div style="display:flex; align-items:center; gap:8px;">
                <div class="activity-amount ${typeClass}">
                    ${prefix} ${formatCurrency(tx.amount)} ${getCurrency()}
                </div>
                ${isResetTx ? `
                    <button class="btn btn-secondary-outline" style="padding:4px 8px; font-size:11px; border-radius:6px; height:28px;" onclick="event.stopPropagation(); printTxResetReceipt('${tx.id}')" title="طباعة وصل الدفع والتسليم">
                        <i class="fa-solid fa-print"></i> وصل دفع
                    </button>
                ` : ''}
            </div>
        `;
        dom.transactionsFeed.appendChild(itemDiv);
    });
}

// -------------------------------------------------------------
// 10. Modals Control Functions
// -------------------------------------------------------------
// Safe Modals
window.openEditSafeModal = function (id) {
    const safe = state.safes.find(s => s.id === id);
    if (!safe) return;

    clearSafeValidationErrors();
    dom.safeModalTitle.textContent = "تعديل بيانات الصندوق";
    dom.safeIdInput.value = safe.id;
    dom.safeNameInput.value = safe.name;
    dom.safeTypeSelect.value = safe.type;

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

function openAddSafeModal() {
    clearSafeValidationErrors();
    dom.safeModalTitle.textContent = "إضافة صندوق جديد";
    dom.safeForm.reset();
    dom.safeIdInput.value = "";
    dom.safeModal.classList.add("open");
}

function closeSafeModal() {
    dom.safeModal.classList.remove("open");
    dom.safeForm.reset();
    clearSafeValidationErrors();
}

// Transaction Modals
function openAddTxModal() {
    if (!state.activeSafeId) return;
    clearTxValidationErrors();
    dom.transactionForm.reset();

    // Load debtors into dropdown
    let debtors = state.debtors || [];
    dom.txDebtorIdSelect.innerHTML = '<option value="">-- اختر الزبون --</option>';
    debtors.forEach(d => {
        const option = document.createElement("option");
        option.value = d.id;
        option.textContent = d.name;
        dom.txDebtorIdSelect.appendChild(option);
    });

    // Load purchase forms into dropdown
    let forms = state.forms || [];
    dom.txFormIdSelect.innerHTML = '<option value="">-- اختر الاستمارة --</option>';
    forms.forEach((form, idx) => {
        const formNum = forms.length - idx; // matching forms.js numbering
        const total = calculateFormTotal(form);
        const option = document.createElement("option");
        option.value = form.id;
        option.textContent = `[#${formNum}] ${form.customerName} - (${form.createdAt ? form.createdAt.substring(0, 10) : ''}) - ${formatCurrency(total)} ${getCurrency()}`;
        dom.txFormIdSelect.appendChild(option);
    });

    dom.txDebtorGroup.style.display = "none";
    dom.txIsDebtRepaymentCheckbox.checked = false;
    dom.txFormSelectGroup.style.display = "none";
    dom.txIsFormPaymentCheckbox.checked = false;
    dom.txTypeSelect.disabled = false;

    // Set default date to today's active work day
    dom.txDateInput.value = getWorkDayDate(new Date());
    dom.transactionModal.classList.add("open");
}

function closeTxModal() {
    dom.transactionModal.classList.remove("open");
    dom.transactionForm.reset();
    dom.txDebtorGroup.style.display = "none";
    dom.txIsDebtRepaymentCheckbox.checked = false;
    dom.txFormSelectGroup.style.display = "none";
    dom.txIsFormPaymentCheckbox.checked = false;
    dom.txTypeSelect.disabled = false;
    clearTxValidationErrors();
}

// Delete Modals
window.openDeleteSafeModal = function (id) {
    const safe = state.safes.find(s => s.id === id);
    if (!safe) return;

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

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

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

function clearTxValidationErrors() {
    dom.txDescriptionInput.closest(".form-group").classList.remove("has-error");
    dom.txDateInput.closest(".form-group").classList.remove("has-error");
    dom.txAmountInput.closest(".form-group").classList.remove("has-error");
    if (dom.txDebtorIdSelect.closest(".form-group")) {
        dom.txDebtorIdSelect.closest(".form-group").classList.remove("has-error");
    }
    if (dom.txFormIdSelect.closest(".form-group")) {
        dom.txFormIdSelect.closest(".form-group").classList.remove("has-error");
    }
}

// Safe Form Submit
function handleSafeSubmit(e) {
    e.preventDefault();

    const id = dom.safeIdInput.value;
    const name = dom.safeNameInput.value.trim();
    const type = dom.safeTypeSelect.value;

    if (!name || name.length < 3) {
        dom.safeNameInput.closest(".form-group").classList.add("has-error");
        return;
    }

    fetch('api/safes.php?action=save_safe', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id, name, type })
    })
        .then(response => response.json())
        .then(res => {
            if (res.status === 'success') {
                showToast(res.message);
                closeSafeModal();

                fetch('api/safes.php?action=list')
                    .then(r => r.json())
                    .then(rList => {
                        if (rList.status === 'success') {
                            state.safes = rList.safes;
                            state.transactions = rList.transactions;
                            applyFilters();

                            if (id) {
                                selectSafe(id);
                            } else {
                                const newestSafe = state.safes.reduce((max, s) => parseInt(s.id) > parseInt(max.id) ? s : max, state.safes[0]);
                                if (newestSafe) selectSafe(newestSafe.id);
                            }
                        }
                    });
            } else {
                showToast(res.message, "danger");
            }
        })
        .catch(err => {
            console.error(err);
            showToast("فشل الاتصال بالخادم لحفظ الصندوق", "danger");
        });
}

// Transaction Form Submit
function handleTxSubmit(e) {
    e.preventDefault();

    const type = dom.txTypeSelect.value;
    const description = dom.txDescriptionInput.value.trim();
    const date = dom.txDateInput.value;
    const amount = parseFloat(dom.txAmountInput.value.replace(/,/g, ''));
    const isRepayment = dom.txIsDebtRepaymentCheckbox.checked;
    const debtorId = dom.txDebtorIdSelect.value;
    const isFormPayment = dom.txIsFormPaymentCheckbox.checked;
    const formId = dom.txFormIdSelect.value;

    let isValid = true;
    clearTxValidationErrors();

    if (!description || description.length < 3) {
        dom.txDescriptionInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }
    if (!date) {
        dom.txDateInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }
    if (isNaN(amount) || amount <= 0) {
        dom.txAmountInput.closest(".form-group").classList.add("has-error");
        isValid = false;
    }
    if (isRepayment && !debtorId) {
        dom.txDebtorIdSelect.closest(".form-group").classList.add("has-error");
        isValid = false;
    }
    if (isFormPayment && !formId) {
        dom.txFormIdSelect.closest(".form-group").classList.add("has-error");
        isValid = false;
    }

    if (!isValid) return;

    fetch('api/safes.php?action=save_tx', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            safeId: state.activeSafeId,
            description,
            type: (isRepayment || isFormPayment) ? 'deposit' : type,
            date,
            amount,
            debtorId: isRepayment ? debtorId : null,
            formId: isFormPayment ? formId : null
        })
    })
        .then(response => response.json())
        .then(res => {
            if (res.status === 'success') {
                // If it is a debt repayment, also update localStorage
                if (isRepayment) {
                    const localEntries = localStorage.getItem("dashboard_debt_entries");
                    let entries = [];
                    if (localEntries) {
                        try {
                            entries = JSON.parse(localEntries);
                        } catch (e) { }
                    }
                }
                showToast(res.message);
                closeTxModal();
                loadData();
            } else {
                showToast(res.message, "danger");
            }
        })
        .catch(err => {
            console.error(err);
            showToast("فشل الاتصال بالخادم لتسجيل الحركة المالية", "danger");
        });
}

// Helper: parse a formula like "عدد * 1000" or "الوزن * 30"
function calcFormula(formula, qty, weight, price, accountingType = '') {
    if (!formula || formula.trim() === '' || formula.trim() === '---') return 0;

    if (formula.includes('+')) {
        return formula.split('+').reduce((sum, part) => sum + calcFormula(part, qty, weight, price, accountingType), 0);
    }

    const f = formula.trim();

    // Pattern: "اضافة X%" or "X%"
    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;
    }

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

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

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

    return 0; // unknown formula — return 0
}

function calculateCommissionParts(formula, qty, weight, price, accountingType = '') {
    if (!formula || formula.trim() === '' || formula.trim() === '---') {
        return { commission: 0, commission_10: 0 };
    }

    let parts = formula.split('+');
    let commission = 0;
    let commission_10 = 0;

    parts.forEach(part => {
        const trimmed = part.trim();
        const pctMatch = trimmed.match(/(\d+(?:\.\d+)?)\s*%/);
        if (pctMatch) {
            commission_10 += calcFormula(trimmed, qty, weight, price, accountingType);
        } else {
            commission += calcFormula(trimmed, qty, weight, price, accountingType);
        }
    });

    return { commission, commission_10 };
}

// Helper to calculate total value of a form from its items
function calculateFormTotal(form) {
    if (!form) return 0;
    // If items are populated, calculate dynamically to ensure it's up to date
    if (form.items && form.items.length > 0) {
        const FORM_FEE = 1000;
        const subtotal = form.items.reduce((total, item) => {
            const weight = parseFloat(item.weight) || 0;
            const qty = parseInt(item.quantity) || 0;
            const price = parseFloat(item.price) || 0;

            const itemSub = 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;

            return total + itemSub + commission + commission_10;
        }, 0);
        return subtotal + FORM_FEE;
    }
    // Otherwise fallback to grandTotal
    if (form.grandTotal !== undefined && form.grandTotal !== null) {
        return parseFloat(form.grandTotal);
    }
    return 1000; // default/fee minimum
}

// Debt repayment view details modal popup logic
window.viewDebtDetails = function (tx) {
    const debtorId = tx.debtorId;
    const debtor = (state.debtors || []).find(d =>
        String(d.id) === String(debtorId) ||
        (d.realIds && d.realIds.includes(String(debtorId)))
    );
    if (!debtor) {
        showToast("لم يتم العثور على بيانات هذا المدين", "warning");
        return;
    }

    // Fetch transactions for this debtor using unified name-based ID
    fetch(`api/debts.php?action=get_transactions&debtor_id=${debtor.id}`)
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') {
                showToast("فشل تحميل حركات المدين", "danger");
                return;
            }
            const entries = res.transactions;
            const totalDebts = entries.filter(x => x.type === "debt").reduce((sum, item) => sum + parseFloat(item.amount), 0);
            const totalRepayments = entries.filter(x => x.type === "repayment").reduce((sum, item) => sum + parseFloat(item.amount), 0);
            const remainingBalance = totalDebts - totalRepayments;

            // Fill the modal
            const words = debtor.name ? debtor.name.trim().split(/\s+/) : ['م'];
            const initials = words.slice(0, 2).map(w => w[0]).join('');

            document.getElementById("modal-debtor-avatar").textContent = initials;
            document.getElementById("modal-debtor-name").textContent = debtor.name;
            document.getElementById("modal-debtor-phone").innerHTML = `<i class="fa-solid fa-phone"></i> ${debtor.phone}`;

            document.getElementById("modal-debtor-total-debt").textContent = `${formatCurrency(totalDebts)} ${getCurrency()}`;
            document.getElementById("modal-debtor-total-repayments").textContent = `${formatCurrency(totalRepayments)} ${getCurrency()}`;
            document.getElementById("modal-debtor-remaining-balance").textContent = `${formatCurrency(remainingBalance)} ${getCurrency()}`;

            document.getElementById("modal-tx-amount").textContent = `${formatCurrency(tx.amount)} ${getCurrency()}`;
            document.getElementById("modal-tx-date").textContent = tx.date;
            document.getElementById("modal-tx-desc").textContent = tx.description;

            dom.debtDetailsModal.classList.add("open");
        })
        .catch(() => showToast("فشل الاتصال بالخادم لجلب تفاصيل الديون", "danger"));
};

function closeDebtDetailsModal() {
    dom.debtDetailsModal.classList.remove("open");
}

// Form invoice payment view details modal logic
window.viewFormPaymentDetails = function (tx) {
    const formId = tx.formId;
    const forms = state.forms || [];
    const form = forms.find(f => String(f.id) === String(formId));
    if (!form) {
        showToast("لم يتم العثور على تفاصيل هذه الاستمارة", "warning");
        return;
    }

    // Calculate form serial index
    const formIndex = forms.findIndex(f => f.id === formId);
    const formNumber = forms.length - formIndex;

    const tbody = document.getElementById("modal-form-items-tbody");
    if (tbody) {
        tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; padding: 15px; color: var(--text-secondary);"><i class="fa-solid fa-spinner fa-spin"></i> جاري تحميل المواد...</td></tr>`;
    }

    // Fetch the form items dynamically
    fetch(`api/forms.php?action=get_items&form_id=${formId}`)
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') {
                showToast("فشل تحميل مواد الاستمارة", "danger");
                if (tbody) tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; padding: 15px; color: var(--danger);">فشل تحميل المواد</td></tr>`;
                return;
            }

            form.items = res.data;
            const totalVal = calculateFormTotal(form);

            // Calculate total paid for this form
            const formTxList = state.transactions.filter(t => String(t.formId) === String(formId));
            const totalPaid = formTxList.reduce((sum, t) => sum + parseFloat(t.amount), 0);
            const remaining = totalVal - totalPaid;
            const remainingAfter = remaining; // current balance remaining after all tx applied

            document.getElementById("modal-form-customer-name").textContent = form.customerName;
            document.getElementById("modal-form-serial").textContent = `#${formNumber}`;
            document.getElementById("modal-form-total-value").textContent = `${formatCurrency(totalVal)} ${getCurrency()}`;
            document.getElementById("modal-form-total-paid").textContent = `${formatCurrency(totalPaid)} ${getCurrency()}`;
            document.getElementById("modal-form-total-remaining").textContent = `${formatCurrency(remaining)} ${getCurrency()}`;

            document.getElementById("modal-form-tx-amount").textContent = `${formatCurrency(tx.amount)} ${getCurrency()}`;
            document.getElementById("modal-form-remaining-after").textContent = `${formatCurrency(remainingAfter)} ${getCurrency()}`;

            // Render items table
            tbody.innerHTML = "";
            const cur = getCurrency();

            if (form.items && form.items.length > 0) {
                let totQty = 0, totWeight = 0, totWorker = 0, totCommission = 0, totCommission10 = 0, totSubtotal = 0;

                form.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 workerShare = calcFormula(item.workerShareType, qty, weight, price, item.accountingType);

                    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 = subtotal + commission + commission_10;

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

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

                    const tr = document.createElement("tr");
                    tr.style.borderBottom = "1px solid var(--border-color)";
                    tr.innerHTML = `
                        <td style="padding: 10px 8px; font-weight: bold; color: var(--text-primary); text-align: right;">${escapeHTML(item.name)}</td>
                        <td style="padding: 10px 8px; text-align: center;">${qty}</td>
                        <td style="padding: 10px 8px; text-align: center;">${weightStr}</td>
                        <td style="padding: 10px 8px; text-align: center;">${formatCurrency(price)}</td>
                        <td style="padding: 10px 8px; text-align: center; color: #10b981; font-weight: 600;">
                            ${workerShare > 0 ? formatCurrency(workerShare) : '<span style="color:var(--text-muted)">---</span>'}
                        </td>
                        <td style="padding: 10px 8px; text-align: center; color: #f59e0b; font-weight: 600;">
                            ${commission > 0 ? formatCurrency(commission) : '<span style="color:var(--text-muted)">---</span>'}
                        </td>
                        <td style="padding: 10px 8px; text-align: center; color: #f59e0b; font-weight: 600;">
                            ${commission_10 > 0 ? formatCurrency(commission_10) : '<span style="color:var(--text-muted)">---</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="padding: 10px 8px; text-align: center; font-weight: bold; color: var(--primary);">${formatCurrency(itemTotal)}</td>
                    `;
                    tbody.appendChild(tr);
                });

                // Add Totals row
                const totalsRow = document.createElement("tr");
                totalsRow.style.cssText = "background: rgba(59,130,246,0.05); border-top: 2px solid rgba(59,130,246,0.15); font-weight: 800; border-bottom: 1px solid var(--border-color);";
                totalsRow.innerHTML = `
                    <td style="padding: 10px 8px; color: var(--text-secondary); text-align: right;">المجاميع</td>
                    <td style="padding: 10px 8px; text-align: center; color: var(--primary);">${totQty}</td>
                    <td style="padding: 10px 8px; text-align: center; color: var(--text-secondary);">${totWeight > 0 ? Number(totWeight.toFixed(2)) : "---"}</td>
                    <td style="padding: 10px 8px;"></td>
                    <td style="padding: 10px 8px; text-align: center; color: #10b981;">${formatCurrency(totWorker)}</td>
                    <td style="padding: 10px 8px; text-align: center; color: #f59e0b;">${formatCurrency(totCommission)}</td>
                    <td style="padding: 10px 8px; text-align: center; color: #f59e0b;">${formatCurrency(totCommission10)}</td>
                    <td style="padding: 10px 8px; text-align: center; color: var(--primary);">${formatCurrency(totSubtotal + totCommission + totCommission10)}</td>
                `;
                tbody.appendChild(totalsRow);

                // Add Form Fee row
                const FORM_FEE = 1000;
                const feeRow = document.createElement("tr");
                feeRow.style.cssText = "background: rgba(245,158,11,0.05); border-top: 2px dashed rgba(245,158,11,0.2);";
                feeRow.innerHTML = `
                    <td style="padding: 10px 8px; font-weight: 700; color: #d97706; text-align: right;"><i class="fa-solid fa-receipt"></i> رسوم الاستمارة</td>
                    <td colspan="6" style="padding: 10px 8px;"></td>
                    <td style="padding: 10px 8px; text-align: center; font-weight: 800; color: #d97706;">${formatCurrency(FORM_FEE)}</td>
                `;
                tbody.appendChild(feeRow);
            } else {
                tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; padding: 15px; color: var(--text-secondary);">لا توجد مواد مدرجة في هذه الاستمارة</td></tr>`;
            }
        })
        .catch((e) => {
            console.error(e);
            showToast("فشل الاتصال بالخادم لجلب تفاصيل الاستمارة", "danger");
            if (tbody) tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; padding: 15px; color: var(--danger);">فشل الاتصال بالخادم</td></tr>`;
        });

    const goToInvoiceBtn = document.getElementById("modal-form-go-to-invoice-btn");
    if (goToInvoiceBtn) {
        goToInvoiceBtn.href = `forms.php?formId=${formId}`;
    }

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

function closeFormPaymentDetailsModal() {
    dom.formPaymentDetailsModal.classList.remove("open");
}

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

    const id = state.deleteTargetId;

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

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

function getOrgName() {
    let settings = {};
    const localSettings = localStorage.getItem("dashboard_settings") || localStorage.getItem("system_settings");
    if (localSettings) {
        try { settings = JSON.parse(localSettings); } catch (e) { }
    }
    return settings.orgName || settings.org_name || settings.companyName || "مكتب الحاج أمجد سهل عبدالامير";
}

function getCurrency() {
    return "د.ع";
}

function formatNum(n) {
    if (n === null || n === undefined || isNaN(n)) return "0";
    return Number(n).toLocaleString('ar-IQ');
}

// -------------------------------------------------------------
// 14. Event Listeners Setup
// -------------------------------------------------------------
function setupEventListeners() {
    // Open Safe Modals
    dom.openAddSafeBtn.addEventListener("click", openAddSafeModal);
    dom.emptyStateAddSafeBtn.addEventListener("click", openAddSafeModal);

    // Open Transaction Modal
    dom.openAddTxBtn.addEventListener("click", openAddTxModal);

    // Close Modals
    dom.closeSafeModalBtn.addEventListener("click", closeSafeModal);
    dom.cancelSafeModalBtn.addEventListener("click", closeSafeModal);
    dom.closeTxModalBtn.addEventListener("click", closeTxModal);
    dom.cancelTxModalBtn.addEventListener("click", closeTxModal);
    dom.cancelDeleteBtn.addEventListener("click", closeDeleteModal);
    dom.closeDebtDetailsModalBtn.addEventListener("click", closeDebtDetailsModal);
    dom.closeDebtDetailsBtn.addEventListener("click", closeDebtDetailsModal);
    dom.closeFormPaymentDetailsModalBtn.addEventListener("click", closeFormPaymentDetailsModal);
    dom.closeFormPaymentDetailsBtn.addEventListener("click", closeFormPaymentDetailsModal);

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

    // Forms Submission
    dom.safeForm.addEventListener("submit", handleSafeSubmit);
    dom.transactionForm.addEventListener("submit", handleTxSubmit);

    // Checkbox and dropdown visibility logic
    dom.txIsDebtRepaymentCheckbox.addEventListener("change", () => {
        if (dom.txIsDebtRepaymentCheckbox.checked) {
            dom.txDebtorGroup.style.display = "block";
            dom.txFormSelectGroup.style.display = "none";
            dom.txIsFormPaymentCheckbox.checked = false;
            dom.txTypeSelect.value = "deposit";
            dom.txTypeSelect.disabled = true;
        } else {
            dom.txDebtorGroup.style.display = "none";
            if (!dom.txIsFormPaymentCheckbox.checked) {
                dom.txTypeSelect.disabled = false;
            }
        }
    });

    dom.txIsFormPaymentCheckbox.addEventListener("change", () => {
        if (dom.txIsFormPaymentCheckbox.checked) {
            dom.txFormSelectGroup.style.display = "block";
            dom.txDebtorGroup.style.display = "none";
            dom.txIsDebtRepaymentCheckbox.checked = false;
            dom.txTypeSelect.value = "deposit";
            dom.txTypeSelect.disabled = true;
        } else {
            dom.txFormSelectGroup.style.display = "none";
            if (!dom.txIsDebtRepaymentCheckbox.checked) {
                dom.txTypeSelect.disabled = false;
            }
        }
    });

    dom.txFormIdSelect.addEventListener("change", () => {
        const formId = dom.txFormIdSelect.value;
        if (formId) {
            const forms = state.forms || [];
            const form = forms.find(f => String(f.id) === String(formId));
            if (form) {
                const formIndex = forms.findIndex(f => String(f.id) === String(formId));
                const formNumber = forms.length - formIndex;
                const formDate = form.createdAt ? form.createdAt.substring(0, 10) : '';
                dom.txDescriptionInput.value = `تحصيل دفعة من استمارة الزبون: ${form.customerName} رقم: #${formNumber} بتاريخ: ${formDate}`;
            }
        }
    });

    // Reset Safe Modal Listeners
    if (dom.resetSafeBtn) {
        dom.resetSafeBtn.addEventListener("click", () => {
            if (!state.activeSafeId) return;
            const balance = calculateSafeBalance(state.activeSafeId);
            if (balance <= 0.01) {
                showToast("رصيد القاصة مساوٍ للصفر بالفعل أو سالب، لا يمكن تصفيره", "error");
                return;
            }
            dom.resetReceiverNameInput.value = "";
            dom.resetSafeModal.classList.add("open");
        });
    }

    if (dom.closeResetModalBtn) dom.closeResetModalBtn.addEventListener("click", () => dom.resetSafeModal.classList.remove("open"));
    if (dom.cancelResetModalBtn) dom.cancelResetModalBtn.addEventListener("click", () => dom.resetSafeModal.classList.remove("open"));

    if (dom.resetSafeForm) {
        dom.resetSafeForm.addEventListener("submit", (e) => {
            e.preventDefault();
            const receiverName = dom.resetReceiverNameInput.value.trim();
            if (!receiverName) return;

            fetch('api/safes.php?action=reset_safe', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    safeId: state.activeSafeId,
                    receiverName: receiverName
                })
            })
                .then(r => r.json())
                .then(res => {
                    if (res.status === 'success') {
                        showToast(res.message, "success");
                        dom.resetSafeModal.classList.remove("open");

                        // Active safe name
                        const safeObj = state.safes.find(s => String(s.id) === String(state.activeSafeId));
                        const safeName = safeObj ? safeObj.name : 'الصندوق الرئيسي';
                        const paidAmount = res.amount !== undefined ? res.amount : 0;

                        // Trigger payout receipt print automatically
                        printResetReceipt({
                            txId: res.tx_id || Date.now(),
                            date: new Date().toISOString().split('T')[0],
                            safeName: safeName,
                            receiverName: receiverName,
                            amount: paidAmount,
                            description: `تصفير القاصة وتسليم النقدية إلى: ${receiverName}`
                        });

                        loadData(); // Refresh safes and transactions
                    } else {
                        showToast(res.message, "danger");
                    }
                })
                .catch(err => {
                    console.error(err);
                    showToast("فشلت عملية تصفير القاصة", "error");
                });
        });
    }

    // Format input amount with commas dynamically
    if (dom.txAmountInput) {
        dom.txAmountInput.addEventListener("input", function (e) {
            let cursorPosition = this.selectionStart;
            let originalLength = this.value.length;

            // Remove any commas and non-digits first
            let value = this.value.replace(/,/g, '');

            // Split decimal part if any
            let parts = value.split('.');

            // Remove non-digit characters from the integer part
            parts[0] = parts[0].replace(/\D/g, '');

            // Add commas to the integer part
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');

            // Reassemble value
            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];
            }

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

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

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

    // Close on overlay click
    window.addEventListener("click", (e) => {
        if (e.target === dom.safeModal) closeSafeModal();
        if (e.target === dom.transactionModal) closeTxModal();
        if (e.target === dom.deleteConfirmModal) closeDeleteModal();
        if (e.target === dom.debtDetailsModal) closeDebtDetailsModal();
        if (e.target === dom.formPaymentDetailsModal) closeFormPaymentDetailsModal();
        if (e.target === dom.resetSafeModal) dom.resetSafeModal.classList.remove("open");
    });

    // Close on Escape
    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeSafeModal();
            closeTxModal();
            closeDeleteModal();
            closeDebtDetailsModal();
            closeFormPaymentDetailsModal();
            if (dom.resetSafeModal) dom.resetSafeModal.classList.remove("open");
        }
    });
}

// -------------------------------------------------------------
// 15. Print Payout Receipt Function (وصل دفع وتصفير نقدية)
// -------------------------------------------------------------
window.printResetReceipt = function (data) {
    const cur = getCurrency();
    const orgName = getOrgName();
    const txId = data.txId || Date.now();
    const dateStr = data.date || new Date().toISOString().split('T')[0];
    const safeName = data.safeName || 'الصندوق الرئيسي';
    const receiverName = data.receiverName || 'مستلم الأموال';
    const amount = parseFloat(data.amount || 0);
    const description = data.description || (`تصفير القاصة وتسليم النقدية إلى: ${receiverName}`);

    const html = `<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>وصل دفع وتسليم نقدية - ${escapeHTML(receiverName)}</title>
<style>
    @page { size: A5 landscape; margin: 8mm; }
    @media print {
        body { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
        .no-print { display: none !important; }
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 12px;
        color: #0f172a;
        background: #ffffff;
        direction: rtl;
        padding: 12px;
    }
    .receipt-card {
        background: #ffffff;
        border: 2px solid #dc2626;
        border-radius: 12px;
        padding: 20px 24px;
        max-width: 720px;
        margin: 0 auto;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        position: relative;
    }
    .receipt-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #ef4444;
        padding-bottom: 12px;
        margin-bottom: 16px;
    }
    .brand-info {
        display: flex;
        align-items: center;
        gap: 12px;
    }
    .brand-icon {
        width: 44px; height: 44px;
        border-radius: 10px;
        background: linear-gradient(135deg, #b91c1c, #dc2626);
        color: #ffffff;
        font-size: 22px;
        display: flex; align-items: center; justify-content: center;
    }
    .brand-title {
        font-size: 17px;
        font-weight: 800;
        color: #0f172a;
        margin: 0;
    }
    .brand-subtitle {
        font-size: 11px;
        color: #64748b;
        margin-top: 2px;
    }
    .receipt-title-box {
        text-align: center;
    }
    .receipt-title-main {
        font-size: 20px;
        font-weight: 900;
        color: #dc2626;
        letter-spacing: 0.5px;
    }
    .receipt-type-tag {
        display: inline-block;
        font-size: 10.5px;
        font-weight: 800;
        padding: 2px 10px;
        border-radius: 12px;
        background: #fef2f2;
        color: #dc2626;
        border: 1px solid #fca5a5;
        margin-top: 3px;
    }
    .meta-details {
        text-align: right;
        font-size: 11.5px;
        color: #475569;
        line-height: 1.6;
    }
    .meta-details strong { color: #0f172a; font-weight: 800; }

    .receipt-body {
        margin-bottom: 16px;
    }
    .info-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0 8px;
        margin-bottom: 14px;
    }
    .info-table td {
        padding: 10px 14px;
        background: #f8fafc;
        border-top: 1px solid #e2e8f0;
        border-bottom: 1px solid #e2e8f0;
    }
    .info-table td:first-child {
        border-right: 1px solid #e2e8f0;
        border-top-right-radius: 8px;
        border-bottom-right-radius: 8px;
        font-weight: 800;
        color: #475569;
        width: 160px;
        font-size: 12.5px;
    }
    .info-table td:last-child {
        border-left: 1px solid #e2e8f0;
        border-top-left-radius: 8px;
        border-bottom-left-radius: 8px;
        font-weight: 700;
        color: #0f172a;
        font-size: 13px;
    }

    .amount-card {
        background: linear-gradient(135deg, #b91c1c 0%, #dc2626 100%);
        color: #ffffff;
        border-radius: 10px;
        padding: 14px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 14px;
    }
    .amount-label {
        font-size: 13.5px;
        font-weight: 700;
        opacity: 0.95;
    }
    .amount-val {
        font-size: 22px;
        font-weight: 900;
        direction: ltr;
    }

    .receipt-footer {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        border-top: 2px dashed #cbd5e1;
        padding-top: 16px;
        margin-top: 16px;
    }
    .sig-box {
        text-align: center;
        width: 180px;
    }
    .sig-title {
        font-size: 11px;
        font-weight: 700;
        color: #64748b;
        margin-bottom: 35px;
    }
    .sig-line {
        border-bottom: 1.5px solid #64748b;
    }
    .system-stamp {
        text-align: center;
        font-size: 10px;
        color: #94a3b8;
    }
</style>
</head>
<body>
<div class="receipt-card">
    <div class="receipt-header">
        <div class="brand-info">
            <div class="brand-icon">💸</div>
            <div>
                <h3 class="brand-title">${escapeHTML(orgName)}</h3>
                <div class="brand-subtitle">سند وصل دفع وتصفير نقدية القاصة</div>
            </div>
        </div>
        <div class="receipt-title-box">
            <div class="receipt-title-main">وصل دفع </div>
            <div class="receipt-type-tag">تصفير القاصة بالكامل</div>
        </div>
        <div class="meta-details">
            <div>رقم السند: <strong>#${escapeHTML(String(txId))}</strong></div>
            <div>التاريخ: <strong>${escapeHTML(dateStr)}</strong></div>
            <div>الصندوق: <strong>${escapeHTML(safeName)}</strong></div>
        </div>
    </div>

    <div class="receipt-body">
        <table class="info-table">
            <tr>
                <td>تم التسليم للسيد:</td>
                <td><strong>${escapeHTML(receiverName)}</strong></td>
            </tr>
            <tr>
                <td>البيان:</td>
                <td>${escapeHTML(description)}</td>
            </tr>
            <tr>
                <td>الصندوق:</td>
                <td>${escapeHTML(safeName)}</td>
            </tr>
        </table>

        <div class="amount-card">
            <span class="amount-label">المبلغ المسلّم:</span>
            <span class="amount-val">${formatNum(amount)} ${cur}</span>
        </div>
    </div>

    <div class="receipt-footer">
        <div class="sig-box">
            <div class="sig-title">توقيع المستلم (${escapeHTML(receiverName)})</div>
            <div class="sig-line"></div>
        </div>
        <div class="system-stamp">
            تمت عملية التصفير والتسليم إلكترونياً عبر نظام ${escapeHTML(orgName)}
        </div>
        <div class="sig-box">
            <div class="sig-title">توقيع أمين الصندوق / المسلّم</div>
            <div class="sig-line"></div>
        </div>
    </div>
</div>
<script>
    window.onload = function() {
        setTimeout(function() {
            window.print();
        }, 400);
    };
<\/script>
</body>
</html>`;

    const printWin = window.open('', '_blank', 'width=800,height=600');
    if (printWin) {
        printWin.document.write(html);
        printWin.document.close();
    } else {
        showToast('يرجى السماح بالنوافذ المنبثقة لطباعة وصل الدفع', 'warning');
    }
};

window.printTxResetReceipt = function (txId) {
    const tx = state.transactions.find(t => String(t.id) === String(txId));
    if (!tx) {
        showToast("تعذر العثور على بيانات الحركة للطباعة", "warning");
        return;
    }

    const safeObj = state.safes.find(s => String(s.id) === String(tx.safeId));
    const safeName = safeObj ? safeObj.name : 'الصندوق الرئيسي';
    let receiverName = 'مستلم الأموال';
    if (tx.description && tx.description.includes(':')) {
        receiverName = tx.description.split(':')[1].trim();
    }

    printResetReceipt({
        txId: tx.id,
        date: tx.date || (tx.createdAt ? tx.createdAt.substring(0, 10) : ''),
        safeName: safeName,
        receiverName: receiverName,
        amount: parseFloat(tx.amount || 0),
        description: tx.description
    });
};
