<?php
/**
 * BOAFO Middleware
 * Authentication and role-based access control
 */
class Middleware {
    public static function run(string $name): void {
        match($name) {
            'auth'    => self::auth(),
            'guest'   => self::guest(),
            'admin'   => self::role('admin'),
            'student' => self::role('student'),
            'mentor'  => self::role('mentor'),
            'tutor'   => self::role('tutor'),
            'mentor_or_student' => self::roleAny(['mentor','student']),
            default   => null,
        };
    }

    private static function auth(): void {
        if (!Auth::check()) {
            $_SESSION['intended_url'] = $_SERVER['REQUEST_URI'];
            redirect(APP_URL . '/login');
        }
    }

    private static function guest(): void {
        if (Auth::check()) {
            redirect(APP_URL . '/dashboard');
        }
    }

    private static function role(string $required): void {
        self::auth();
        if (Auth::user()['role'] !== $required) {
            http_response_code(403);
            require APP_PATH . '/Views/errors/403.php';
            exit;
        }
    }

    private static function roleAny(array $roles): void {
        self::auth();
        if (!in_array(Auth::user()['role'], $roles, true)) {
            http_response_code(403);
            require APP_PATH . '/Views/errors/403.php';
            exit;
        }
    }
}
