<?php
/**
 * Sub-Admin Action Enforcement
 * Use these functions in sub-admin page handlers to enforce permission hierarchy
 */

require_once __DIR__ . '/permission_helper.php';

class SubAdminActions {
    
    /**
     * Check if sub-admin can perform an action and return response
     * @param string $feature Feature key
     * @param string $action Action type: 'view', 'create', 'edit', 'delete'
     * @param array $permissions From $_SESSION['subadmin_permissions']
     * @return array ['allowed' => bool, 'message' => string]
     */
    public static function checkAction($feature, $action, $permissions) {
        $canPerform = PermissionHelper::can($feature, $action, $permissions);
        
        if (!$canPerform) {
            $level = PermissionHelper::getLevel($feature, $permissions);
            $message = "Access denied. Your permission level for this feature is: " . ucfirst($level);
            
            if ($action === 'delete') {
                $message = "Delete operation not allowed. Only Administrators can delete content.";
            } elseif ($action === 'edit') {
                $message = "Edit operation not allowed. Your current permission level does not support editing.";
            } elseif ($action === 'create') {
                $message = "Create operation not allowed. Your current permission level does not support creating.";
            }
            
            return ['allowed' => false, 'message' => $message];
        }
        
        return ['allowed' => true, 'message' => 'Action authorized'];
    }
    
    /**
     * Enforce permission check in JSON API response
     * @param string $feature Feature key
     * @param string $action Action type
     * @param array $permissions From $_SESSION
     */
    public static function enforceSilent($feature, $action, $permissions) {
        $check = self::checkAction($feature, $action, $permissions);
        if (!$check['allowed']) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => $check['message']]);
            exit;
        }
    }
    
    /**
     * Get action capabilities for current permission level
     * @param string $feature
     * @param array $permissions
     * @return array ['can_view', 'can_create', 'can_edit', 'can_delete']
     */
    public static function getCapabilities($feature, $permissions) {
        return [
            'can_view' => PermissionHelper::can($feature, 'view', $permissions),
            'can_create' => PermissionHelper::can($feature, 'create', $permissions),
            'can_edit' => PermissionHelper::can($feature, 'edit', $permissions),
            'can_delete' => PermissionHelper::can($feature, 'delete', $permissions),
            'level' => PermissionHelper::getLevel($feature, $permissions)
        ];
    }
}
?>
