<?php
/**
 * Session Helper Functions
 * Provides standardized session access across EasyStream
 *
 * This file resolves conflicts between different session variable names
 * used throughout the application.
 */

if (!defined('_ISVALID')) {
    die('Direct access is not allowed');
}

/**
 * Get current user ID from session
 * Handles legacy session variable names for backward compatibility
 *
 * @return int User ID or 0 if not logged in
 */
function getCurrentUserId() {
    // Check modern standard (preferred)
    if (isset($_SESSION['USER_ID']) && $_SESSION['USER_ID'] > 0) {
        return (int) $_SESSION['USER_ID'];
    }

    // Check legacy variant 1 (migrate to new standard)
    if (isset($_SESSION['usr_id']) && $_SESSION['usr_id'] > 0) {
        $_SESSION['USER_ID'] = (int) $_SESSION['usr_id'];
        unset($_SESSION['usr_id']);
        VLogger::log('info', 'Migrated session variable usr_id to USER_ID', [
            'user_id' => $_SESSION['USER_ID']
        ]);
        return (int) $_SESSION['USER_ID'];
    }

    // Check legacy variant 2 (migrate to new standard)
    if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0) {
        $_SESSION['USER_ID'] = (int) $_SESSION['user_id'];
        unset($_SESSION['user_id']);
        VLogger::log('info', 'Migrated session variable user_id to USER_ID', [
            'user_id' => $_SESSION['USER_ID']
        ]);
        return (int) $_SESSION['USER_ID'];
    }

    return 0;
}

/**
 * Set current user ID in session
 * Automatically cleans up legacy session variables
 *
 * @param int $userId User ID to set
 * @return void
 */
function setCurrentUserId($userId) {
    $_SESSION['USER_ID'] = (int) $userId;

    // Clean up legacy session variables to prevent conflicts
    unset($_SESSION['usr_id']);
    unset($_SESSION['user_id']);
}

/**
 * Check if user is logged in
 *
 * @return bool True if user is authenticated, false otherwise
 */
function isUserLoggedIn() {
    return getCurrentUserId() > 0;
}

/**
 * Get current username from session
 *
 * @return string|null Username or null if not set
 */
function getCurrentUsername() {
    return $_SESSION['USER_NAME'] ?? $_SESSION['usr_user'] ?? null;
}

/**
 * Get current user email from session
 *
 * @return string|null Email or null if not set
 */
function getCurrentUserEmail() {
    return $_SESSION['USER_EMAIL'] ?? $_SESSION['usr_email'] ?? null;
}

/**
 * Get current user key (unique identifier)
 *
 * @return string|null User key or null if not set
 */
function getCurrentUserKey() {
    return $_SESSION['USER_KEY'] ?? null;
}

/**
 * Clear user session completely
 * Removes all user-related session variables
 *
 * @return void
 */
function clearUserSession() {
    // Standard variables
    unset($_SESSION['USER_ID']);
    unset($_SESSION['USER_NAME']);
    unset($_SESSION['USER_EMAIL']);
    unset($_SESSION['USER_KEY']);

    // Legacy variables
    unset($_SESSION['usr_id']);
    unset($_SESSION['user_id']);
    unset($_SESSION['usr_user']);
    unset($_SESSION['usr_email']);

    // Additional user data
    unset($_SESSION['usr_verified']);
    unset($_SESSION['usr_partner']);
    unset($_SESSION['usr_avatar']);
}

/**
 * Migrate all session variables to new standard
 * Useful for one-time migration during login
 *
 * @param array $userData User data from database
 * @return void
 */
function migrateSessionVariables($userData) {
    // Set standard variables
    if (isset($userData['usr_id'])) {
        setCurrentUserId($userData['usr_id']);
    }

    if (isset($userData['usr_user'])) {
        $_SESSION['USER_NAME'] = $userData['usr_user'];
    }

    if (isset($userData['usr_email'])) {
        $_SESSION['USER_EMAIL'] = $userData['usr_email'];
    }

    if (isset($userData['usr_key'])) {
        $_SESSION['USER_KEY'] = $userData['usr_key'];
    }

    // Store additional user data if needed
    if (isset($userData['usr_verified'])) {
        $_SESSION['usr_verified'] = (bool) $userData['usr_verified'];
    }

    if (isset($userData['usr_partner'])) {
        $_SESSION['usr_partner'] = (bool) $userData['usr_partner'];
    }

    if (isset($userData['usr_avatar'])) {
        $_SESSION['usr_avatar'] = $userData['usr_avatar'];
    }

    VLogger::log('info', 'Session variables migrated to new standard', [
        'user_id' => getCurrentUserId()
    ]);
}

/**
 * Get all current user session data
 *
 * @return array User session data
 */
function getCurrentUserSessionData() {
    return [
        'user_id' => getCurrentUserId(),
        'username' => getCurrentUsername(),
        'email' => getCurrentUserEmail(),
        'user_key' => getCurrentUserKey(),
        'verified' => $_SESSION['usr_verified'] ?? false,
        'partner' => $_SESSION['usr_partner'] ?? false,
        'avatar' => $_SESSION['usr_avatar'] ?? null,
        'is_logged_in' => isUserLoggedIn()
    ];
}

/**
 * Validate session and check for hijacking attempts
 *
 * @return bool True if session is valid, false if suspicious
 */
function validateUserSession() {
    if (!isUserLoggedIn()) {
        return true; // No session to validate
    }

    // Check if user agent changed (possible hijacking)
    $currentUserAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $sessionUserAgent = $_SESSION['USER_AGENT'] ?? '';

    if (!empty($sessionUserAgent) && $sessionUserAgent !== $currentUserAgent) {
        VLogger::log('warning', 'Session user agent mismatch - possible hijacking', [
            'user_id' => getCurrentUserId(),
            'session_ua' => substr($sessionUserAgent, 0, 100),
            'current_ua' => substr($currentUserAgent, 0, 100)
        ]);

        clearUserSession();
        return false;
    }

    // Check if IP changed (optional strict check)
    if (defined('SESSION_IP_CHECK') && SESSION_IP_CHECK === true) {
        $currentIp = $_SERVER['REMOTE_ADDR'] ?? '';
        $sessionIp = $_SESSION['USER_IP'] ?? '';

        if (!empty($sessionIp) && $sessionIp !== $currentIp) {
            VLogger::log('warning', 'Session IP mismatch - possible hijacking', [
                'user_id' => getCurrentUserId(),
                'session_ip' => $sessionIp,
                'current_ip' => $currentIp
            ]);

            clearUserSession();
            return false;
        }
    }

    return true;
}

/**
 * Initialize session security variables
 * Call this after successful login
 *
 * @return void
 */
function initializeSessionSecurity() {
    $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $_SESSION['USER_IP'] = $_SERVER['REMOTE_ADDR'] ?? '';
    $_SESSION['SESSION_START_TIME'] = time();
}

/**
 * Check if session has expired
 *
 * @param int $timeout Timeout in seconds (default: 1 hour)
 * @return bool True if expired, false otherwise
 */
function isSessionExpired($timeout = 3600) {
    if (!isset($_SESSION['SESSION_START_TIME'])) {
        return false; // No timestamp, can't determine
    }

    $elapsed = time() - $_SESSION['SESSION_START_TIME'];

    if ($elapsed > $timeout) {
        VLogger::log('info', 'Session expired', [
            'user_id' => getCurrentUserId(),
            'elapsed_seconds' => $elapsed
        ]);

        return true;
    }

    return false;
}

/**
 * Refresh session timestamp
 * Call periodically to extend session
 *
 * @return void
 */
function refreshSession() {
    if (isUserLoggedIn()) {
        $_SESSION['SESSION_START_TIME'] = time();
    }
}
