<?php
/**
 * Session Manager
 * Handles PHP session configuration and management
 */

class SessionManager {
    private $sessionDir;
    private $sessionLifetime = 7200; // 2 hours
    private $sessionName = 'homoeopathy_session';
    
    public function __construct($sessionDir = null) {
        $this->sessionDir = $sessionDir ?: __DIR__ . '/../tmp/sessions/';
        $this->configure();
    }
    
    /**
     * Configure session settings
     */
    private function configure() {
        // Ensure session directory exists
        if (!is_dir($this->sessionDir)) {
            mkdir($this->sessionDir, 0755, true);
        }
        
        // Set session save path
        session_save_path($this->sessionDir);
        
        // Set session name
        session_name($this->sessionName);
        
        // Set session cookie parameters
        session_set_cookie_params([
            'lifetime' => $this->sessionLifetime,
            'path' => '/',
            'domain' => '',
            'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
            'httponly' => true,
            'samesite' => 'Strict'
        ]);
    }
    
    /**
     * Start session
     * @return bool
     */
    public function start() {
        if (session_status() === PHP_SESSION_NONE) {
            return session_start();
        }
        return true;
    }
    
    /**
     * Destroy session
     * @return bool
     */
    public function destroy() {
        $_SESSION = [];
        
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        
        return session_destroy();
    }
    
    /**
     * Regenerate session ID
     * @param bool $deleteOldSession
     * @return bool
     */
    public function regenerate($deleteOldSession = true) {
        return session_regenerate_id($deleteOldSession);
    }
    
    /**
     * Set session value
     * @param string $key
     * @param mixed $value
     */
    public function set($key, $value) {
        $_SESSION[$key] = $value;
    }
    
    /**
     * Get session value
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public function get($key, $default = null) {
        return $_SESSION[$key] ?? $default;
    }
    
    /**
     * Delete session value
     * @param string $key
     */
    public function delete($key) {
        unset($_SESSION[$key]);
    }
    
    /**
     * Check if session has key
     * @param string $key
     * @return bool
     */
    public function has($key) {
        return isset($_SESSION[$key]);
    }
    
    /**
     * Get all session data
     * @return array
     */
    public function getAll() {
        return $_SESSION;
    }
    
    /**
     * Flash message (temporary session data)
     * @param string $key
     * @param mixed $value
     */
    public function flash($key, $value) {
        $_SESSION['_flash'][$key] = $value;
    }
    
    /**
     * Get flash message
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public function getFlash($key, $default = null) {
        $value = $_SESSION['_flash'][$key] ?? $default;
        unset($_SESSION['_flash'][$key]);
        return $value;
    }
    
    /**
     * Clean expired sessions
     * @return int Number of sessions cleaned
     */
    public function cleanExpired() {
        $count = 0;
        $files = glob($this->sessionDir . 'sess_*');
        $now = time();
        
        foreach ($files as $file) {
            if (filemtime($file) < $now - $this->sessionLifetime) {
                if (unlink($file)) {
                    $count++;
                }
            }
        }
        
        return $count;
    }
    
    /**
     * Get session statistics
     * @return array
     */
    public function getStats() {
        $files = glob($this->sessionDir . 'sess_*');
        $totalSize = 0;
        
        foreach ($files as $file) {
            $totalSize += filesize($file);
        }
        
        return [
            'active_sessions' => count($files),
            'total_size' => $totalSize,
            'session_lifetime' => $this->sessionLifetime,
            'session_name' => $this->sessionName
        ];
    }
}

// Global session manager
$sessionManager = null;

function getSession() {
    global $sessionManager;
    if ($sessionManager === null) {
        $sessionManager = new SessionManager();
        $sessionManager->start();
    }
    return $sessionManager;
}