<?php
/**
 * Session Management
 * Initialize user sessions and authentication checks.
 */

if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
    session_start();
}

// Define session timeout (30 minutes)
$session_timeout = 1800;

// Check if user session has expired
if (session_status() === PHP_SESSION_ACTIVE && isset($_SESSION['user_id'])) {
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
        session_destroy();
        if (!headers_sent()) {
            header("Location: login.php?session_expired=1");
            exit();
        }
    }
    $_SESSION['last_activity'] = time();
}

/**
 * Check if user is logged in
 */
function isLoggedIn() {
    return session_status() === PHP_SESSION_ACTIVE && isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

/**
 * Get current logged in user ID
 */
function getCurrentUserId() {
    return session_status() === PHP_SESSION_ACTIVE ? ($_SESSION['user_id'] ?? null) : null;
}

/**
 * Get current logged in user data
 */
function getCurrentUser() {
    return session_status() === PHP_SESSION_ACTIVE ? ($_SESSION['user_data'] ?? null) : null;
}

/**
 * Login user
 */
function loginUser($user_id, $email, $first_name, $last_name, $user_type = 'guest') {
    if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
        session_start();
    }
    if (session_status() !== PHP_SESSION_ACTIVE) {
        return false;
    }

    $_SESSION['user_id'] = $user_id;
    $_SESSION['email'] = $email;
    $_SESSION['user_data'] = [
        'id' => $user_id,
        'email' => $email,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'user_type' => $user_type
    ];
    $_SESSION['last_activity'] = time();

    return true;
}

/**
 * Logout user
 */
function logoutUser() {
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_destroy();
    }
}
