<?php
/**
 * Secure Session Management
 */
class Session {
    
    public static function init() {
        if (session_status() === PHP_SESSION_NONE) {
            // Secure session settings
            ini_set('session.cookie_httponly', 1);
            ini_set('session.cookie_secure', 1);
            ini_set('session.cookie_samesite', 'Strict');
            ini_set('session.use_strict_mode', 1);
            ini_set('session.use_only_cookies', 1);
            ini_set('session.gc_maxlifetime', Config::get('session_lifetime', 1800));
            
            session_name(Config::get('session_name', 'NIS_AMS_SESSION'));
            session_start();
            
            // Regenerate session ID periodically
            if (!isset($_SESSION['_last_regenerate']) || 
                time() - $_SESSION['_last_regenerate'] > 300) {
                session_regenerate_id(true);
                $_SESSION['_last_regenerate'] = time();
            }
            
            // Validate session fingerprint
            self::validateFingerprint();
        }
    }
    
    public static function set($key, $value) {
        $_SESSION[$key] = $value;
    }
    
    public static function get($key, $default = null) {
        return $_SESSION[$key] ?? $default;
    }
    
    public static function has($key) {
        return isset($_SESSION[$key]);
    }
    
    public static function remove($key) {
        unset($_SESSION[$key]);
    }
    
    public static 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"]
            );
        }
        
        session_destroy();
    }
    
    private static function validateFingerprint() {
        $fingerprint = self::generateFingerprint();
        
        if (!isset($_SESSION['_fingerprint'])) {
            $_SESSION['_fingerprint'] = $fingerprint;
        } elseif ($_SESSION['_fingerprint'] !== $fingerprint) {
            self::destroy();
            header('Location: ' . Config::get('app_url') . '/auth/login');
            exit();
        }
    }
    
    private static function generateFingerprint() {
        return hash('sha256', 
            $_SERVER['HTTP_USER_AGENT'] . 
            $_SERVER['REMOTE_ADDR'] . 
            (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '')
        );
    }
    
    public static function regenerate() {
        session_regenerate_id(true);
        $_SESSION['_last_regenerate'] = time();
    }
}