<?php
namespace App\Middleware;

class RoleGuard
{
    public static function allow(array $roles)
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

/*
|--------------------------------------------------------------------------
| PUBLIC CONFERENCE / PAPER PAGES
|--------------------------------------------------------------------------
*/

$path =
    parse_url(
        $_SERVER['REQUEST_URI'] ?? '/',
        PHP_URL_PATH
    );

$isPublicConference =
    preg_match(
        '#^/easychair/conference/[a-zA-Z0-9\-_]+$#',
        $path
    );

$isPublicPaper =
    preg_match(
        '#^/easychair/paper/[0-9]+$#',
        $path
    );

/*
ALLOW PUBLIC ACCESS
*/

if (
    $isPublicConference
    || $isPublicPaper
) {

    return true;

}

        if (empty($_SESSION['user_id'])) {
            
error_log(
    'ROLEGUARD REDIRECT >>> ' .
    ($_SERVER['REQUEST_URI'] ?? '')
);

header("Location: /easychair/login");
            exit;
        }

        $role = $_SESSION['role'] ?? $_SESSION['user_role'] ?? '';

        if ($role === 'super_admin') {
            return true;
        }

        if (in_array('admin', $roles, true)) {
            $adminRoles = [
                'org_admin',
                'admin',
                'organizer',
                'conference_chair',
                'track_chair',
                'tpc'
            ];

            if (in_array($role, $adminRoles, true)) {
                return true;
            }
        }

        if (!in_array($role, $roles, true)) {
            http_response_code(403);
            exit("Access denied.");
        }

        return true;
    }
}
