<?php

if (!function_exists('sikompro_session_bootstrap')) {
    function sikompro_session_bootstrap($requireLogin = false, $idleTimeoutSeconds = 2592000, $cookieLifetimeSeconds = 2592000)
    {
        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

        if (session_status() !== PHP_SESSION_ACTIVE) {
            if (PHP_VERSION_ID >= 70300) {
                session_set_cookie_params([
                    'lifetime' => $cookieLifetimeSeconds,
                    'path' => '/',
                    'domain' => '',
                    'secure' => $secure,
                    'httponly' => true,
                    'samesite' => 'Lax',
                ]);
            } else {
                session_set_cookie_params($cookieLifetimeSeconds, '/');
            }

            ini_set('session.gc_maxlifetime', (string) $cookieLifetimeSeconds);
            session_start();
        }

        if (!isset($_SESSION['session_created_at'])) {
            $_SESSION['session_created_at'] = time();
        }

        if (!isset($_SESSION['last_activity'])) {
            $_SESSION['last_activity'] = time();
        }

        if ($requireLogin && isset($_SESSION['login']) && $idleTimeoutSeconds > 0) {
            $lastActivity = (int) ($_SESSION['last_activity'] ?? 0);

            if ($lastActivity > 0 && (time() - $lastActivity) > $idleTimeoutSeconds) {
                $_SESSION = [];

                if (ini_get('session.use_cookies')) {
                    $params = session_get_cookie_params();
                    setcookie(
                        session_name(),
                        '',
                        time() - 3600,
                        $params['path'],
                        $params['domain'],
                        (bool) $params['secure'],
                        (bool) $params['httponly']
                    );
                }

                session_destroy();
                header('Location: ../middleware/login.php?expired=1');
                exit;
            }

            $_SESSION['last_activity'] = time();
        }
    }
}
