<?php
/**
 * Role-Based Access Control (RBAC) Middleware
 * 
 * Enforces role-based permissions on API endpoints.
 * Must be called AFTER AuthMiddleware::check().
 * 
 * Usage:
 *   RoleMiddleware::require(['admin', 'super_admin']);
 *   RoleMiddleware::requireAny(['admin', 'accountant', 'super_admin']);
 *   RoleMiddleware::denyRole('viewer');
 */

declare(strict_types=1);

namespace App\Middleware;

final class RoleMiddleware
{
    /**
     * Require the user to have ONE of the specified roles.
     * Halts execution with 403 if the user doesn't have any of them.
     */
    public static function require(array $allowedRoles, ?array $decoded = null): array
    {
        if (!$decoded) {
            $decoded = AuthMiddleware::check();
        }

        $userRole = $decoded['role'] ?? '';

        if (!in_array($userRole, $allowedRoles, true)) {
            http_response_code(403);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'ليس لديك صلاحية للوصول إلى هذا المورد',
                'code'    => 'FORBIDDEN',
                'required_roles' => $allowedRoles,
                'your_role'      => $userRole,
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }

        return $decoded;
    }

    /**
     * Deny access to specific roles (blacklist approach).
     */
    public static function deny(array $deniedRoles, ?array $decoded = null): array
    {
        if (!$decoded) {
            $decoded = AuthMiddleware::check();
        }

        $userRole = $decoded['role'] ?? '';

        if (in_array($userRole, $deniedRoles, true)) {
            http_response_code(403);
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'ليس لديك صلاحية للوصول إلى هذا المورد',
                'code'    => 'FORBIDDEN',
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }

        return $decoded;
    }

    /**
     * Check if the current user is a super_admin.
     */
    public static function isSuperAdmin(array $decoded): bool
    {
        return ($decoded['role'] ?? '') === 'super_admin';
    }

    /**
     * Check if the current user is an admin or super_admin.
     */
    public static function isAdmin(array $decoded): bool
    {
        return in_array($decoded['role'] ?? '', ['admin', 'super_admin'], true);
    }

    /**
     * Check if the current user can write (create/update/delete).
     * Viewers are read-only.
     */
    public static function canWrite(array $decoded): bool
    {
        return in_array($decoded['role'] ?? '', ['super_admin', 'admin', 'accountant'], true);
    }
}
