<?php
/**
 * Session cookie configuration — must run before session_start().
 *
 * Uses a browser "session" cookie (lifetime 0): when the user fully closes the
 * browser or standalone PWA, the cookie is typically discarded so they must
 * sign in again. (Exact behaviour depends on OS/browser; backgrounding the app
 * does not always count as "close".)
 *
 * Requires BASE_PATH from config/app.php.
 */
declare(strict_types=1);

function nazareth_bootstrap_session_cookie(): void
{
    static $configured = false;
    if ($configured) {
        return;
    }
    $configured = true;

    if (!defined('BASE_PATH')) {
        return;
    }

    if (headers_sent()) {
        return;
    }

    ini_set('session.use_strict_mode', '1');
    ini_set('session.cookie_lifetime', '0');

    $path = '/';
    $bp = (string) BASE_PATH;
    if ($bp !== '' && $bp !== '/') {
        $path = rtrim($bp, '/');
    }

    $secure = (!empty($_SERVER['HTTPS']) && strcasecmp((string) $_SERVER['HTTPS'], 'off') !== 0)
        || ((string) ($_SERVER['SERVER_PORT'] ?? '') === '443')
        || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https');

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