<?php
// app/core/AuthHelper.php

namespace app\cnx\admin;

use model\util\SessionManager;

require_once __DIR__ . '/SessionManager.php';

class AuthHelper
{

    /**
     * Verify user is logged in, redirect to login if not
     */
    public static function requireLogin()
    {
        $session = SessionManager::getInstance();

        if (!$session->isLoggedIn()) {
            // Redirect to login page
            header('Location: /login.php');
            exit();
        }
        return true;
    }

    /**
     * Verify user is logged in and has required role
     */
    public static function requireRole($role)
    {
        self::requireLogin();

        $session = SessionManager::getInstance();
        if (!$session->hasRole($role)) {
            // Access denied - redirect or show error
            header('Location: /access-denied.php');
            exit();
        }
        return true;
    }

    /**
     * Verify user is logged in and has any of the required roles
     */
    public static function requireAnyRole($roles)
    {
        self::requireLogin();

        $session = SessionManager::getInstance();
        if (!$session->hasAnyRole($roles)) {
            header('Location: /access-denied.php');
            exit();
        }
        return true;
    }

    /**
     * Get current user data (with optional redirect if not logged in)
     */
    public static function getCurrentUser($redirectIfNotLoggedIn = false)
    {
        $session = SessionManager::getInstance();

        if ($redirectIfNotLoggedIn && !$session->isLoggedIn()) {
            header('Location: /login.php');
            exit();
        }

        return $session->getCurrentUser();
    }

    /**
     * Check if user is logged in (returns boolean)
     */
    public static function isLoggedIn()
    {
        $session = SessionManager::getInstance();
        return $session->isLoggedIn();
    }

    /**
     * Get user ID or null if not logged in
     */
    public static function getUserId()
    {
        $session = SessionManager::getInstance();
        return $session->getUserId();
    }

    /**
     * Get user role or null if not logged in
     */
    public static function getUserRole()
    {
        $session = SessionManager::getInstance();
        return $session->getUserRole();
    }

    /**
     * Logout user
     */
    public static function logout()
    {
        $session = SessionManager::getInstance();
        return $session->logout();
    }
}

?>
