<?php
/**
 * Session Manager - Handles session security and validation
 * Prevents multiple user sessions and session hijacking
 */

namespace App\classes;

class SessionManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    /**
     * Validate current session
     * Checks if session belongs to the logged-in user and hasn't been hijacked
     */
    public function validateSession($userId) {
        // Check if user is logged in
        if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] != $userId) {
            return ['valid' => false, 'reason' => 'Session user mismatch'];
        }
        
        // Check session token exists
        if (!isset($_SESSION['session_token'])) {
            return ['valid' => false, 'reason' => 'Missing session token'];
        }
        
        // Check IP address hasn't changed (optional - can be disabled for mobile users)
        // Uncomment if you want strict IP checking
        /*
        if (isset($_SESSION['ip_address']) && 
            $_SESSION['ip_address'] !== ($_SERVER['REMOTE_ADDR'] ?? 'unknown')) {
            return ['valid' => false, 'reason' => 'IP address changed'];
        }
        */
        
        // Check user agent hasn't changed significantly
        if (isset($_SESSION['user_agent']) && 
            $_SESSION['user_agent'] !== ($_SERVER['HTTP_USER_AGENT'] ?? 'unknown')) {
            // Log but don't block (user agent can change with browser updates)
            error_log("User agent changed for user ID: $userId");
        }
        
        // Check session timeout (8 hours)
        if (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time']) > 28800) {
            return ['valid' => false, 'reason' => 'Session expired'];
        }
        
        return ['valid' => true];
    }
    
    /**
     * Check if another user is logged in
     * Returns true if a different user's session exists
     */
    public function hasOtherUserSession($currentUserId) {
        if (isset($_SESSION['user_id']) && $_SESSION['user_id'] != $currentUserId) {
            return [
                'has_other' => true,
                'other_user_id' => $_SESSION['user_id'],
                'other_username' => $_SESSION['username'] ?? 'Unknown'
            ];
        }
        return ['has_other' => false];
    }
    
    /**
     * Force logout of current session
     */
    public function forceLogout() {
        if (isset($_SESSION['user_id'])) {
            $userId = $_SESSION['user_id'];
            
            // Log the forced logout
            try {
                require_once __DIR__ . '/UserLoginTracker.php';
                $loginTracker = new \App\classes\UserLoginTracker($this->conn);
                $loginTracker->logLogout($userId, date('Y-m-d H:i:s', $_SESSION['login_time'] ?? time()));
            } catch (Exception $e) {
                error_log("Failed to log forced logout: " . $e->getMessage());
            }
        }
        
        // Destroy session
        session_destroy();
        
        // Clear session cookie
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 3600, '/');
        }
    }
    
    /**
     * Regenerate session ID (security best practice)
     */
    public function regenerateSessionId() {
        session_regenerate_id(true);
    }
}
?>

