// Central Authentication, Authorization & Page-Specific Permissions System Script

// Helper to determine role label dynamically
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 "مستخدم مخصص";
}

// Dynamically updates UI elements matching current user profile
function updateSidebarProfile(currentUser) {
    if (!currentUser) return;
    const nameEl = document.querySelector(".sidebar .user-name");
    const roleEl = document.querySelector(".sidebar .user-role");
    const avatarEl = document.querySelector(".sidebar .avatar");

    if (nameEl) nameEl.textContent = currentUser.name || currentUser.username;
    if (roleEl) {
        roleEl.textContent = getUserRoleLabel(currentUser);
    }
    if (avatarEl && currentUser.name) {
        avatarEl.textContent = currentUser.name.trim().charAt(0).toUpperCase();
    }
}

// Helper to map pathname to permission page key
function getPageKey(pathname) {
    if (!pathname) return null;
    const file = pathname.substring(pathname.lastIndexOf('/') + 1) || 'index.php';
    if (file.indexOf("index.php") !== -1) return "index";
    if (file.indexOf("gatherers.php") !== -1) return "gatherers";
    if (file.indexOf("customers.php") !== -1) return "customers";
    if (file.indexOf("safes.php") !== -1) return "safes";
    if (file.indexOf("materials.php") !== -1) return "materials";
    if (file.indexOf("materials_report.php") !== -1) return "materials_report";
    if (file.indexOf("gatherers_report.php") !== -1) return "gatherers_report";
    if (file.indexOf("settlements.php") !== -1) return "settlements";
    if (file.indexOf("calibration.php") !== -1) return "calibration";
    if (file.indexOf("pricing.php") !== -1) return "pricing";
    if (file.indexOf("forms.php") !== -1) return "forms";
    if (file.indexOf("debts.php") !== -1) return "debts";
    if (file.indexOf("activity_logs.php") !== -1) return "activity_logs";
    if (file.indexOf("users.php") !== -1) return "users";
    if (file.indexOf("settings.php") !== -1) return "settings";
    if (file.indexOf("order.php") !== -1) return "order";
    return null;
}

// Show local toast helper
function showAuthToast(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);
}

// Enforces Granular Action Permissions dynamically in the DOM
function applyGranularPermissions(currentUser) {
    if (!currentUser || !currentUser.permissions) return;

    const path = window.location.pathname;
    const pageKey = getPageKey(path);
    if (!pageKey || !currentUser.permissions[pageKey]) return;

    const pageActions = currentUser.permissions[pageKey];

    // 1. Check VIEW permission
    if (pageActions.view === false) {
        const style = document.createElement("style");
        style.innerHTML = `
            .lock-hidden { display: none !important; }
            .permission-lock-container {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 60px 24px;
                text-align: center;
                background: var(--bg-card);
                border-radius: var(--radius-lg);
                border: 1.5px dashed var(--border-color);
                margin: 30px auto;
                max-width: 600px;
                box-shadow: var(--shadow-sm);
            }
            .lock-icon-circle {
                width: 72px;
                height: 72px;
                border-radius: 50%;
                background: rgba(239, 68, 68, 0.1);
                color: var(--danger);
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 32px;
                margin-bottom: 20px;
                box-shadow: 0 4px 12px rgba(239,68,68,0.15);
            }
            .lock-title {
                font-family: var(--font-family);
                font-size: 18px;
                color: var(--text-primary);
                margin-bottom: 10px;
                font-weight: 700;
            }
            .lock-desc {
                font-family: var(--font-family);
                font-size: 13.5px;
                color: var(--text-secondary);
                line-height: 1.6;
                margin: 0;
            }
        `;
        document.head.appendChild(style);

        const targets = document.querySelectorAll(".table-container-card, .stats-grid, .data-table, .table-responsive, .filter-bar, .card, .report-section, .safes-split-grid, .debtors-split-grid, .digital-cards-section");
        targets.forEach(t => t.classList.add("lock-hidden"));

        const bodyContainer = document.querySelector(".dashboard-body") || document.querySelector(".main-content");
        if (bodyContainer) {
            if (!document.querySelector(".permission-lock-container")) {
                const lockDiv = document.createElement("div");
                lockDiv.className = "permission-lock-container";
                lockDiv.innerHTML = `
                    <div class="lock-icon-circle">
                        <i class="fa-solid fa-lock"></i>
                    </div>
                    <h3 class="lock-title">عرض البيانات مقيد 🔒</h3>
                    <p class="lock-desc">حسابك لا يمتلك الصلاحية الكافية لعرض العناصر والبيانات في هذه الصفحة. يرجى مراجعة مسؤول النظام لمنحك الصلاحيات المطلوبة.</p>
                `;
                bodyContainer.appendChild(lockDiv);
            }
        }

        document.querySelectorAll("form").forEach(form => {
            form.addEventListener("submit", (e) => {
                e.preventDefault();
                showAuthToast("عذراً، لا يمكنك حفظ أو تعديل البيانات لأنك لا تملك صلاحية العرض في هذه الصفحة.", "warning");
            });
        });
        return; // stop execution as view is locked
    }

    // Helper to hide elements matching selectors
    const hideElements = (selectors) => {
        selectors.forEach(selector => {
            document.querySelectorAll(selector).forEach(el => {
                el.style.setProperty("display", "none", "important");
            });
        });
    };

    // 2. Enforce ADD restriction
    if (pageActions.add === false) {
        const addSelectors = [
            "#open-add-modal-btn",
            "#open-transaction-modal-btn",
            "#empty-state-add-btn",
            "#add-purchase-item-btn",
            "#empty-state-view button",
            "#empty-state-transactions button",
            "button.btn-primary:not(#save-btn):not(#save-settings-btn)"
        ];
        hideElements(addSelectors);
    }

    // 3. Enforce EDIT restriction
    if (pageActions.edit === false) {
        const editSelectors = [
            ".btn-icon-edit",
            "#btn-save",
            "#save-btn",
            "#save-safe-btn",
            "#save-tx-btn",
            "#save-debtor-btn",
            ".row-action-btn",
            ".card-action-btn",
            "#btn-backup",
            "#btn-trigger-restore",
            "#save-settings-btn"
        ];
        hideElements(editSelectors);

        // Disable editing forms and inputs (except search inputs and page size entries)
        document.querySelectorAll("input, select, textarea").forEach(el => {
            if (el.id !== "search-input" &&
                el.id !== "entries-count" &&
                el.id !== "modal-search-input" &&
                !el.classList.contains("panel-search-input") &&
                el.type !== "search" &&
                !el.classList.contains("perm-matrix-checkbox") &&
                el.getAttribute("type") !== "checkbox") {
                el.disabled = true;
                el.style.opacity = "0.75";
            }
        });
    }

    // 4. Enforce DELETE restriction
    if (pageActions.delete === false) {
        const deleteSelectors = [
            ".btn-icon-delete",
            "#btn-factory-reset"
        ];
        hideElements(deleteSelectors);
    }

    // 5. Hide Actions Column if both EDIT and DELETE are restricted
    if (pageActions.edit === false && pageActions.delete === false) {
        const tables = document.querySelectorAll(".data-table");
        tables.forEach(table => {
            let actionColIndex = -1;
            const headers = table.querySelectorAll("thead th");
            headers.forEach((th, idx) => {
                if (th.textContent.includes("الإجراءات") || th.textContent.includes("إجراءات")) {
                    actionColIndex = idx;
                    th.style.setProperty("display", "none", "important");
                }
            });
            if (actionColIndex !== -1) {
                const hideCells = () => {
                    table.querySelectorAll("tbody tr").forEach(tr => {
                        const cells = tr.querySelectorAll("td");
                        if (cells[actionColIndex]) {
                            cells[actionColIndex].style.setProperty("display", "none", "important");
                        }
                    });
                };
                hideCells();

                // Monitor changes to table rows dynamically
                const observer = new MutationObserver(hideCells);
                observer.observe(table.querySelector("tbody") || table, { childList: true, subtree: true });
            }
        });
    }

    // 6. Block form submit requests programmatically
    document.querySelectorAll("form").forEach(form => {
        form.addEventListener("submit", (e) => {
            const isEdit = document.getElementById("user-id")?.value ||
                document.getElementById("safe-id")?.value ||
                document.getElementById("gatherer-id")?.value ||
                document.getElementById("material-id")?.value ||
                document.getElementById("tx-id")?.value ||
                document.getElementById("debtor-id")?.value;

            if (isEdit && pageActions.edit === false) {
                e.preventDefault();
                showAuthToast("عذراً، حسابك لا يملك صلاحية تعديل البيانات في هذه الصفحة.", "warning");
            } else if (!isEdit && pageActions.add === false) {
                e.preventDefault();
                showAuthToast("عذراً، حسابك لا يملك صلاحية إضافة بيانات جديدة في هذه الصفحة.", "warning");
            }
        });
    });
}

(function () {
    const loggedIn = localStorage.getItem("dashboard_logged_in") === "true";
    const path = window.location.pathname;
    const isLoginPage = path.indexOf("login.php") !== -1;

    // 1. Enforce local authentication redirect immediately
    if (!loggedIn && !isLoginPage) {
        window.location.href = "login.php";
        return;
    } else if (loggedIn && isLoginPage) {
        // Verify server session before redirecting away from login page to prevent infinite loops
        fetch('api/auth.php?action=check_session')
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success' && res.user) {
                    window.location.href = "index.php";
                } else {
                    localStorage.removeItem("dashboard_logged_in");
                    localStorage.removeItem("dashboard_current_user");
                }
            })
            .catch(() => {
                localStorage.removeItem("dashboard_logged_in");
                localStorage.removeItem("dashboard_current_user");
            });
        return;
    }

    // 2. Perform server check if logged in
    if (loggedIn) {
        const currentUserStr = localStorage.getItem("dashboard_current_user");
        let localUser = null;
        if (currentUserStr) {
            try {
                localUser = JSON.parse(currentUserStr);
            } catch (e) { }
        }

        // Fetch fresh state from the server
        fetch('api/auth.php?action=check_session')
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success' && res.user) {
                    const freshUser = res.user;
                    localStorage.setItem("dashboard_current_user", JSON.stringify(freshUser));

                    // Fetch latest settings from database to sync localStorage settings
                    fetch('api/settings.php?action=get')
                        .then(sr => sr.json())
                        .then(sdata => {
                            if (sdata.status === 'success' && sdata.settings) {
                                localStorage.setItem("dashboard_settings", JSON.stringify(sdata.settings));
                            }
                        })
                        .catch(() => { });

                    // Verify authorization for current page
                    const pageKey = getPageKey(path);
                    if (pageKey && freshUser.permissions && freshUser.permissions[pageKey]) {
                        if (freshUser.permissions[pageKey].view === false) {
                            // Redirect to home or first allowed page (preventing self-redirect loop)
                            let redirectPage = "";
                            const perms = freshUser.permissions;
                            if (pageKey !== 'index' && perms.index && perms.index.view !== false) {
                                redirectPage = "index.php";
                            } else {
                                const allowedPageKey = Object.keys(perms).find(k => k !== pageKey && perms[k] && perms[k].view === true);
                                redirectPage = allowedPageKey ? allowedPageKey + ".php" : "";
                            }

                            const currentPageName = path.substring(path.lastIndexOf('/') + 1) || 'index.php';
                            if (redirectPage && redirectPage !== currentPageName) {
                                window.location.href = redirectPage + "?error=unauthorized";
                            } else if (!redirectPage) {
                                handleSessionDeath("no_pages");
                            }
                            return;
                        }
                    }

                    // Sync UI
                    updateSidebarProfile(freshUser);
                    applyGranularPermissions(freshUser);
                } else {
                    handleSessionDeath(res.message === 'تم إيقاف حسابك من قبل الإدارة.' ? 'suspended' : 'session_expired');
                }
            })
            .catch(err => {
                console.error("Auth check failed:", err);
                // Prevent unauthorized access by forcing redirect on session check failure
                handleSessionDeath("connection_error");
            });

        // Instant local view permission lock before fetch completes to avoid page flash
        if (localUser && !isLoginPage) {
            const pageKey = getPageKey(path);
            const currentPageName = path.substring(path.lastIndexOf('/') + 1) || 'index.php';
            if (pageKey && pageKey !== 'index' && localUser.permissions && localUser.permissions[pageKey]) {
                if (localUser.permissions[pageKey].view === false) {
                    window.location.href = "index.php?error=unauthorized";
                }
            }
        }
    }

    function handleSessionDeath(reason) {
        localStorage.removeItem("dashboard_logged_in");
        localStorage.removeItem("dashboard_current_user");
        window.location.href = "login.php?error=" + reason;
    }
})();

// DOMContentLoaded Hooks for Sidebar Profile and Read-only views
document.addEventListener("DOMContentLoaded", () => {
    // 1. Check URL parameters for authorization errors
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has("error") && urlParams.get("error") === "unauthorized") {
        showAuthToast("عذراً، لا تمتلك صلاحية كافية للوصول إلى هذه الصفحة.", "danger");
        window.history.replaceState({}, document.title, window.location.pathname);
    }
    if (urlParams.has("error") && urlParams.get("error") === "no_pages") {
        showAuthToast("عذراً، حسابك لا يملك صلاحية الوصول لأي صفحة في النظام.", "danger");
        window.history.replaceState({}, document.title, window.location.pathname);
    }
    if (urlParams.has("error") && urlParams.get("error") === "suspended") {
        showAuthToast("عذراً، تم إيقاف حساب الموظف هذا من قبل الإدارة.", "danger");
        window.history.replaceState({}, document.title, window.location.pathname);
    }
    if (urlParams.has("error") && urlParams.get("error") === "session_expired") {
        showAuthToast("انتهت جلسة العمل الخاصة بك، يرجى تسجيل الدخول مجدداً.", "info");
        window.history.replaceState({}, document.title, window.location.pathname);
    }
    if (urlParams.has("error") && urlParams.get("error") === "connection_error") {
        showAuthToast("فشل الاتصال بالخادم للتحقق من الصلاحيات. يرجى تسجيل الدخول مجدداً.", "danger");
        window.history.replaceState({}, document.title, window.location.pathname);
    }

    const currentUserStr = localStorage.getItem("dashboard_current_user");
    let currentUser = null;
    if (currentUserStr) {
        try {
            currentUser = JSON.parse(currentUserStr);
        } catch (e) { }
    }

    if (currentUser) {
        updateSidebarProfile(currentUser);
        applyGranularPermissions(currentUser);
    }

    // 2. Bind Logout Action
    const logoutBtn = document.getElementById("btn-logout");
    if (logoutBtn) {
        logoutBtn.addEventListener("click", (e) => {
            e.preventDefault();
            fetch('api/auth.php?action=logout', { method: 'POST' })
                .finally(() => {
                    localStorage.removeItem("dashboard_logged_in");
                    localStorage.removeItem("dashboard_current_user");
                    window.location.href = "login.php";
                });
        });
    }
});

// Global function to refresh system data from server and clear browser cache
window.refreshSystemAndClearCache = function(btnEl) {
    const iconEl = document.getElementById("refresh-cache-icon") || (btnEl ? btnEl.querySelector("i") : null);
    if (iconEl) iconEl.classList.add("fa-spin");

    if (typeof showAuthToast === "function") {
        showAuthToast("جاري تحديث بيانات السيرفر وتفريغ الذاكرة المؤقتة...", "info");
    }

    // 1. Clear Browser Cache Storage (Cache API)
    if ('caches' in window) {
        caches.keys().then(names => {
            names.forEach(name => caches.delete(name));
        }).catch(() => {});
    }

    // 2. Clear Session Storage
    try {
        sessionStorage.clear();
    } catch (e) {}

    // 3. Request fresh state update from server & hard reload
    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .catch(() => {})
        .finally(() => {
            setTimeout(() => {
                const cleanUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
                window.location.href = cleanUrl + '?_v=' + Date.now();
            }, 600);
        });
};
