<?php

declare(strict_types=1);

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

function require_login(): void
{
    if (!current_user()) {
        redirect('/login.php');
    }
}

function load_user_profiles(int $userId): array
{
    $sql = 'SELECT p.codigo, p.nombre FROM usuario_perfil up
            INNER JOIN perfiles p ON p.id = up.perfil_id
            WHERE up.usuario_id = ?';
    $st = db()->prepare($sql);
    $st->execute([$userId]);
    $rows = $st->fetchAll();
    $codes = [];
    foreach ($rows as $r) {
        $codes[] = $r['codigo'];
    }
    return $codes;
}

function attempt_login(string $email, string $password): bool
{
    $st = db()->prepare(
        'SELECT id, email, password_hash, nombre, apellidos, activo FROM usuarios WHERE email = ? LIMIT 1'
    );
    $st->execute([$email]);
    $u = $st->fetch();
    if (!$u || !(int) $u['activo']) {
        return false;
    }
    if (!password_verify($password, $u['password_hash'])) {
        return false;
    }
    $perfiles = load_user_profiles((int) $u['id']);
    $_SESSION['user'] = [
        'id' => (int) $u['id'],
        'email' => $u['email'],
        'nombre' => $u['nombre'],
        'apellidos' => $u['apellidos'],
        'perfiles' => $perfiles,
    ];
    if (empty($_SESSION['_csrf'])) {
        $_SESSION['_csrf'] = bin2hex(random_bytes(32));
    }
    $upd = db()->prepare('UPDATE usuarios SET ultimo_acceso = NOW() WHERE id = ?');
    $upd->execute([(int) $u['id']]);
    return true;
}

function logout(): void
{
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
}
