<?php
// includes/auth.php
// Handles session management and basic authentication checks.

// Function to set a session message (for alerts)
function set_message($message, $type = 'info') {
    $_SESSION['message'] = $message;
    $_SESSION['message_type'] = $type;
}
/**
 * Retrieves and clears a session message.
 * @return array|null The message array or null if no message exists.
 */
function get_message() {
    if (isset($_SESSION['message'])) {
        $message = $_SESSION['message'];
        unset($_SESSION['message']);
        return $message;
    }
    return null;
}

// Function to check if a user is logged in
function is_logged_in() {
    return isset($_SESSION['user_id']);
}

// Function to check if the logged-in user has a specific role
function has_role($required_role) {
    if (!is_logged_in()) {
        return false;
    }
    // For simplicity, this assumes a direct match.
    // In a real app, you might have an array of roles or more complex logic.
    return $_SESSION['user_status'] === $required_role;
}

/**
 * Checks whether the current user is allowed to run R/Jupyter integrations.
 *
 * @return bool
 */
function has_r_access(): bool {
    return !empty($_SESSION['can_run_r']);
}

// Function to redirect if not logged in
function redirect_if_not_logged_in($redirect_path = '../index.php') {
    if (!is_logged_in()) {
        set_message("Please login to access this page.", "warning");
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            $scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
        }
        $host = $_SERVER['HTTP_HOST'] ?? '';
        if ($host && str_starts_with($redirect_path, '../')) {
            $path = '/' . ltrim($redirect_path, './');
            header("Location: {$scheme}://{$host}{$path}");
        } else {
            header("Location: " . $redirect_path);
        }
        exit();
    }
}

// Function to redirect if user does not have required role
function redirect_if_not_role($required_role, $redirect_path = '../index.php') {
    if (!has_role($required_role)) {
        set_message("You do not have permission to access this page.", "danger");
        header("Location: " . $redirect_path);
        exit();
    }
}

/**
 * Redirects away if the user lacks R/Jupyter access rights.
 *
 * @param string $redirect_path Where to redirect when access is denied.
 */
function redirect_if_no_r_access($redirect_path = '../index.php') {
    if (!has_r_access()) {
        set_message("You do not have R/Jupyter access. Please contact DAC Staff.", "danger");
        header("Location: " . $redirect_path);
        exit();
    }
}

?>
