<?php
require_once __DIR__ . '/config.php';

/**
 * Detect HTTPS even when running behind a reverse proxy or
 * Cloudflare (where $_SERVER['HTTPS'] is often empty because
 * the proxy talks plain HTTP to the origin).
 */
function session_is_https(): bool {
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') return true;
    if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
        && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') return true;
    if (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) return true;
    return false;
}

/**
 * Start a session exactly once per request, with safe defaults.
 * Safe to call anywhere; no-op if the session is already active.
 */
function session_start_once(): void {
    if (session_status() === PHP_SESSION_ACTIVE) return;

    session_name(AUTH_SESSION_NAME);

    // Only set cookie params if we haven't sent the session cookie yet
    session_set_cookie_params([
        'lifetime' => AUTH_SESSION_LIFE,
        'path'     => '/',
        'secure'   => session_is_https(),
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    session_start();
}