<?php

// --- Helper Functions (Extracted from header.php) ---

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function isSuperAdmin() {
    return isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin'] == 1;
}

function isAdmin() {
    if (isSuperAdmin()) return true;
    if (isset($_SESSION['user_role']) && strtolower($_SESSION['user_role']) === 'admin') return true;
    if (isset($_SESSION['role']) && strtolower($_SESSION['role']) === 'admin') return true;
    return false;
}

function redirect($path) {
    if (!headers_sent()) {
        header("Location: $path");
    } else {
        echo "<script>window.location.href='$path';</script>";
    }
    exit;
}

// Permission helpers
function canView($page = null) {
    if (isAdmin()) return true;
    if ($page) {
        return $_SESSION['permissions'][$page]['view'] ?? false;
    }
    return $_SESSION['can_view'] ?? false;
}

function canAdd($page = null) {
    if (isAdmin()) return true;
    if ($page) {
        return $_SESSION['permissions'][$page]['add'] ?? false;
    }
    return $_SESSION['can_add'] ?? false;
}

function canEdit($page = null) {
    if (isAdmin()) return true;
    if ($page) {
        return $_SESSION['permissions'][$page]['edit'] ?? false;
    }
    return $_SESSION['can_edit'] ?? false;
}

function canDelete($page = null) {
    if (isAdmin()) return true;
    if ($page) {
        return $_SESSION['permissions'][$page]['delete'] ?? false;
    }
    return $_SESSION['can_delete'] ?? false;
}

function canViewInternal() {
    return canView('internal');
}

// Added for auditing display
function getAuditUserName($user_id) {
    if (!$user_id) return '-';
    static $userCache = null;
    if ($userCache === null) {
        $userCache = [];
        try {
            $stmt = db()->query("SELECT id, username, full_name FROM users");
            while ($u = $stmt->fetch()) {
                $userCache[$u['id']] = $u['full_name'] ?: $u['username'];
            }
        } catch(Exception $e) {}
    }
    return $userCache[$user_id] ?? '-';
}
