<?php

if (!function_exists('ec_access_session')) {
    function ec_access_session(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }
    }
}

if (!function_exists('ec_access_role')) {
    function ec_access_role(): string
    {
        ec_access_session();

        if (function_exists('ec_scope_role')) {
            return ec_scope_role();
        }

        return (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }
}

if (!function_exists('ec_access_landing_for_role')) {
    function ec_access_landing_for_role(?string $role = null): string
    {
        $role = $role ?: ec_access_role();

        if (function_exists('ec_scope_landing_url')) {
            return ec_scope_landing_url($role);
        }

        return match ($role) {
            'author' => '/easychair/author/dashboard',
            'reviewer' => '/easychair/reviewer/dashboard',
            'super_admin' => '/easychair/select-conference',
            default => '/easychair/admin/dashboard',
        };
    }
}

if (!function_exists('ec_access_guard_current_path')) {
    function ec_access_guard_current_path(): void
    {
        if (PHP_SAPI === 'cli') {
            return;
        }

        ec_access_session();

        if (empty($_SESSION['user_id'])) {
            return;
        }

        if (defined('BASE_PATH') && file_exists(BASE_PATH . '/app/helpers/conference_scope.php')) {
            require_once BASE_PATH . '/app/helpers/conference_scope.php';
        }

        $role = ec_access_role();
        $path = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '';

        if ($role !== 'super_admin' && function_exists('ec_scope_auto_select_conference')) {
            ec_scope_auto_select_conference(false);
        }

        if ($role !== 'super_admin' && str_starts_with($path, '/easychair/select-conference')) {
            header('Location: ' . ec_access_landing_for_role($role));
            exit;
        }

        if ($role === 'author' && str_starts_with($path, '/easychair/admin')) {
            header('Location: /easychair/author/dashboard');
            exit;
        }

        if ($role === 'reviewer' && str_starts_with($path, '/easychair/admin')) {
            header('Location: /easychair/reviewer/dashboard');
            exit;
        }

        if (!in_array($role, ['author'], true) && str_starts_with($path, '/easychair/author')) {
            header('Location: ' . ec_access_landing_for_role($role));
            exit;
        }

        if (!in_array($role, ['reviewer'], true) && str_starts_with($path, '/easychair/reviewer')) {
            header('Location: ' . ec_access_landing_for_role($role));
            exit;
        }
    }
}
