<?php
/**
 * Permission Hierarchy System
 * 
 * Permission Levels:
 * - 'none'           = No access
 * - 'viewer'         = View only (READ)
 * - 'editor'         = View, Create, Edit (READ, CREATE, UPDATE - NO DELETE)
 * - 'administrator'  = Full access (READ, CREATE, UPDATE, DELETE)
 */

class PermissionHelper {
    
    /**
     * Check if a sub-admin has permission to perform an action
     * 
     * @param string $feature The feature key (e.g., 'manage_products')
     * @param string $action The action: 'view', 'create', 'edit', 'delete'
     * @param array $permissions The sub-admin's permissions array
     * @return bool True if the sub-admin can perform the action
     */
    public static function can($feature, $action, $permissions) {
        // No permissions set for this feature
        if (!isset($permissions[$feature]) || $permissions[$feature] === 'none') {
            return false;
        }
        
        $level = $permissions[$feature];
        
        // Define what each level can do
        $levelAccess = [
            'viewer' => ['view'],
            'editor' => ['view', 'create', 'edit'],
            'administrator' => ['view', 'create', 'edit', 'delete']
        ];
        
        // Check if this level can perform the action
        if (!isset($levelAccess[$level])) {
            return false;
        }
        
        return in_array($action, $levelAccess[$level]);
    }
    
    /**
     * Check if sub-admin can perform any action on a feature
     * @param string $feature
     * @param array $permissions
     * @return bool
     */
    public static function hasAccess($feature, $permissions) {
        return isset($permissions[$feature]) && $permissions[$feature] !== 'none';
    }
    
    /**
     * Get the permission level for a feature
     * @param string $feature
     * @param array $permissions
     * @return string The level: 'none', 'viewer', 'editor', 'administrator'
     */
    public static function getLevel($feature, $permissions) {
        return $permissions[$feature] ?? 'none';
    }
    
    /**
     * Get all accessible features with their levels
     * @param array $permissions
     * @return array Features with level > 'none'
     */
    public static function getAccessibleFeatures($permissions) {
        $accessible = [];
        foreach ($permissions as $feature => $level) {
            if ($level !== 'none') {
                $accessible[$feature] = $level;
            }
        }
        return $accessible;
    }
}
?>
