<?php
namespace App\Middlewares;

class RbacMiddleware {
    
    public function handle() {
        if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role'])) {
            header('Location: /nis-migrant-ereg/login');
            exit;
        }
        
        // Get current route
        $uri = $_SERVER['REQUEST_URI'];
        $role = $_SESSION['user_role'];
        
        // Define role permissions
        $permissions = [
            'SuperAdmin' => ['*'],
            'Admin' => [
                '/dashboard',
                '/migrants/*',
                '/pending',
                '/reports',
                '/profile'
            ],
            'ImmigrationOfficer' => [
                '/dashboard',
                '/migrants/create',
                '/migrants/*',
                '/profile'
            ],
            'Reviewer' => [
                '/dashboard',
                '/migrants/*/show',
                '/profile'
            ]
        ];
        
        // Check if role has permission
        if (!$this->checkPermission($role, $uri, $permissions)) {
            header('HTTP/1.0 403 Forbidden');
            include APP_PATH . '/views/errors/403.php';
            exit;
        }
    }
    
    private function checkPermission($role, $uri, $permissions) {
        if ($role === 'SuperAdmin') return true;
        
        $allowed = $permissions[$role] ?? [];
        
        foreach ($allowed as $pattern) {
            $pattern = str_replace('*', '.*', $pattern);
            $pattern = '/^' . str_replace('/', '\/', $pattern) . '$/';
            if (preg_match($pattern, $uri)) {
                return true;
            }
        }
        
        return false;
    }
}