<?php
declare(strict_types=1);

/**
 * Session-based authentication for the server-rendered portal.
 */
final class Auth
{
    private const ROLE_RANK = ['viewer' => 1, 'analyst' => 2, 'admin' => 3];

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

        session_name(SESSION_NAME);
        session_set_cookie_params([
            'lifetime' => 0,
            'path'     => BASE_URL === '' ? '/' : BASE_URL,
            'httponly' => true,
            'secure'   => COOKIE_SECURE,
            'samesite' => 'Lax',
        ]);
        session_start();

        // Idle timeout
        $idleLimit = SESSION_IDLE_MINUTES * 60;
        if (isset($_SESSION['last_seen']) && (time() - (int) $_SESSION['last_seen']) > $idleLimit) {
            self::logout();
            session_start();
            $_SESSION['flash'] = [['warn', 'Your session timed out. Sign in again.']];
        }
        $_SESSION['last_seen'] = time();
    }

    public static function user(): ?array
    {
        if (empty($_SESSION['user_id'])) {
            return null;
        }

        static $cached = null;
        if ($cached !== null) {
            return $cached;
        }

        $u = Database::one(
            'SELECT id, username, full_name, email, role, is_active FROM users WHERE id = :id',
            ['id' => $_SESSION['user_id']]
        );

        if ($u === null || (int) $u['is_active'] !== 1) {
            self::logout();
            return null;
        }

        return $cached = $u;
    }

    public static function id(): ?int
    {
        $u = self::user();
        return $u === null ? null : (int) $u['id'];
    }

    public static function check(): bool
    {
        return self::user() !== null;
    }

    /** Send anonymous visitors to the login screen. */
    public static function requireLogin(): array
    {
        $u = self::user();
        if ($u === null) {
            $target = $_SERVER['REQUEST_URI'] ?? '';
            redirect('auth', 'login', ['next' => base64_encode($target)]);
        }
        return $u;
    }

    /** Stop the request unless the user holds at least this role. */
    public static function requireRole(string $minRole): array
    {
        $u = self::requireLogin();
        if ((self::ROLE_RANK[$u['role']] ?? 0) < (self::ROLE_RANK[$minRole] ?? 99)) {
            http_response_code(403);
            Flash::add('error', 'You do not have permission for that action.');
            redirect('dashboard');
        }
        return $u;
    }

    public static function can(string $minRole): bool
    {
        $u = self::user();
        if ($u === null) {
            return false;
        }
        return (self::ROLE_RANK[$u['role']] ?? 0) >= (self::ROLE_RANK[$minRole] ?? 99);
    }

    public static function isAdmin(): bool
    {
        return self::can('admin');
    }

    /** Returns true on success. */
    public static function attempt(string $username, string $password): bool
    {
        $user = Database::one(
            'SELECT id, username, full_name, role, password_hash, is_active
               FROM users WHERE username = :u LIMIT 1',
            ['u' => $username]
        );

        // Always run a hash comparison so a missing account is not detectable by timing.
        $hash = $user['password_hash'] ?? '$2y$12$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvalidin';
        $ok = password_verify($password, (string) $hash);

        if ($user === null || !$ok || (int) $user['is_active'] !== 1) {
            Audit::log('login_failed', 'user', null, ['username' => $username]);
            return false;
        }

        if (password_needs_rehash((string) $user['password_hash'], PASSWORD_BCRYPT, ['cost' => BCRYPT_COST])) {
            Database::run('UPDATE users SET password_hash = :h WHERE id = :id', [
                'h'  => password_hash($password, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]),
                'id' => $user['id'],
            ]);
        }

        session_regenerate_id(true);
        $_SESSION['user_id']   = (int) $user['id'];
        $_SESSION['last_seen'] = time();

        Database::run('UPDATE users SET last_login_at = NOW() WHERE id = :id', ['id' => $user['id']]);
        Audit::log('login', 'user', (int) $user['id']);

        return true;
    }

    public static 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();
    }

    /** Too many recent failures from this IP for this username? */
    public static function isLockedOut(string $username): bool
    {
        $n = (int) Database::scalar(
            "SELECT COUNT(*) FROM audit_log
              WHERE action = 'login_failed'
                AND ip = :ip
                AND JSON_UNQUOTE(JSON_EXTRACT(changes, '$.username')) = :u
                AND created_at > (NOW() - INTERVAL " . (int) LOGIN_LOCKOUT_MINUTES . " MINUTE)",
            ['ip' => client_ip_binary(), 'u' => $username]
        );
        return $n >= LOGIN_MAX_ATTEMPTS;
    }
}
