// Business Logic and Operations for Activity Logs Page

// -------------------------------------------------------------
// 1. App State
// -------------------------------------------------------------
let state = {
    logs: [],
    currentPage: 1,
    pageSize: 10,
    totalLogs: 0,
    searchQuery: "",
    filterAction: "",
    filterTable: "",
    fromDate: "",
    toDate: ""
};

// Translations
const TABLE_TRANSLATIONS = {
    forms: "الاستمارات (forms)",
    form_items: "المواد بالاستمارة (form_items)",
    safe_transactions: "الحركات المالية (safe_transactions)",
    debtors: "الديون والعملاء (debtors)",
    materials: "قائمة المواد (materials)",
    safes: "الصناديق (safes)",
    users: "المستخدمين (users)",
    system_settings: "الإعدادات العامة (settings)"
};

const ACTION_TRANSLATIONS = {
    insert: "إضافة جديدة",
    update: "تعديل بيانات",
    delete: "حذف سجل",
    payment: "تسديد فاتورة"
};

const KEY_TRANSLATIONS = {
    customer_name: "اسم الزبون",
    customerName: "اسم الزبون",
    grand_total: "المجموع الكلي",
    grandTotal: "المجموع الكلي",
    status: "حالة الدفع",
    materials_count: "عدد المواد",
    name: "الاسم",
    phone: "رقم الهاتف",
    notes: "ملاحظات",
    quantity: "الكمية / العدد",
    weight: "الوزن",
    price: "السعر الفردي",
    total: "المجموع الكلي للمادة",
    worker_share: "حق العامل",
    commission: "العمولة العامة",
    commission_10: "عمولة النسبة %",
    description: "البيان / الوصف",
    amount: "المبلغ",
    date: "التاريخ",
    type: "نوع الحركة",
    safe_id: "رقم الصندوق",
    safeId: "رقم الصندوق",
    accounting_type: "طريقة الاحتساب",
    accountingType: "طريقة الاحتساب",
    commission_type: "طريقة العمولة",
    commissionType: "طريقة العمولة",
    worker_share_type: "معادلة حق العامل",
    workerShareType: "معادلة حق العامل",
    jallab_id: "معرف الجلاب",
    jallabId: "معرف الجلاب",
    user_id: "معرف المستخدم",
    org_name: "اسم المنشأة",
    org_email: "البريد الإلكتروني",
    max_daily_expense: "الحد الأقصى للمصروف",
    low_balance_threshold: "حد تحذير الصندوق",
    workday_start_hour: "ساعة بدء الوردية",
    workday_end_hour: "ساعة انتهاء الوردية",
    username: "اسم المستخدم",
    debtor_id: "معرف المدين",
    form_id: "رقم الاستمارة",
    formId: "رقم الاستمارة",
    option_value: "خيار العمولة/حق العامل",
    paid_amount: "المبلغ المدفوع",
    pay_amount: "مبلغ التحصيل"
};

// -------------------------------------------------------------
// 2. DOM Elements
// -------------------------------------------------------------
const dom = {
    logsTbody: document.getElementById("logs-tbody"),
    emptyStateView: document.getElementById("empty-state-view"),
    paginationInfoText: document.getElementById("pagination-info-text"),
    paginationControls: document.getElementById("pagination-controls"),
    entriesCount: document.getElementById("entries-count"),
    searchInput: document.getElementById("search-input"),
    filterAction: document.getElementById("filter-action"),
    filterTable: document.getElementById("filter-table"),
    filterFromDate: document.getElementById("filter-from-date"),
    filterToDate: document.getElementById("filter-to-date"),
    searchResultsBadge: document.getElementById("search-results-badge"),

    // Stats elements
    statTotalLogs: document.getElementById("stat-total-logs"),
    statInsertLogs: document.getElementById("stat-insert-logs"),
    statUpdateLogs: document.getElementById("stat-update-logs"),
    statDeleteLogs: document.getElementById("stat-delete-logs"),

    // Detail Modal elements
    detailModal: document.getElementById("detail-modal"),
    closeModalBtn: document.getElementById("close-modal-btn"),
    closeModalFooterBtn: document.getElementById("close-modal-footer-btn"),
    detailUser: document.getElementById("detail-user"),
    detailAction: document.getElementById("detail-action"),
    detailTable: document.getElementById("detail-table"),
    detailDate: document.getElementById("detail-date"),
    comparisonSection: document.getElementById("comparison-section"),
    comparisonTbody: document.getElementById("comparison-tbody"),
    rawJsonSection: document.getElementById("raw-json-section"),
    rawJsonView: document.getElementById("raw-json-view")
};

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

function setupEventListeners() {
    // Search input typing handler
    let searchTimeout = null;
    if (dom.searchInput) {
        dom.searchInput.addEventListener("input", () => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                state.searchQuery = dom.searchInput.value.trim();
                state.currentPage = 1;
                loadData(false);
            }, 400);
        });
    }

    // Filters selection
    if (dom.filterAction) {
        dom.filterAction.addEventListener("change", () => {
            state.filterAction = dom.filterAction.value;
            state.currentPage = 1;
            loadData(false);
        });
    }

    if (dom.filterTable) {
        dom.filterTable.addEventListener("change", () => {
            state.filterTable = dom.filterTable.value;
            state.currentPage = 1;
            loadData(false);
        });
    }

    if (dom.filterFromDate) {
        dom.filterFromDate.addEventListener("change", () => {
            state.fromDate = dom.filterFromDate.value;
            state.currentPage = 1;
            loadData(false);
        });
    }

    if (dom.filterToDate) {
        dom.filterToDate.addEventListener("change", () => {
            state.toDate = dom.filterToDate.value;
            state.currentPage = 1;
            loadData(false);
        });
    }

    // Page size dropdown
    if (dom.entriesCount) {
        dom.entriesCount.addEventListener("change", () => {
            state.pageSize = parseInt(dom.entriesCount.value);
            state.currentPage = 1;
            loadData(false);
        });
    }

    // Close Modal
    if (dom.closeModalBtn) dom.closeModalBtn.addEventListener("click", closeModal);
    if (dom.closeModalFooterBtn) dom.closeModalFooterBtn.addEventListener("click", closeModal);

    // Close modal on click outside card
    if (dom.detailModal) {
        dom.detailModal.addEventListener("click", (e) => {
            if (e.target === dom.detailModal) closeModal();
        });
    }
}

// -------------------------------------------------------------
// 4. Data Loading and Binding
// -------------------------------------------------------------
function loadData(updateStats = false) {
    const url = `api/activity_logs.php?action=list&search=${encodeURIComponent(state.searchQuery)}&filter_action=${state.filterAction}&filter_table=${state.filterTable}&from_date=${state.fromDate}&to_date=${state.toDate}&page=${state.currentPage}&limit=${state.pageSize}`;

    fetch(url)
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                state.logs = res.data;
                state.totalLogs = res.total;
                renderTable();
                renderPagination();

                if (res.stats) {
                    updateStatsUI(res.stats);
                }
            } else {
                showToast(res.message || "حدث خطأ أثناء جلب سجل العمليات", "danger");
            }
        })
        .catch(err => {
            console.error(err);
            showToast("فشل الاتصال بالخادم لجلب البيانات", "danger");
        });
}

function updateStatsUI(stats) {
    if (dom.statTotalLogs) dom.statTotalLogs.textContent = (stats.total || 0).toLocaleString('ar-EG');
    if (dom.statInsertLogs) dom.statInsertLogs.textContent = (stats.insert || 0).toLocaleString('ar-EG');
    if (dom.statUpdateLogs) dom.statUpdateLogs.textContent = (stats.update || 0).toLocaleString('ar-EG');
    if (dom.statDeleteLogs) dom.statDeleteLogs.textContent = (stats.delete || 0).toLocaleString('ar-EG');
}

function generateDetailedDescription(log) {
    const user = `<strong>${log.userFullname}</strong>`;
    const actionWord = log.action === 'insert' ? 'إضافة جديدة' :
        log.action === 'update' ? 'تعديل بيانات' :
            log.action === 'delete' ? 'حذف سجل' :
                log.action === 'payment' ? 'تسديد مالي' : log.action;

    const recordId = `#${log.recordId}`;
    const dateFormatted = formatDateTime(log.createdAt);

    let detailsSummary = "";
    const oldData = log.details.old || {};
    const newData = log.details.new || {};

    if (log.tableName === 'materials') {
        const matName = newData.name || oldData.name || "";
        if (log.action === 'insert') {
            detailsSummary = `إضافة مادة جديدة باسم <strong>"${matName}"</strong>`;
        } else if (log.action === 'update') {
            const keys = Object.keys(newData).map(k => KEY_TRANSLATIONS[k] || k);
            detailsSummary = `تعديل المادة <strong>"${matName}"</strong> في الحقول (${keys.join(', ')})`;
        } else if (log.action === 'delete') {
            detailsSummary = `حذف المادة <strong>"${matName}"</strong> نهائياً من النظام`;
        }
    } else if (log.tableName === 'forms') {
        const custName = newData.customer_name || oldData.customer_name || newData.customerName || oldData.customerName || "";
        const grandTotal = newData.grand_total || oldData.grand_total || newData.grandTotal || oldData.grandTotal || 0;
        const formattedTotal = parseFloat(grandTotal).toLocaleString('ar-EG') + " د.ع";

        if (log.action === 'insert') {
            detailsSummary = `إنشاء فاتورة استمارة للزبون <strong>"${custName}"</strong> بقيمة <strong>${formattedTotal}</strong>`;
        } else if (log.action === 'update') {
            const keys = Object.keys(newData).map(k => KEY_TRANSLATIONS[k] || k);
            detailsSummary = `تعديل فاتورة الزبون <strong>"${custName}"</strong> في الحقول (${keys.join(', ')})`;
        } else if (log.action === 'delete') {
            detailsSummary = `حذف الفاتورة رقم <strong>${recordId}</strong> التابعة للزبون <strong>"${custName}"</strong>`;
        } else if (log.action === 'payment') {
            const paid = log.details.amount || newData.amount || oldData.amount || 0;
            detailsSummary = `تسديد مبلغ <strong>${parseFloat(paid).toLocaleString('ar-EG')} د.ع</strong> للفاتورة رقم <strong>${recordId}</strong> للزبون <strong>"${custName}"</strong>`;
        }
    } else if (log.tableName === 'safe_transactions') {
        const desc = newData.description || oldData.description || "";
        const amount = newData.amount || oldData.amount || 0;
        const formattedAmount = parseFloat(amount).toLocaleString('ar-EG') + " د.ع";
        const typeStr = (newData.type || oldData.type) === 'deposit' ? 'إيداع' : 'سحب';

        if (log.action === 'insert') {
            detailsSummary = `تسجيل حركة مالية <strong>(${typeStr})</strong> بمبلغ <strong>${formattedAmount}</strong> ببيان: <strong>"${desc}"</strong>`;
        } else if (log.action === 'update') {
            const keys = Object.keys(newData).map(k => KEY_TRANSLATIONS[k] || k);
            detailsSummary = `تعديل الحركة المالية رقم <strong>${recordId}</strong> ببيان <strong>"${desc}"</strong> في الحقول (${keys.join(', ')})`;
        } else if (log.action === 'delete') {
            detailsSummary = `حذف الحركة المالية <strong>(${typeStr})</strong> بمبلغ <strong>${formattedAmount}</strong> ذات البيان <strong>"${desc}"</strong>`;
        }
    } else if (log.tableName === 'debtors') {
        const name = newData.name || oldData.name || "";
        if (log.action === 'insert') {
            detailsSummary = `تسجيل عميل مدين جديد باسم <strong>"${name}"</strong>`;
        } else if (log.action === 'update') {
            detailsSummary = `تعديل ملف العميل المدين <strong>"${name}"</strong>`;
        } else if (log.action === 'delete') {
            detailsSummary = `حذف ملف العميل المدين <strong>"${name}"</strong> من النظام`;
        }
    } else if (log.tableName === 'safes') {
        const name = newData.name || oldData.name || "";
        if (log.action === 'insert') {
            detailsSummary = `إنشاء صندوق مالي جديد باسم <strong>"${name}"</strong>`;
        } else if (log.action === 'update') {
            detailsSummary = `تعديل بيانات الصندوق المالي <strong>"${name}"</strong>`;
        } else if (log.action === 'delete') {
            detailsSummary = `حذف الصندوق المالي <strong>"${name}"</strong> من النظام`;
        }
    } else if (log.tableName === 'system_settings') {
        detailsSummary = "تحديث إعدادات النظام والسياسات المالية للمنشأة";
    } else if (log.tableName === 'users') {
        const uName = newData.username || oldData.username || newData.name || oldData.name || "";
        detailsSummary = `تعديل بيانات حساب المستخدم <strong>"${uName}"</strong>`;
    }

    // Default fallback if not matched
    if (!detailsSummary) {
        if (log.action === 'insert') detailsSummary = "إضافة سجل جديد لقاعدة البيانات";
        else if (log.action === 'delete') detailsSummary = "حذف سجل من النظام نهائياً";
        else if (log.action === 'payment') detailsSummary = "تسجيل حركة تسديد مالي";
        else {
            const keys = Object.keys(newData).map(k => KEY_TRANSLATIONS[k] || k);
            detailsSummary = `تعديل الحقول: (${keys.join(', ')})`;
        }
    }

    return `قام الموظف ${user} بعملية <strong>${actionWord}</strong> في تاريخ <strong>${dateFormatted}</strong> لمعرف سجله <strong>${recordId}</strong> وببياناته: ${detailsSummary}`;
}

function renderTable() {
    dom.logsTbody.innerHTML = "";

    if (state.logs.length === 0) {
        dom.emptyStateView.style.display = "flex";
        document.getElementById("logs-table").style.display = "none";
        return;
    }

    dom.emptyStateView.style.display = "none";
    document.getElementById("logs-table").style.display = "table";

    state.logs.forEach((log, index) => {
        const rowNum = (state.currentPage - 1) * state.pageSize + index + 1;

        // Formatted elements
        const actionLabel = ACTION_TRANSLATIONS[log.action] || log.action;
        let actionClass = "badge-custom ";
        if (log.action === 'insert') actionClass += "badge-success";
        else if (log.action === 'update') actionClass += "badge-warning";
        else if (log.action === 'delete') actionClass += "badge-danger";
        else if (log.action === 'payment') actionClass += "badge-primary";

        const tableLabel = TABLE_TRANSLATIONS[log.tableName] || log.tableName;
        const detailedDescription = generateDetailedDescription(log);

        const tr = document.createElement("tr");
        tr.innerHTML = `
            <td><strong>${rowNum}</strong></td>
            <td>
                <div style="font-weight:700; color:var(--text-primary);">${log.userFullname}</div>
                <div style="font-size:11px; color:var(--text-secondary);">@${log.userUsername}</div>
            </td>
            <td><span class="${actionClass}">${actionLabel}</span></td>
            <td><span style="font-weight:600; color:var(--text-secondary);"><i class="fa-regular fa-folder" style="margin-left:6px;"></i>${tableLabel}</span></td>
            <td><code>#${log.recordId}</code></td>
            <td style="max-width: 450px;"><div style="font-size:12.5px; line-height:1.6; color:var(--text-secondary); text-align:right;">${detailedDescription}</div></td>
            <td><span style="font-size:12px; color:var(--text-secondary);"><i class="fa-regular fa-calendar" style="margin-left:4px;"></i>${formatDateTime(log.createdAt)}</span></td>
            <td>
                <button class="btn btn-sm btn-secondary-outline" onclick="viewLogDetail(${log.id})" style="padding:6px 12px; display:flex; align-items:center; gap:5px; font-size:11.5px;">
                    <i class="fa-solid fa-eye"></i> التفاصيل
                </button>
            </td>
        `;
        dom.logsTbody.appendChild(tr);
    });
}

// -------------------------------------------------------------
// 5. Difference comparison formatter (WOW Factor!)
// -------------------------------------------------------------
window.viewLogDetail = function (logId) {
    const log = state.logs.find(l => l.id == logId);
    if (!log) return;

    // Header details
    dom.detailUser.textContent = `${log.userFullname} (@${log.userUsername})`;

    const actionLabel = ACTION_TRANSLATIONS[log.action] || log.action;
    dom.detailAction.textContent = actionLabel;
    dom.detailAction.className = "badge-custom " +
        (log.action === 'insert' ? 'badge-success' :
            log.action === 'update' ? 'badge-warning' :
                log.action === 'delete' ? 'badge-danger' : 'badge-primary');

    dom.detailTable.textContent = TABLE_TRANSLATIONS[log.tableName] || log.tableName;
    dom.detailDate.textContent = formatDateTime(log.createdAt) + ` (#${log.recordId})`;

    // Fill diff data
    dom.comparisonTbody.innerHTML = "";
    const theadTr = document.getElementById("comparison-thead-tr");

    const formatValue = (key, val) => {
        if (val === undefined || val === null) return '-';
        if (typeof val === 'number') {
            if (['price', 'amount', 'total', 'grand_total', 'grandTotal', 'worker_share', 'commission', 'commission_10', 'max_daily_expense', 'low_balance_threshold'].includes(key)) {
                return parseFloat(val).toLocaleString('ar-EG') + ' د.ع';
            }
            return val.toLocaleString('ar-EG');
        }
        if (key === 'status') {
            return val == '1' ? 'مسددة بالكامل 🟢' : val == '2' ? 'متبقي دين 🟡' : 'جديدة ⚪';
        }
        return val;
    };

    if (log.action === 'update' && log.details && log.details.new && Object.keys(log.details.new).length > 0) {
        dom.comparisonSection.style.display = "block";
        dom.rawJsonSection.style.display = "block";

        if (theadTr) {
            theadTr.innerHTML = `
                <th>الحقل المعدل</th>
                <th style="background:rgba(239,68,68,0.05); color:var(--danger);">القيمة السابقة (قبل)</th>
                <th style="background:rgba(16,185,129,0.05); color:var(--success);">القيمة الجديدة (بعد)</th>
            `;
        }

        const oldData = log.details.old || {};
        const newData = log.details.new || {};

        Object.keys(newData).forEach(key => {
            const fieldLabel = KEY_TRANSLATIONS[key] || key;
            const valOld = formatValue(key, oldData[key]);
            const valNew = formatValue(key, newData[key]);

            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td style="font-weight:700; color:var(--text-primary); font-size:13px;">${fieldLabel}</td>
                <td style="background:rgba(239,68,68,0.02); color:var(--danger); font-family:monospace; font-size:12.5px;">${valOld}</td>
                <td style="background:rgba(16,185,129,0.02); color:var(--success); font-family:monospace; font-size:12.5px; font-weight:700;">${valNew}</td>
            `;
            dom.comparisonTbody.appendChild(tr);
        });
    } else if (log.action === 'insert' && log.details && log.details.new) {
        dom.comparisonSection.style.display = "block";
        dom.rawJsonSection.style.display = "block";

        if (theadTr) {
            theadTr.innerHTML = `
                <th>الحقل المضاف</th>
                <th style="background:rgba(16,185,129,0.05); color:var(--success);" colspan="2">القيمة المدخلة</th>
            `;
        }

        const newData = log.details.new || {};
        Object.keys(newData).forEach(key => {
            const fieldLabel = KEY_TRANSLATIONS[key] || key;
            const valNew = formatValue(key, newData[key]);

            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td style="font-weight:700; color:var(--text-primary); font-size:13px;">${fieldLabel}</td>
                <td style="background:rgba(16,185,129,0.02); color:var(--success); font-family:monospace; font-size:12.5px; font-weight:700;" colspan="2">${valNew}</td>
            `;
            dom.comparisonTbody.appendChild(tr);
        });
    } else if (log.action === 'delete' && log.details && log.details.old) {
        dom.comparisonSection.style.display = "block";
        dom.rawJsonSection.style.display = "block";

        if (theadTr) {
            theadTr.innerHTML = `
                <th>الحقل المحذوف</th>
                <th style="background:rgba(239,68,68,0.05); color:var(--danger);" colspan="2">القيمة السابقة</th>
            `;
        }

        const oldData = log.details.old || {};
        Object.keys(oldData).forEach(key => {
            const fieldLabel = KEY_TRANSLATIONS[key] || key;
            const valOld = formatValue(key, oldData[key]);

            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td style="font-weight:700; color:var(--text-primary); font-size:13px;">${fieldLabel}</td>
                <td style="background:rgba(239,68,68,0.02); color:var(--danger); font-family:monospace; font-size:12.5px;" colspan="2">${valOld}</td>
            `;
            dom.comparisonTbody.appendChild(tr);
        });
    } else if (log.action === 'payment' && log.details) {
        dom.comparisonSection.style.display = "block";
        dom.rawJsonSection.style.display = "block";

        if (theadTr) {
            theadTr.innerHTML = `
                <th>الحقل المالي</th>
                <th style="background:rgba(99,102,241,0.05); color:var(--primary);" colspan="2">تفاصيل تسديد العملية</th>
            `;
        }

        const detailsData = log.details;
        Object.keys(detailsData).forEach(key => {
            if (key === 'old' || key === 'new') return;
            const fieldLabel = KEY_TRANSLATIONS[key] || key;
            const val = formatValue(key, detailsData[key]);

            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td style="font-weight:700; color:var(--text-primary); font-size:13px;">${fieldLabel}</td>
                <td style="background:rgba(99,102,241,0.02); color:var(--primary); font-family:monospace; font-size:12.5px; font-weight:700;" colspan="2">${val}</td>
            `;
            dom.comparisonTbody.appendChild(tr);
        });
    } else {
        dom.comparisonSection.style.display = "none";
        dom.rawJsonSection.style.display = "block";
    }

    // Pretty print json
    dom.rawJsonView.textContent = JSON.stringify(log.details, null, 4);

    // Open Modal
    dom.detailModal.classList.add("open");
    document.body.style.overflow = "hidden"; // disable background scroll
};

function closeModal() {
    dom.detailModal.classList.remove("open");
    document.body.style.overflow = "";
}

// -------------------------------------------------------------
// 6. Pagination UI Builder
// -------------------------------------------------------------
function renderPagination() {
    const totalPages = Math.ceil(state.totalLogs / state.pageSize);
    const startEntry = state.totalLogs === 0 ? 0 : (state.currentPage - 1) * state.pageSize + 1;
    const endEntry = Math.min(state.currentPage * state.pageSize, state.totalLogs);

    dom.paginationInfoText.textContent = `يعرض ${startEntry} إلى ${endEntry} من أصل ${state.totalLogs} سجل عمل`;
    dom.paginationControls.innerHTML = "";

    if (totalPages <= 1) return;

    // Prev Button
    const prevBtn = document.createElement("button");
    prevBtn.className = `btn btn-icon-only ${state.currentPage === 1 ? 'disabled' : ''}`;
    prevBtn.innerHTML = '<i class="fa-solid fa-angle-right"></i>';
    prevBtn.addEventListener("click", () => {
        if (state.currentPage > 1) {
            state.currentPage--;
            loadData(false);
        }
    });
    dom.paginationControls.appendChild(prevBtn);

    // Page Numbers
    for (let i = 1; i <= totalPages; i++) {
        if (totalPages > 6 && Math.abs(state.currentPage - i) > 2 && i !== 1 && i !== totalPages) {
            if (i === 2 || i === totalPages - 1) {
                const dots = document.createElement("span");
                dots.textContent = "...";
                dots.style.margin = "0 8px";
                dots.style.color = "var(--text-muted)";
                dom.paginationControls.appendChild(dots);
            }
            continue;
        }

        const pageBtn = document.createElement("button");
        pageBtn.className = `btn btn-icon-only ${state.currentPage === i ? 'btn-primary' : 'btn-secondary-outline'}`;
        pageBtn.textContent = i.toLocaleString('ar-EG');
        pageBtn.addEventListener("click", () => {
            state.currentPage = i;
            loadData(false);
        });
        dom.paginationControls.appendChild(pageBtn);
    }

    // Next Button
    const nextBtn = document.createElement("button");
    nextBtn.className = `btn btn-icon-only ${state.currentPage === totalPages ? 'disabled' : ''}`;
    nextBtn.innerHTML = '<i class="fa-solid fa-angle-left"></i>';
    nextBtn.addEventListener("click", () => {
        if (state.currentPage < totalPages) {
            state.currentPage++;
            loadData(false);
        }
    });
    dom.paginationControls.appendChild(nextBtn);
}

// -------------------------------------------------------------
// 7. Excel Export & Printable Report Features
// -------------------------------------------------------------
window.exportLogsToExcel = function () {
    if (!state.logs || state.logs.length === 0) {
        showToast("لا توجد سجلات متاحة للتصدير", "warning");
        return;
    }

    let csvContent = "\uFEFF"; // UTF-8 BOM for Arabic support in Excel
    csvContent += "التسلسل,الموظف المسؤول,اسم المستخدم,نوع العملية,الجدول المستهدف,معرف السجل,تاريخ العملية\n";

    state.logs.forEach((log, index) => {
        const rowNum = index + 1;
        const userFull = `"${log.userFullname.replace(/"/g, '""')}"`;
        const userUser = `"${log.userUsername.replace(/"/g, '""')}"`;
        const actionLabel = `"${(ACTION_TRANSLATIONS[log.action] || log.action).replace(/"/g, '""')}"`;
        const tableLabel = `"${(TABLE_TRANSLATIONS[log.tableName] || log.tableName).replace(/"/g, '""')}"`;
        const recordId = `"#${log.recordId}"`;
        const dateStr = `"${formatDateTime(log.createdAt)}"`;

        csvContent += `${rowNum},${userFull},${userUser},${actionLabel},${tableLabel},${recordId},${dateStr}\n`;
    });

    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    const today = new Date().toISOString().split('T')[0];
    link.href = url;
    link.download = `activity_logs_${today}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    showToast("تم تصدير سجل الأنشطة إلى Excel بنجاح!");
};

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

    const printWin = window.open('', '_blank');
    const today = new Date().toLocaleDateString('ar-EG');

    let rowsHtml = '';
    state.logs.forEach((log, index) => {
        const actionLabel = ACTION_TRANSLATIONS[log.action] || log.action;
        const tableLabel = TABLE_TRANSLATIONS[log.tableName] || log.tableName;
        rowsHtml += `
            <tr>
                <td>${index + 1}</td>
                <td>${log.userFullname} (@${log.userUsername})</td>
                <td>${actionLabel}</td>
                <td>${tableLabel}</td>
                <td>#${log.recordId}</td>
                <td>${formatDateTime(log.createdAt)}</td>
            </tr>
        `;
    });

    const orgName = getOrgName();
    printWin.document.write(`<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>تقرير سجل حركات النظام – ${escapeHTML(orgName)}</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, #475569 0%, #334155 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: #334155;
        margin-bottom: 4px;
    }
    .report-meta {
        font-size: 11px;
        color: #475569;
        line-height: 1.5;
    }

    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;
        text-align: center;
    }
    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>${state.logs.length} سجل</strong></div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="border:none; padding:0;">
                    <table class="report-table">
                        <thead>
                            <tr>
                                <th style="width:40px;">ت</th>
                                <th>الموظف المسؤول</th>
                                <th>نوع العملية</th>
                                <th>الجدول المستهدف</th>
                                <th>معرف السجل</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 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 || "مكتب الحاج أمجد سهل عبدالامير";
}

// -------------------------------------------------------------
// 8. General Helpers
// -------------------------------------------------------------
window.doFilterLogs = function () {
    state.searchQuery = dom.searchInput ? dom.searchInput.value.trim() : "";
    state.filterAction = dom.filterAction ? dom.filterAction.value : "";
    state.filterTable = dom.filterTable ? dom.filterTable.value : "";
    state.fromDate = dom.filterFromDate ? dom.filterFromDate.value : "";
    state.toDate = dom.filterToDate ? dom.filterToDate.value : "";
    state.currentPage = 1;
    loadData(false);
};

window.clearFiltersLogs = function () {
    if (dom.searchInput) dom.searchInput.value = "";
    if (dom.filterAction) dom.filterAction.value = "";
    if (dom.filterTable) dom.filterTable.value = "";
    if (dom.filterFromDate) dom.filterFromDate.value = "";
    if (dom.filterToDate) dom.filterToDate.value = "";

    const actLbl = document.getElementById("selected-action-label");
    const tblLbl = document.getElementById("selected-table-label");
    if (actLbl) actLbl.textContent = "جميع العمليات";
    if (tblLbl) tblLbl.textContent = "جميع الجداول";

    state.searchQuery = "";
    state.filterAction = "";
    state.filterTable = "";
    state.fromDate = "";
    state.toDate = "";
    state.currentPage = 1;
    loadData(false);
};

window.setQuickDate = function (preset) {
    const today = new Date();
    const formatDate = (d) => {
        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}`;
    };

    if (preset === 'today') {
        const dateStr = formatDate(today);
        if (dom.filterFromDate) dom.filterFromDate.value = dateStr;
        if (dom.filterToDate) dom.filterToDate.value = dateStr;
        state.fromDate = dateStr;
        state.toDate = dateStr;
    } else if (preset === 'yesterday') {
        const yesterday = new Date();
        yesterday.setDate(today.getDate() - 1);
        const dateStr = formatDate(yesterday);
        if (dom.filterFromDate) dom.filterFromDate.value = dateStr;
        if (dom.filterToDate) dom.filterToDate.value = dateStr;
        state.fromDate = dateStr;
        state.toDate = dateStr;
    } else if (preset === 'this_week') {
        const firstDay = new Date(today);
        firstDay.setDate(today.getDate() - 7);
        if (dom.filterFromDate) dom.filterFromDate.value = formatDate(firstDay);
        if (dom.filterToDate) dom.filterToDate.value = formatDate(today);
        state.fromDate = formatDate(firstDay);
        state.toDate = formatDate(today);
    } else if (preset === 'all') {
        if (dom.filterFromDate) dom.filterFromDate.value = "";
        if (dom.filterToDate) dom.filterToDate.value = "";
        state.fromDate = "";
        state.toDate = "";
    }
    state.currentPage = 1;
    loadData(false);
};

window.setQuickAction = function (actionVal) {
    if (dom.filterAction) dom.filterAction.value = actionVal;
    state.filterAction = actionVal;
    state.currentPage = 1;
    loadData(false);
};

window.setQuickTable = function (tableVal) {
    if (dom.filterTable) dom.filterTable.value = tableVal;
    state.filterTable = tableVal;
    state.currentPage = 1;
    loadData(false);
};

// -------------------------------------------------------------
// Custom Styled Floating Dropdown Components
// -------------------------------------------------------------
window.toggleCustomDropdown = function (type) {
    const actionMenu = document.getElementById("custom-action-menu");
    const tableMenu = document.getElementById("custom-table-menu");

    if (type === 'action') {
        if (tableMenu) tableMenu.style.display = "none";
        if (actionMenu) {
            actionMenu.style.display = actionMenu.style.display === "block" ? "none" : "block";
        }
    } else if (type === 'table') {
        if (actionMenu) actionMenu.style.display = "none";
        if (tableMenu) {
            tableMenu.style.display = tableMenu.style.display === "block" ? "none" : "block";
        }
    }
};

window.selectCustomOption = function (type, val, label) {
    if (type === 'action') {
        const sel = document.getElementById("filter-action");
        const lbl = document.getElementById("selected-action-label");
        const menu = document.getElementById("custom-action-menu");
        if (sel) sel.value = val;
        if (lbl) lbl.textContent = label;
        if (menu) menu.style.display = "none";
        state.filterAction = val;
    } else if (type === 'table') {
        const sel = document.getElementById("filter-table");
        const lbl = document.getElementById("selected-table-label");
        const menu = document.getElementById("custom-table-menu");
        if (sel) sel.value = val;
        if (lbl) lbl.textContent = label;
        if (menu) menu.style.display = "none";
        state.filterTable = val;
    }
    state.currentPage = 1;
    loadData(false);
};

document.addEventListener("click", (e) => {
    const actionBtn = document.getElementById("custom-action-dropdown-btn");
    const actionMenu = document.getElementById("custom-action-menu");
    const tableBtn = document.getElementById("custom-table-dropdown-btn");
    const tableMenu = document.getElementById("custom-table-menu");

    if (actionMenu && actionBtn && !actionBtn.contains(e.target) && !actionMenu.contains(e.target)) {
        actionMenu.style.display = "none";
    }
    if (tableMenu && tableBtn && !tableBtn.contains(e.target) && !tableMenu.contains(e.target)) {
        tableMenu.style.display = "none";
    }
});

// -------------------------------------------------------------
// Interactive Arabic Custom Date Picker Component
// -------------------------------------------------------------
let currentPickerInput = null;
let pickerDate = new Date();

window.openCustomDatePicker = function (targetInputId) {
    const targetInput = document.getElementById(targetInputId);
    if (!targetInput) return;

    currentPickerInput = targetInput;
    if (targetInput.value) {
        const parts = targetInput.value.split('-');
        if (parts.length === 3) {
            pickerDate = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
        }
    } else {
        pickerDate = new Date();
    }

    renderCustomDatePickerModal();
};

function renderCustomDatePickerModal() {
    let modal = document.getElementById("custom-date-picker-modal");
    if (!modal) {
        modal = document.createElement("div");
        modal.id = "custom-date-picker-modal";
        modal.style.cssText = `
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.45);
            backdrop-filter: blur(4px);
            z-index: 99999;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 16px;
        `;
        document.body.appendChild(modal);

        modal.addEventListener("click", (e) => {
            if (e.target === modal) closeCustomDatePickerModal();
        });
    }

    const year = pickerDate.getFullYear();
    const month = pickerDate.getMonth();

    const monthNames = ["كانون الثاني (1)", "شباط (2)", "آذار (3)", "نيسان (4)", "أيار (5)", "حزيران (6)", "تموز (7)", "آب (8)", "أيلول (9)", "تشرين الأول (10)", "تشرين الثاني (11)", "كانون الأول (12)"];

    const firstDayIndex = new Date(year, month, 1).getDay();
    const totalDays = new Date(year, month + 1, 0).getDate();

    let daysHtml = "";
    for (let x = 0; x < firstDayIndex; x++) {
        daysHtml += `<div style="padding:8px;"></div>`;
    }

    const selectedVal = currentPickerInput ? currentPickerInput.value : "";
    const todayStr = new Date().toISOString().split('T')[0];

    for (let d = 1; d <= totalDays; d++) {
        const dStr = String(d).padStart(2, '0');
        const mStr = String(month + 1).padStart(2, '0');
        const fullDateStr = `${year}-${mStr}-${dStr}`;
        const isSelected = selectedVal === fullDateStr;
        const isToday = todayStr === fullDateStr;

        let style = "color:var(--text-primary); border-radius:50%; border:1px solid transparent;";
        if (isSelected) {
            style = "background:var(--primary); color:#fff; font-weight:700; border-radius:50%; box-shadow:0 2px 8px rgba(59,130,246,0.3);";
        } else if (isToday) {
            style = "border:1.5px solid var(--primary); color:var(--primary); font-weight:700; border-radius:50%;";
        }

        daysHtml += `
            <button type="button" onclick="selectDatePickerDate('${fullDateStr}')" style="width:36px; height:36px; border:none; cursor:pointer; font-family:var(--font-family); font-size:13px; margin:auto; transition:var(--transition); ${style}" onmouseover="if(!${isSelected})this.style.background='var(--primary-light)'" onmouseout="if(!${isSelected})this.style.background='transparent'">
                ${d}
            </button>
        `;
    }

    modal.innerHTML = `
        <div style="background:var(--bg-card); border:1px solid var(--border-color); border-radius:var(--radius-lg); width:330px; padding:20px; box-shadow:var(--shadow-xl); color:var(--text-primary); font-family:var(--font-family); direction:rtl; animation: fadeIn 0.15s ease;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
                <button type="button" onclick="changePickerMonth(-1)" class="btn btn-sm btn-secondary-outline" style="padding:6px 12px;"><i class="fa-solid fa-chevron-right"></i></button>
                <div style="font-weight:700; font-size:14px; color:var(--primary);">${monthNames[month]} ${year}</div>
                <button type="button" onclick="changePickerMonth(1)" class="btn btn-sm btn-secondary-outline" style="padding:6px 12px;"><i class="fa-solid fa-chevron-left"></i></button>
            </div>
            
            <div style="display:grid; grid-template-columns:repeat(7, 1fr); text-align:center; font-size:11px; font-weight:700; color:var(--text-muted); margin-bottom:8px;">
                <div>أحد</div><div>إثنين</div><div>ثلاثاء</div><div>أربعاء</div><div>خميس</div><div>جمعة</div><div>سبت</div>
            </div>
            
            <div style="display:grid; grid-template-columns:repeat(7, 1fr); gap:4px; text-align:center; margin-bottom:16px;">
                ${daysHtml}
            </div>
            
            <div style="display:flex; justify-content:space-between; align-items:center; border-top:1px solid var(--border-color); padding-top:12px;">
                <button type="button" onclick="selectDatePickerDate('${new Date().toISOString().split('T')[0]}')" class="btn btn-sm btn-secondary-outline" style="font-size:12px; gap:4px;"><i class="fa-solid fa-calendar-day" style="color:var(--primary);"></i> اختر اليوم</button>
                <button type="button" onclick="closeCustomDatePickerModal()" class="btn btn-sm btn-secondary" style="font-size:12px;">إلغاء</button>
            </div>
        </div>
    `;
    modal.style.display = "flex";
}

window.changePickerMonth = function (delta) {
    pickerDate.setMonth(pickerDate.getMonth() + delta);
    renderCustomDatePickerModal();
};

window.selectDatePickerDate = function (dateStr) {
    if (currentPickerInput) {
        currentPickerInput.value = dateStr;
        if (currentPickerInput.id === 'filter-from-date') state.fromDate = dateStr;
        if (currentPickerInput.id === 'filter-to-date') state.toDate = dateStr;
        state.currentPage = 1;
        loadData(false);
    }
    closeCustomDatePickerModal();
};

window.closeCustomDatePickerModal = function () {
    const modal = document.getElementById("custom-date-picker-modal");
    if (modal) modal.style.display = "none";
};

function formatDateTime(dbTimestamp) {
    if (!dbTimestamp) return "";
    const normalized = dbTimestamp.replace(' ', 'T');
    const date = new Date(normalized);
    if (isNaN(date.getTime())) {
        return dbTimestamp;
    }

    const optionsDate = { year: 'numeric', month: 'short', day: 'numeric' };
    const optionsTime = { hour: '2-digit', minute: '2-digit', hour12: true };

    try {
        const dStr = date.toLocaleDateString('ar-EG', optionsDate);
        const tStr = date.toLocaleTimeString('ar-EG', optionsTime);
        return `${dStr} - ${tStr}`;
    } catch (e) {
        return dbTimestamp;
    }
}

// Show Toast Alerts
function showToast(message, type = "success") {
    let container = document.getElementById("toast-container");
    if (!container) {
        container = document.createElement("div");
        container.className = "toast-container";
        container.id = "toast-container";
        document.body.appendChild(container);
    }

    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>
    `;

    container.appendChild(toast);
    setTimeout(() => {
        toast.remove();
    }, 3500);
}

// Theme logic
function initTheme() {
    const savedTheme = localStorage.getItem("dashboard_theme") || "light";
    document.documentElement.setAttribute("data-theme", savedTheme);

    const themeBtn = document.getElementById("theme-toggle");
    if (themeBtn) {
        const icon = themeBtn.querySelector("i");
        if (savedTheme === "dark") {
            icon.className = "fa-solid fa-sun";
        } else {
            icon.className = "fa-solid fa-moon";
        }

        themeBtn.addEventListener("click", () => {
            const currentTheme = document.documentElement.getAttribute("data-theme");
            const newTheme = currentTheme === "dark" ? "light" : "dark";
            document.documentElement.setAttribute("data-theme", newTheme);
            localStorage.setItem("dashboard_theme", newTheme);
            icon.className = newTheme === "dark" ? "fa-solid fa-sun" : "fa-solid fa-moon";
        });
    }
}
