<?php

require_once __DIR__ . '/permissions.php';
require_once __DIR__ . '/../config/response.php';

/**
 * Require a single permission
 */
function requirePermission(string $permission): void
{
    $user = $GLOBALS['_auth_user'] ?? null;

    if (!$user || empty($user['permissions'])) {
        jsonResponse(false, 'Unauthorized', [], 401);
    }

    if (!in_array($permission, $user['permissions'], true)) {
        jsonResponse(false, 'Forbidden', [
            'required_permission' => $permission
        ], 403);
    }
}

/**
 * Require ANY permission (OR)
 */
function requireAnyPermission(array $permissions): void
{
    $user = $GLOBALS['_auth_user'] ?? null;

    if (!$user) {
        jsonResponse(false, 'Unauthorized', [], 401);
    }

    foreach ($permissions as $permission) {
        if (in_array($permission, $user['permissions'], true)) {
            return;
        }
    }

    jsonResponse(false, 'Forbidden', [
        'required_any' => $permissions
    ], 403);
}

/**
 * Require ALL permissions (AND)
 */
function requireAllPermissions(array $permissions): void
{
    $user = $GLOBALS['_auth_user'] ?? null;

    if (!$user) {
        jsonResponse(false, 'Unauthorized', [], 401);
    }

    foreach ($permissions as $permission) {
        if (!in_array($permission, $user['permissions'], true)) {
            jsonResponse(false, 'Forbidden', [
                'required_all' => $permissions
            ], 403);
        }
    }
}
