<?php

/*
 * ICYLAB OS — Inicialización segura de sesión.
 * Debe cargarse antes de imprimir cualquier contenido HTML.
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    $httpsValue = $_SERVER['HTTPS'] ?? '';
    $forwardedProto = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
    $serverPort = $_SERVER['SERVER_PORT'] ?? null;

    if (!is_string($httpsValue)) {
        $httpsValue = '';
    }

    if (!is_string($forwardedProto)) {
        $forwardedProto = '';
    }

    // Algunos proxies envían: "https,http".
    $forwardedParts = explode(',', strtolower($forwardedProto));
    $forwardedProto = trim($forwardedParts[0] ?? '');

    $isHttps =
        ($httpsValue !== '' && strtolower($httpsValue) !== 'off')
        || $forwardedProto === 'https'
        || (is_scalar($serverPort) && (string) $serverPort === '443')
        || (defined('APP_URL') && stripos((string)APP_URL, 'https://') === 0)
        || (defined('APP_ENV') && APP_ENV === 'production');

    /*
     * Se utilizan directivas individuales en lugar de
     * session_set_cookie_params([...]) para evitar el aviso
     * "Array to string conversion" en handlers incompatibles.
     */
    ini_set('session.use_only_cookies', '1');
    ini_set('session.use_strict_mode', '1');
    ini_set('session.use_trans_sid', '0');
    ini_set('session.gc_maxlifetime', '43200');
    ini_set('session.cookie_lifetime', '0');
    ini_set('session.cookie_path', '/');
    ini_set('session.cookie_secure', $isHttps ? '1' : '0');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');

    session_name('ICYLABSESSID');
    session_start();
}

require_once __DIR__ . '/csrf.php';

$sessionNow = time();
$sessionCreatedAt = isset($_SESSION['_created_at']) ? (int)$_SESSION['_created_at'] : $sessionNow;
$sessionLastSeenAt = isset($_SESSION['_last_seen_at']) ? (int)$_SESSION['_last_seen_at'] : $sessionNow;
$sessionExpired = !empty($_SESSION['user']) && (
    ($sessionNow - $sessionLastSeenAt) > 7200
    || ($sessionNow - $sessionCreatedAt) > 43200
);

if ($sessionExpired) {
    $_SESSION = array();
    session_regenerate_id(true);
    $_SESSION['_created_at'] = $sessionNow;
} else {
    $_SESSION['_created_at'] = $sessionCreatedAt;
}

$_SESSION['_last_seen_at'] = $sessionNow;
$lastRotation = isset($_SESSION['_last_rotation_at']) ? (int)$_SESSION['_last_rotation_at'] : 0;
if (!$sessionExpired && !headers_sent() && ($sessionNow - $lastRotation) > 1800) {
    session_regenerate_id(true);
    $_SESSION['_last_rotation_at'] = $sessionNow;
}

unset($sessionNow, $sessionCreatedAt, $sessionLastSeenAt, $sessionExpired, $lastRotation);

function current_user(): ?array
{
    $user = $_SESSION['user'] ?? null;

    return is_array($user) ? $user : null;
}

function is_logged_in(): bool
{
    $user = current_user();

    return $user !== null
        && isset($user['id'])
        && (int) $user['id'] > 0;
}

function require_login(): void
{
    if (is_logged_in()) {
        csrf_require_same_origin_request();
        return;
    }

    if (!headers_sent()) {
        header('Location: /login.php');
    }

    exit;
}
