<?php
/**
 * Session Helper
 * Session management, secure cookie setup, flash messages, timeout & regeneration
 */

class Session {
    public static function start(): void {
        if (session_status() === PHP_SESSION_NONE) {
            $lifetime = 7200; // 2 hours
            
            ini_set('session.use_only_cookies', '1');
            ini_set('session.use_strict_mode', '1');
            
            session_set_cookie_params([
                'lifetime' => $lifetime,
                'path' => '/',
                'domain' => '',
                'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
                'httponly' => true,
                'samesite' => 'Lax'
            ]);

            session_name('CARGOO_SESSID');
            session_start();

            // Check session expiration
            self::checkTimeout();
        }
    }

    /**
     * Check if session has timed out due to inactivity
     */
    private static function checkTimeout(): void {
        $maxLifetime = 7200; // 2 hours
        $now = time();

        if (isset($_SESSION['LAST_ACTIVITY'])) {
            if (($now - $_SESSION['LAST_ACTIVITY']) > $maxLifetime) {
                self::destroy();
                return;
            }
        }
        $_SESSION['LAST_ACTIVITY'] = $now;

        // Periodic session regeneration every 30 minutes
        if (!isset($_SESSION['CREATED'])) {
            $_SESSION['CREATED'] = $now;
        } elseif (($now - $_SESSION['CREATED']) > 1800) {
            session_regenerate_id(true);
            $_SESSION['CREATED'] = $now;
        }
    }

    public static function set(string $key, $value): void {
        $_SESSION[$key] = $value;
    }

    public static function get(string $key, $default = null) {
        return $_SESSION[$key] ?? $default;
    }

    public static function has(string $key): bool {
        return isset($_SESSION[$key]);
    }

    public static function remove(string $key): void {
        unset($_SESSION[$key]);
    }

    public static function regenerate(): void {
        if (session_status() === PHP_SESSION_ACTIVE && !headers_sent()) {
            session_regenerate_id(true);
        }
    }

    public static function destroy(): void {
        $_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();
    }

    /**
     * Set a flash message
     * Types: success, danger, warning, info
     */
    public static function setFlash(string $type, string $message): void {
        if (!isset($_SESSION['_flash'])) {
            $_SESSION['_flash'] = [];
        }
        $_SESSION['_flash'][$type][] = $message;
    }

    /**
     * Get flash messages and clear them
     */
    public static function getFlashes(): array {
        $flashes = $_SESSION['_flash'] ?? [];
        unset($_SESSION['_flash']);
        return $flashes;
    }

    /**
     * Flash Old Input Data
     */
    public static function setOldInput(array $data): void {
        // Exclude passwords
        unset($data['password'], $data['confirm_password'], $data['current_password'], $data['new_password'], $data['confirm_new_password'], $data['csrf_token']);
        $_SESSION['_old_input'] = $data;
    }

    public static function getOldInput(string $key, $default = '') {
        $old = $_SESSION['_old_input'][$key] ?? $default;
        return $old;
    }

    public static function clearOldInput(): void {
        unset($_SESSION['_old_input']);
    }
}
