<?php
namespace App\Core;

/**
 * Wraps PHP's native session so the internal agent console and the external
 * customer portal use two independent session cookies. A browser open on
 * both never has one login clobber the other (BRD 4: two front ends, one
 * ticket record, different visibility).
 */
class Session
{
    private static ?string $activeCookieName = null;

    public static function start(string $cookieName, int $idleTimeoutMinutes = 0): void
    {
        if (self::$activeCookieName === $cookieName) {
            return;
        }
        if (session_status() === PHP_SESSION_ACTIVE) {
            session_write_close();
        }
        session_name($cookieName);
        $secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
        session_set_cookie_params([
            'lifetime' => 0,
            'path' => '/',
            'secure' => $secure,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
        session_start();
        self::$activeCookieName = $cookieName;

        if ($idleTimeoutMinutes > 0) {
            $last = $_SESSION['_last_activity'] ?? null;
            if ($last !== null && (time() - $last) > $idleTimeoutMinutes * 60) {
                $_SESSION = [];
                session_regenerate_id(true);
            }
            $_SESSION['_last_activity'] = time();
        }
    }

    public static function regenerate(): void
    {
        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();
        self::$activeCookieName = null;
    }

    public static function flash(string $key, $value = null)
    {
        if ($value !== null) {
            $_SESSION['_flash'][$key] = $value;
            return null;
        }
        $v = $_SESSION['_flash'][$key] ?? null;
        unset($_SESSION['_flash'][$key]);
        return $v;
    }
}
