// Business Logic and Operations for Users and Permissions Page

// -------------------------------------------------------------
// 1. App State
// -------------------------------------------------------------
let state = {
    users: [],
    filteredUsers: [],
    currentPage: 1,
    pageSize: 10,
    currentUserIdToEdit: null,
    currentUserIdToDelete: null,
    searchQuery: "",
    viewMode: "cards" // 'cards' or 'table'
};

// -------------------------------------------------------------
// 2. DOM Elements Selection
// -------------------------------------------------------------
const dom = {
    // Stats
    statTotalUsers: document.getElementById("stat-total-users"),
    statActiveUsers: document.getElementById("stat-active-users"),
    statSuspendedUsers: document.getElementById("stat-suspended-users"),

    // Table / Cards elements
    usersTbody: document.getElementById("users-tbody"),
    usersCardsGrid: document.getElementById("users-cards-grid"),
    usersTableWrapper: document.getElementById("users-table-wrapper"),
    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"),
    searchResultsBadge: document.getElementById("search-results-badge"),

    // Modals
    userModal: document.getElementById("user-modal"),
    modalTitle: document.getElementById("modal-title"),
    userForm: document.getElementById("user-form"),
    userIdInput: document.getElementById("user-id"),
    userFullnameInput: document.getElementById("user-fullname"),
    userUsernameInput: document.getElementById("user-username"),
    userPasswordInput: document.getElementById("user-password"),
    userStatusInput: document.getElementById("user-status"),
    passwordReq: document.getElementById("password-req"),
    passwordHelpText: document.getElementById("password-help-text"),
    btnToggleModalPassword: document.getElementById("btn-toggle-modal-password"),
    modalPasswordToggleIcon: document.getElementById("modal-password-toggle-icon"),
    
    // Add / Close Buttons
    openAddModalBtn: document.getElementById("open-add-modal-btn"),
    closeModalBtn: document.getElementById("close-modal-btn"),
    cancelModalBtn: document.getElementById("cancel-modal-btn"),
    emptyStateAddBtn: document.getElementById("empty-state-add-btn"),

    // Delete Confirmation Modal
    deleteConfirmModal: document.getElementById("delete-confirm-modal"),
    cancelDeleteBtn: document.getElementById("cancel-delete-btn"),
    confirmDeleteBtn: document.getElementById("confirm-delete-btn"),
    deleteItemName: document.getElementById("delete-item-name"),

    // Theme & Toast
    themeToggle: document.getElementById("theme-toggle"),
    toastContainer: document.getElementById("toast-container")
};

// -------------------------------------------------------------
// 3. Helper Functions for Permission Matrix
// -------------------------------------------------------------
function setPermissionCheckboxes(perms) {
    if (!perms) return;
    
    const keys = [
        "index", "gatherers", "customers", "expenses", "safes", 
        "materials", "materials_report", "gatherers_report", "settlements", "calibration", "forms", "pricing", "debts", "users", "activity_logs", "settings",
        "view_others_data"
    ];
    
    keys.forEach(k => {
        const pagePerms = perms[k] || { view: false, add: false, edit: false, delete: false };
        
        // view checkbox
        const viewEl = document.getElementById(`perm-${k}-view`);
        if (viewEl) viewEl.checked = !!pagePerms.view;
        
        // add checkbox
        const addEl = document.getElementById(`perm-${k}-add`);
        if (addEl) addEl.checked = !!pagePerms.add;
        
        // edit checkbox
        const editEl = document.getElementById(`perm-${k}-edit`);
        if (editEl) editEl.checked = !!pagePerms.edit;
        
        // delete checkbox
        const deleteEl = document.getElementById(`perm-${k}-delete`);
        if (deleteEl) deleteEl.checked = !!pagePerms.delete;
    });
}

function getPermissionFromCheckboxes() {
    const keys = [
        "index", "gatherers", "customers", "expenses", "safes", 
        "materials", "materials_report", "gatherers_report", "settlements", "forms", "pricing", "debts", "users", "activity_logs", "settings",
        "view_others_data"
    ];
    
    const perms = {};
    keys.forEach(k => {
        const viewEl = document.getElementById(`perm-${k}-view`);
        const addEl = document.getElementById(`perm-${k}-add`);
        const editEl = document.getElementById(`perm-${k}-edit`);
        const deleteEl = document.getElementById(`perm-${k}-delete`);
        
        perms[k] = {
            view: viewEl ? viewEl.checked : false,
            add: addEl ? addEl.checked : false,
            edit: editEl ? editEl.checked : false,
            delete: deleteEl ? deleteEl.checked : false
        };
    });
    return perms;
}

window.toggleAllPermissions = function(checkAll) {
    const checkboxes = document.querySelectorAll('.perm-matrix-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = !!checkAll;
    });
};

window.generateRandomPassword = function() {
    const chars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789!@#$%&*";
    let pass = "";
    for (let i = 0; i < 10; i++) {
        pass += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    if (dom.userPasswordInput) {
        dom.userPasswordInput.value = pass;
        dom.userPasswordInput.type = "text";
        if (dom.modalPasswordToggleIcon) {
            dom.modalPasswordToggleIcon.className = "fa-solid fa-eye-slash";
        }
    }
    showToast(`تم توليد كلمة مرور عشوائية جديدة`, "info");
};

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

// -------------------------------------------------------------
// 4. App Initialization
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    // Retrieve viewMode preference from localStorage
    const savedViewMode = localStorage.getItem("users_view_mode");
    if (savedViewMode === "table" || savedViewMode === "cards") {
        state.viewMode = savedViewMode;
    } else {
        state.viewMode = "cards"; // default
    }
    
    loadUsers();
    initTheme();
    setupEventListeners();

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

    setInterval(() => {
        checkSystemStateAndRefresh(['users'], loadUsers);
    }, 3000);
});

// -------------------------------------------------------------
// 5. Data Loading and State Management
// -------------------------------------------------------------
function loadUsers() {
    fetch('api/users.php?action=list')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                state.users = res.users || [];
            } else {
                state.users = [];
                showToast(res.message || "فشل تحميل قائمة المستخدمين", "danger");
            }
            applyFilters();
        })
        .catch(err => {
            console.error("Load users failed:", err);
            showToast("حدث خطأ أثناء تحميل المستخدمين من الخادم", "danger");
            state.users = [];
            applyFilters();
        });
}

function applyFilters() {
    const q = state.searchQuery.trim().toLowerCase();
    
    if (q) {
        state.filteredUsers = state.users.filter(u => {
            const nameMatch = (u.name || "").toLowerCase().includes(q);
            const usernameMatch = (u.username || "").toLowerCase().includes(q);
            
            const roleText = getUserRoleLabel(u);
            const roleMatch = roleText.toLowerCase().includes(q);
            
            return nameMatch || usernameMatch || roleMatch;
        });
        
        dom.searchResultsBadge.style.display = "inline-block";
        dom.searchResultsBadge.textContent = `${state.filteredUsers.length} نتائج`;
    } else {
        state.filteredUsers = [...state.users];
        dom.searchResultsBadge.style.display = "none";
    }
    
    state.currentPage = 1;
    updateStats();
    renderUsers();
}

// -------------------------------------------------------------
// 6. Statistics calculation
// -------------------------------------------------------------
function updateStats() {
    const total = state.users.length;
    const active = state.users.filter(u => u.status === "active").length;
    const suspended = state.users.filter(u => u.status === "suspended").length;
    
    if (dom.statTotalUsers) dom.statTotalUsers.textContent = total;
    if (dom.statActiveUsers) dom.statActiveUsers.textContent = active;
    if (dom.statSuspendedUsers) dom.statSuspendedUsers.textContent = suspended;
}

// Helper to get initials from fullname
function getInitials(name) {
    if (!name) return "👤";
    const parts = name.trim().split(/\s+/);
    if (parts.length >= 2) {
        return (parts[0][0] + parts[1][0]).toUpperCase();
    }
    return parts[0].substring(0, 2).toUpperCase();
}

// Arabic mapping for page permissions labels
const PERM_PAGE_LABELS = {
    index: "الرئيسية",
    gatherers: "الجلابين",
    customers: "العملاء",
    expenses: "المصروفات",
    safes: "الصناديق",
    materials: "إضافة المادة",
    materials_report: "كشف المواد",
    gatherers_report: "كشف الجلابين",
    settlements: "التسويات",
    forms: "الاستمارات",
    pricing: "التسعير",
    debts: "الديون",
    users: "المستخدمين",
    activity_logs: "سجل العمليات",
    settings: "الإعدادات",
    view_others_data: "بيانات الآخرين"
};

// Handle toggle between Cards View and Table View
window.setViewMode = function(mode) {
    state.viewMode = mode;
    localStorage.setItem("users_view_mode", mode);
    renderUsers();
};

// -------------------------------------------------------------
// 7. Dynamic Rendering of Table List
// -------------------------------------------------------------
function renderUsers() {
    if (!dom.usersTbody) return;
    
    // Toggle containers visibility
    if (state.viewMode === "cards") {
        if (dom.usersCardsGrid) dom.usersCardsGrid.style.display = "grid";
        if (dom.usersTableWrapper) dom.usersTableWrapper.style.display = "none";
    } else {
        if (dom.usersCardsGrid) dom.usersCardsGrid.style.display = "none";
        if (dom.usersTableWrapper) dom.usersTableWrapper.style.display = "block";
    }
    
    // Update button highlighting style
    const btnCards = document.getElementById("btn-view-cards");
    const btnTable = document.getElementById("btn-view-table");
    if (btnCards && btnTable) {
        if (state.viewMode === "cards") {
            btnCards.style.background = "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)";
            btnCards.style.color = "#fff";
            btnCards.style.border = "none";
            btnCards.style.boxShadow = "0 2px 8px rgba(99, 102, 241, 0.2)";
            
            btnTable.style.background = "var(--bg-input)";
            btnTable.style.color = "var(--text-secondary)";
            btnTable.style.border = "1.5px solid var(--border-color)";
            btnTable.style.boxShadow = "none";
        } else {
            btnTable.style.background = "linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)";
            btnTable.style.color = "#fff";
            btnTable.style.border = "none";
            btnTable.style.boxShadow = "0 2px 8px rgba(99, 102, 241, 0.2)";
            
            btnCards.style.background = "var(--bg-input)";
            btnCards.style.color = "var(--text-secondary)";
            btnCards.style.border = "1.5px solid var(--border-color)";
            btnCards.style.boxShadow = "none";
        }
    }
    
    dom.usersTbody.innerHTML = "";
    if (dom.usersCardsGrid) dom.usersCardsGrid.innerHTML = "";
    
    const startIdx = (state.currentPage - 1) * state.pageSize;
    const endIdx = startIdx + state.pageSize;
    const pageUsers = state.filteredUsers.slice(startIdx, endIdx);
    
    if (state.filteredUsers.length === 0) {
        if (dom.usersCardsGrid) dom.usersCardsGrid.style.display = "none";
        if (dom.usersTableWrapper) dom.usersTableWrapper.style.display = "none";
        dom.emptyStateView.style.display = "flex";
        dom.paginationInfoText.textContent = "يعرض 0 إلى 0 من أصل 0 مستخدم";
        dom.paginationControls.innerHTML = "";
        return;
    }
    
    dom.emptyStateView.style.display = "none";
    
    // A. Render Cards Mode
    if (state.viewMode === "cards") {
        pageUsers.forEach((user, idx) => {
            const serial = startIdx + idx + 1;
            const roleText = getUserRoleLabel(user);
            
            let badgeColor = "rgba(100,116,139,0.12)";
            let badgeTextColor = "#64748b";
            let badgeIcon = "fa-user";
            let avatarGradient = "linear-gradient(135deg, #94a3b8 0%, #64748b 100%)";
            
            if (roleText === "مسؤول النظام") {
                badgeColor = "rgba(99,102,241,0.12)";
                badgeTextColor = "#6366f1";
                badgeIcon = "fa-user-shield";
                avatarGradient = "linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%)";
            } else if (roleText === "محاسب") {
                badgeColor = "rgba(16,185,129,0.12)";
                badgeTextColor = "#10b981";
                badgeIcon = "fa-calculator";
                avatarGradient = "linear-gradient(135deg, #34d399 0%, #059669 100%)";
            } else if (roleText === "مشاهد") {
                badgeColor = "rgba(148,163,184,0.15)";
                badgeTextColor = "#475569";
                badgeIcon = "fa-eye";
                avatarGradient = "linear-gradient(135deg, #cbd5e1 0%, #64748b 100%)";
            } else {
                badgeColor = "rgba(245,158,11,0.12)";
                badgeTextColor = "#f59e0b";
                badgeIcon = "fa-user-gear";
                avatarGradient = "linear-gradient(135deg, #fbbf24 0%, #d97706 100%)";
            }
            
            let allowedPagesCount = 0;
            let totalPagesCount = 0;
            const activePermTags = [];
            
            if (user.permissions) {
                const keys = Object.keys(PERM_PAGE_LABELS);
                totalPagesCount = keys.length;
                keys.forEach(k => {
                    const p = user.permissions[k];
                    const label = PERM_PAGE_LABELS[k];
                    if (p && p.view) {
                        allowedPagesCount++;
                        activePermTags.push(`<span class="user-card-perm-tag enabled" title="تصفح ودخول"><i class="fa-solid fa-check"></i> ${label}</span>`);
                    }
                });
            }
            
            const progressPercentage = totalPagesCount > 0 ? (allowedPagesCount / totalPagesCount) * 100 : 0;
            const initials = getInitials(user.name);
            
            const statusBadge = user.status === "active" 
                ? `<span class="user-card-status-badge active"><i class="fa-solid fa-circle-check"></i> نشط</span>`
                : `<span class="user-card-status-badge suspended"><i class="fa-solid fa-circle-xmark"></i> موقوف</span>`;
                
            const card = document.createElement("div");
            card.className = "user-profile-card";
            card.innerHTML = `
                ${statusBadge}
                <div class="user-card-header">
                    <div class="user-card-avatar" style="background: ${avatarGradient};">
                        ${escapeHTML(initials)}
                    </div>
                    <h4 class="user-card-fullname" title="${escapeHTML(user.name)}">${escapeHTML(user.name)}</h4>
                    <span class="user-card-username">@${escapeHTML(user.username)}</span>
                </div>
                <div class="user-card-body">
                    <div class="user-card-info-row">
                        <span class="user-card-info-label"><i class="fa-solid ${badgeIcon}"></i> الدور الوظيفي</span>
                        <span class="user-card-role-badge" style="background: ${badgeColor}; color: ${badgeTextColor};">
                            ${roleText}
                        </span>
                    </div>
                    <div class="user-card-info-row">
                        <span class="user-card-info-label"><i class="fa-solid fa-folder-open"></i> الصفحات المتاحة</span>
                        <span class="user-card-info-value">${allowedPagesCount} / ${totalPagesCount}</span>
                    </div>
                    
                    <div class="user-card-progress-container">
                        <div class="user-card-progress-bar-bg">
                            <div class="user-card-progress-bar-fill" style="width: ${progressPercentage}%;"></div>
                        </div>
                    </div>
                    
                    <div class="user-card-perms-summary">
                        ${activePermTags.length > 0 ? activePermTags.join("") : '<span class="user-card-perm-tag">لا توجد صلاحيات نشطة</span>'}
                    </div>
                </div>
                <div class="user-card-footer">
                    <button type="button" class="user-card-btn-edit" onclick="openEditUserModal('${user.id}')">
                        <i class="fa-solid fa-user-pen"></i> تعديل الصلاحيات
                    </button>
                    <button type="button" class="user-card-btn-delete" onclick="triggerDeleteUser('${user.id}')" title="حذف الحساب">
                        <i class="fa-solid fa-trash-can"></i>
                    </button>
                </div>
            `;
            dom.usersCardsGrid.appendChild(card);
        });
    }
    
    // B. Render Table Mode
    else {
        pageUsers.forEach((user, idx) => {
            const serial = startIdx + idx + 1;
            const roleText = getUserRoleLabel(user);
            
            let badgeColor = "rgba(100,116,139,0.12)";
            let badgeTextColor = "#64748b";
            let badgeIcon = "fa-user";
            if (roleText === "مسؤول النظام") {
                badgeColor = "rgba(99,102,241,0.12)";
                badgeTextColor = "#6366f1";
                badgeIcon = "fa-user-shield";
            } else if (roleText === "محاسب") {
                badgeColor = "rgba(16,185,129,0.12)";
                badgeTextColor = "#10b981";
                badgeIcon = "fa-calculator";
            } else if (roleText === "مشاهد") {
                badgeColor = "rgba(100,116,139,0.12)";
                badgeTextColor = "#64748b";
                badgeIcon = "fa-eye";
            } else {
                badgeColor = "rgba(245,158,11,0.12)";
                badgeTextColor = "#f59e0b";
                badgeIcon = "fa-user-gear";
            }
            
            let allowedPagesCount = 0;
            let totalPagesCount = 0;
            let canViewAny = false;
            let canAddAny = false;
            let canEditAny = false;
            let canDeleteAny = false;
            
            if (user.permissions) {
                const keys = Object.keys(user.permissions);
                totalPagesCount = keys.length;
                keys.forEach(k => {
                    const p = user.permissions[k];
                    if (p.view) {
                        allowedPagesCount++;
                        canViewAny = true;
                    }
                    if (p.add) canAddAny = true;
                    if (p.edit) canEditAny = true;
                    if (p.delete) canDeleteAny = true;
                });
            }
            
            const pagesBadge = `<span class="status-badge" style="padding:2px 8px; border-radius:12px; font-size:10.5px; font-weight:600; background:rgba(99,102,241,0.08); color:var(--primary); display:block; margin-top:4px; text-align:center;"><i class="fa-solid fa-folder-open" style="margin-left:4px;"></i>تصفح: ${allowedPagesCount}/${totalPagesCount}</span>`;
            
            let actionsBadgeHtml = `<div style="display:flex; gap:6px; align-items:center; margin-top:6px;">`;
            actionsBadgeHtml += `<span title="عرض البيانات (في بعض الصفحات)" style="color:${canViewAny ? 'var(--success)' : 'var(--text-muted)'}; opacity:${canViewAny ? '1' : '0.3'}; font-size:11px;"><i class="fa-solid fa-eye"></i></span>`;
            actionsBadgeHtml += `<span title="إضافة وحفظ (في بعض الصفحات)" style="color:${canAddAny ? 'var(--primary)' : 'var(--text-muted)'}; opacity:${canAddAny ? '1' : '0.3'}; font-size:11px;"><i class="fa-solid fa-circle-plus"></i></span>`;
            actionsBadgeHtml += `<span title="تعديل البيانات (في بعض الصفحات)" style="color:${canEditAny ? 'var(--warning)' : 'var(--text-muted)'}; opacity:${canEditAny ? '1' : '0.3'}; font-size:11px;"><i class="fa-solid fa-user-pen"></i></span>`;
            actionsBadgeHtml += `<span title="حذف البيانات (في بعض الصفحات)" style="color:${canDeleteAny ? 'var(--danger)' : 'var(--text-muted)'}; opacity:${canDeleteAny ? '1' : '0.3'}; font-size:11px;"><i class="fa-solid fa-trash-can"></i></span>`;
            actionsBadgeHtml += `</div>`;
            
            const roleBadge = `
                <div style="display:flex; flex-direction:column; align-items:flex-start;">
                    <span class="status-badge" style="padding:4px 10px; border-radius:12px; font-size:11px; font-weight:700; background:${badgeColor}; color:${badgeTextColor}; display:inline-flex; align-items:center;">
                        <i class="fa-solid ${badgeIcon}" style="margin-left:4px;"></i>${roleText}
                    </span>
                    ${pagesBadge}
                    ${actionsBadgeHtml}
                </div>
            `;
            
            let statusBadge = "";
            if (user.status === "active") {
                statusBadge = `<span class="status-badge" style="padding:4px 10px; border-radius:12px; font-size:11px; font-weight:700; background:rgba(16,185,129,0.15); color:#10b981;"><i class="fa-solid fa-circle-check" style="margin-left:4px;"></i>نشط</span>`;
            } else {
                statusBadge = `<span class="status-badge" style="padding:4px 10px; border-radius:12px; font-size:11px; font-weight:700; background:rgba(239,68,68,0.15); color:#ef4444;"><i class="fa-solid fa-circle-xmark" style="margin-left:4px;"></i>موقوف</span>`;
            }
            
            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td class="serial-col">#${serial}</td>
                <td class="name-col" style="font-weight:700;">${escapeHTML(user.name)}</td>
                <td><code>${escapeHTML(user.username)}</code></td>
                <td>${roleBadge}</td>
                <td style="text-align: center;">${statusBadge}</td>
                <td>
                    <div class="actions-cell" style="justify-content: center;">
                        <button class="btn-icon btn-icon-edit" onclick="openEditUserModal('${user.id}')" title="تعديل الحساب">
                            <i class="fa-solid fa-user-pen"></i>
                        </button>
                        <button class="btn-icon btn-icon-delete" onclick="triggerDeleteUser('${user.id}')" title="حذف الحساب">
                            <i class="fa-solid fa-trash-can"></i>
                        </button>
                    </div>
                </td>
            `;
            dom.usersTbody.appendChild(tr);
        });
    }
    
    // Pagination rendering
    const totalEntries = state.filteredUsers.length;
    const startEntry = startIdx + 1;
    const endEntry = Math.min(endIdx, totalEntries);
    dom.paginationInfoText.textContent = `يعرض ${startEntry} إلى ${endEntry} من أصل ${totalEntries} مستخدم`;
    
    renderPagination(totalEntries);
}

function renderPagination(totalEntries) {
    dom.paginationControls.innerHTML = "";
    const totalPages = Math.ceil(totalEntries / state.pageSize);
    if (totalPages <= 1) return;
    
    // Prev Button
    const prevBtn = document.createElement("button");
    prevBtn.className = "page-btn";
    prevBtn.disabled = state.currentPage === 1;
    prevBtn.innerHTML = '<i class="fa-solid fa-angle-right"></i>';
    prevBtn.addEventListener("click", () => {
        if (state.currentPage > 1) {
            state.currentPage--;
            renderUsers();
        }
    });
    dom.paginationControls.appendChild(prevBtn);
    
    // Numbers
    for (let i = 1; i <= totalPages; i++) {
        const btn = document.createElement("button");
        btn.className = `page-btn ${state.currentPage === i ? 'active' : ''}`;
        btn.textContent = i;
        btn.addEventListener("click", () => {
            state.currentPage = i;
            renderUsers();
        });
        dom.paginationControls.appendChild(btn);
    }
    
    // Next Button
    const nextBtn = document.createElement("button");
    nextBtn.className = "page-btn";
    nextBtn.disabled = state.currentPage === totalPages;
    nextBtn.innerHTML = '<i class="fa-solid fa-angle-left"></i>';
    nextBtn.addEventListener("click", () => {
        if (state.currentPage < totalPages) {
            state.currentPage++;
            renderUsers();
        }
    });
    dom.paginationControls.appendChild(nextBtn);
}

// -------------------------------------------------------------
// 8. Modals Logic and Add/Edit Actions
// -------------------------------------------------------------
function openAddUserModal() {
    clearValidationErrors();
    state.currentUserIdToEdit = null;
    
    dom.modalTitle.textContent = "إضافة مستخدم جديد";
    dom.userIdInput.value = "";
    dom.userFullnameInput.value = "";
    dom.userUsernameInput.value = "";
    dom.userPasswordInput.value = "";
    dom.userStatusInput.value = "active";
    
    // Set standard preset permissions mapping
    setPermissionCheckboxes({
        index: { view: true, add: false, edit: false, delete: false },
        gatherers: { view: true, add: true, edit: true, delete: false },
        customers: { view: true, add: true, edit: true, delete: false },
        expenses: { view: true, add: true, edit: true, delete: false },
        safes: { view: true, add: true, edit: true, delete: false },
        materials: { view: true, add: true, edit: true, delete: false },
        materials_report: { view: true, add: false, edit: false, delete: false },
        gatherers_report: { view: true, add: false, edit: false, delete: false },
        forms: { view: true, add: true, edit: true, delete: false },
        debts: { view: true, add: true, edit: true, delete: false },
        users: { view: false, add: false, edit: false, delete: false },
        settings: { view: false, add: false, edit: false, delete: false }
    });
    
    // Requirements adjustments
    dom.passwordReq.style.display = "inline";
    dom.userPasswordInput.required = true;
    dom.passwordHelpText.style.display = "none";
    
    dom.userModal.classList.add("open");
    dom.userFullnameInput.focus();
}

window.openEditUserModal = function(id) {
    clearValidationErrors();
    const user = state.users.find(u => u.id === id);
    if (!user) return;
    
    state.currentUserIdToEdit = id;
    dom.modalTitle.textContent = "تعديل حساب المستخدم";
    dom.userIdInput.value = user.id;
    dom.userFullnameInput.value = user.name;
    dom.userUsernameInput.value = user.username;
    dom.userPasswordInput.value = ""; // Empty password during edit
    dom.userStatusInput.value = user.status;
    
    // Fill checkboxes in matrix table
    setPermissionCheckboxes(user.permissions);
    
    // Requirements adjustments
    dom.passwordReq.style.display = "none";
    dom.userPasswordInput.required = false;
    dom.passwordHelpText.style.display = "block";
    
    dom.userModal.classList.add("open");
    dom.userFullnameInput.focus();
};

function closeUserModal() {
    dom.userModal.classList.remove("open");
}

function clearValidationErrors() {
    document.querySelectorAll(".form-group").forEach(g => {
        g.classList.remove("has-error");
    });
}

// Form Submission Actions
function handleFormSubmit(e) {
    e.preventDefault();
    clearValidationErrors();
    
    const fullname = dom.userFullnameInput.value.trim();
    const username = dom.userUsernameInput.value.trim().toLowerCase();
    const password = dom.userPasswordInput.value;
    const status = dom.userStatusInput.value;
    const permissions = getPermissionFromCheckboxes();
    
    let isValid = true;
    
    // Validate Full name
    if (!fullname || fullname.length < 3) {
        document.getElementById("fullname-error").parentNode.classList.add("has-error");
        isValid = false;
    }
    
    // Validate Username
    const usernameRegex = /^[a-zA-Z0-9_\-\.]{3,30}$/;
    if (!username || !usernameRegex.test(username)) {
        document.getElementById("username-error").parentNode.classList.add("has-error");
        isValid = false;
    }
    
    // Validate Password
    const isNew = !state.currentUserIdToEdit;
    if (isNew) {
        if (!password || password.length < 4) {
            document.getElementById("password-error").parentNode.classList.add("has-error");
            isValid = false;
        }
    } else {
        if (password && password.length < 4) {
            document.getElementById("password-error").parentNode.classList.add("has-error");
            isValid = false;
        }
    }
    
    if (!isValid) {
        showToast("يرجى تصحيح الأخطاء أولاً قبل الحفظ", "danger");
        return;
    }
    
    const payload = {
        id: state.currentUserIdToEdit || "",
        name: fullname,
        username: username,
        password: password,
        status: status,
        permissions: permissions
    };

    fetch('api/users.php?action=save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || "تم حفظ حساب الموظف بنجاح");
            
            // If the updated user is the currently logged in user, refresh their session dynamically in auth
            const currentLoggedIn = JSON.parse(localStorage.getItem("dashboard_current_user") || "{}");
            if (state.currentUserIdToEdit === currentLoggedIn.id || username === currentLoggedIn.username) {
                // Background update local session info
                fetch('api/auth.php?action=check_session')
                    .then(r => r.json())
                    .then(rdata => {
                        if (rdata.status === 'success') {
                            localStorage.setItem("dashboard_current_user", JSON.stringify(rdata.user));
                            if (window.updateSidebarProfile) window.updateSidebarProfile(rdata.user);
                            if (window.applyGranularPermissions) window.applyGranularPermissions(rdata.user);
                        }
                    });
            }
            
            loadUsers();
            closeUserModal();
        } else {
            showToast(res.message || "فشل حفظ الحساب", "danger");
        }
    })
    .catch(err => {
        console.error("Save user failed:", err);
        showToast("حدث خطأ غير متوقع أثناء الاتصال بالخادم", "danger");
    });
}

// -------------------------------------------------------------
// 9. Delete User Safeguards
// -------------------------------------------------------------
window.triggerDeleteUser = function(id) {
    const user = state.users.find(u => u.id === id);
    if (!user) return;
    
    // Check 1: Cannot delete logged in account
    const currentLoggedIn = JSON.parse(localStorage.getItem("dashboard_current_user") || "{}");
    if (id === currentLoggedIn.id || user.username === currentLoggedIn.username) {
        showToast("خطأ: لا يمكنك حذف حسابك الشخصي الذي تستخدمه حالياً!", "danger");
        return;
    }
    
    // Check 2: Cannot delete admin
    if (user.username === 'admin') {
        showToast("خطأ: لا يمكن حذف حساب المدير العام الرئيسي للنظام!", "danger");
        return;
    }
    
    state.currentUserIdToDelete = id;
    dom.deleteItemName.textContent = user.name;
    dom.deleteConfirmModal.classList.add("open");
};

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

function executeDeleteUser() {
    if (!state.currentUserIdToDelete) return;
    
    const payload = {
        id: state.currentUserIdToDelete
    };

    fetch('api/users.php?action=delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            showToast(res.message || "تم حذف الحساب بنجاح");
            loadUsers();
        } else {
            showToast(res.message || "فشل حذف الحساب", "danger");
        }
        closeDeleteModal();
    })
    .catch(err => {
        console.error("Delete user failed:", err);
        showToast("حدث خطأ أثناء محاولة حذف الحساب", "danger");
        closeDeleteModal();
    });
}

// -------------------------------------------------------------
// 10. Toast 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);
}

// -------------------------------------------------------------
// 11. Search Logic
// -------------------------------------------------------------
window.doSearchUsers = function() {
    state.searchQuery = dom.searchInput.value;
    applyFilters();
};

window.clearSearchUsers = function() {
    dom.searchInput.value = "";
    state.searchQuery = "";
    applyFilters();
};

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

function toggleModalPassword() {
    if (dom.userPasswordInput.type === "password") {
        dom.userPasswordInput.type = "text";
        dom.modalPasswordToggleIcon.classList.remove("fa-eye");
        dom.modalPasswordToggleIcon.classList.add("fa-eye-slash");
    } else {
        dom.userPasswordInput.type = "password";
        dom.modalPasswordToggleIcon.classList.remove("fa-eye-slash");
        dom.modalPasswordToggleIcon.classList.add("fa-eye");
    }
}

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

// Helper to determine role label dynamically (for UI stats and badges)
function getUserRoleLabel(user) {
    if (!user || !user.permissions) return "مستخدم";
    
    const p = user.permissions;
    
    // Admin check
    const hasAdminUsers = p.users && p.users.view && p.users.delete && p.users.edit && p.users.add;
    const hasAdminSettings = p.settings && p.settings.view && p.settings.edit;
    
    if (hasAdminUsers && hasAdminSettings) {
        return "مسؤول النظام";
    }
    
    // Accountant check
    const hasAccountantForms = p.forms && p.forms.add && p.forms.edit;
    const hasAccountantExpenses = p.expenses && p.expenses.add && p.expenses.edit;
    
    if (hasAccountantForms || hasAccountantExpenses) {
        return "محاسب";
    }
    
    // Viewer check
    const allPages = Object.keys(p);
    let canModifyAny = false;
    allPages.forEach(k => {
        if (p[k].add || p[k].edit || p[k].delete) {
            canModifyAny = true;
        }
    });
    
    if (!canModifyAny) {
        return "مشاهد";
    }
    
    return "مستخدم مخصص";
}

// -------------------------------------------------------------
// 13. Setup Event Listeners
// -------------------------------------------------------------
function setupEventListeners() {
    // Theme
    dom.themeToggle.addEventListener("click", toggleTheme);

    // Modal Triggers
    dom.openAddModalBtn.addEventListener("click", openAddUserModal);
    dom.emptyStateAddBtn.addEventListener("click", openAddUserModal);
    dom.closeModalBtn.addEventListener("click", closeUserModal);
    dom.cancelModalBtn.addEventListener("click", closeUserModal);
    dom.btnToggleModalPassword.addEventListener("click", toggleModalPassword);
    
    // Form Submit
    dom.userForm.addEventListener("submit", handleFormSubmit);

    // Delete Triggers
    dom.cancelDeleteBtn.addEventListener("click", closeDeleteModal);
    dom.confirmDeleteBtn.addEventListener("click", executeDeleteUser);

    // Page sizing entries count
    dom.entriesCount.addEventListener("change", (e) => {
        state.pageSize = parseInt(e.target.value);
        state.currentPage = 1;
        renderUsers();
    });

    // Close Modals on overlay click
    window.addEventListener("click", (e) => {
        if (e.target === dom.userModal) closeUserModal();
        if (e.target === dom.deleteConfirmModal) closeDeleteModal();
    });

    // Close Modals on Escape key
    window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            closeUserModal();
            closeDeleteModal();
        }
    });

    // Keyboard support for search
    dom.searchInput.addEventListener("input", (e) => {
        if (e.target.value === "") {
            clearSearchUsers();
        }
    });
    dom.searchInput.addEventListener("keydown", (e) => {
        if (e.key === "Enter") {
            doSearchUsers();
        }
    });
}
