<?php

namespace App\Core;

final class Session
{
    private static bool $configured = false;

    public static function isHttps(): bool
    {
        return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (($_SERVER['SERVER_PORT'] ?? null) === '443')
            || (strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');
    }

    public static function cookieOptions(int $expires = 0): array
    {
        return [
            'expires' => $expires,
            'path' => '/',
            'domain' => '',
            'secure' => self::isHttps(),
            'httponly' => true,
            'samesite' => 'Lax',
        ];
    }

    public static function start(): void
    {
        if (session_status() === PHP_SESSION_ACTIVE) {
            return;
        }

        if (!self::$configured) {
            $isHttps = self::isHttps();

            session_set_cookie_params([
                'lifetime' => 0,
                'path' => '/',
                'secure' => $isHttps,
                'httponly' => true,
                'samesite' => 'Lax',
            ]);

            ini_set('session.use_strict_mode', '1');
            ini_set('session.cookie_httponly', '1');
            if ($isHttps) {
                ini_set('session.cookie_secure', '1');
            }
            ini_set('session.cookie_samesite', 'Lax');
            self::$configured = true;
        }

        session_start();
    }
}
