<?php
declare(strict_types=1);

require_once __DIR__ . '/Planets.php';
require_once __DIR__ . '/Blocks.php';

final class Store
{
    private PDO $pdo;
    private int $txDepth = 0;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->migrate();
    }

    public static function open(?string $dir = null): self
    {
        $dir = $dir ?? dataDir();
        if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
            throw new RuntimeException('De datamap moet schrijfbaar zijn.');
        }
        $path = $dir . '/meteors.sqlite';
        $pdo = new PDO('sqlite:' . $path, null, null, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        $pdo->exec('PRAGMA journal_mode = WAL');
        $pdo->exec('PRAGMA foreign_keys = ON');
        $pdo->exec('PRAGMA busy_timeout = 4000');
        return new self($pdo);
    }

    private function migrate(): void
    {
        $this->pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS lobbies (
    id TEXT PRIMARY KEY,
    code TEXT UNIQUE NOT NULL,
    host_id TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'waiting',
    miss_chance REAL NOT NULL DEFAULT 0.30,
    flight_duration REAL NOT NULL DEFAULT 1.2,
    created INTEGER NOT NULL,
    started INTEGER,
    finished INTEGER
);
CREATE TABLE IF NOT EXISTS members (
    lobby_id TEXT NOT NULL,
    user_id TEXT NOT NULL,
    name TEXT NOT NULL,
    ready INTEGER NOT NULL DEFAULT 0,
    eliminated INTEGER NOT NULL DEFAULT 0,
    place INTEGER,
    left_at INTEGER,
    joined INTEGER NOT NULL,
    last_seen INTEGER NOT NULL,
    score INTEGER NOT NULL DEFAULT 0,
    snapshot TEXT,
    PRIMARY KEY (lobby_id, user_id)
);
CREATE TABLE IF NOT EXISTS shots (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    lobby_id TEXT NOT NULL,
    from_user TEXT NOT NULL,
    to_user TEXT,
    color INTEGER NOT NULL,
    client_id TEXT,
    created REAL NOT NULL,
    deliver_at REAL NOT NULL,
    delivered INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
SQL);
        $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
        $this->ensureColumn('members', 'planet_json', 'TEXT');
        $this->ensureColumn('shots', 'land_col', 'INTEGER');
        $this->ensureColumn('shots', 'from_col', 'INTEGER');
        $this->ensureColumn('shots', 'from_y', 'REAL');
        $this->pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS profiles (
    user_id TEXT PRIMARY KEY,
    lifetime_points INTEGER NOT NULL DEFAULT 0,
    locale TEXT,
    updated INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS point_awards (
    award_key TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    mode TEXT NOT NULL,
    points INTEGER NOT NULL,
    created INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
CREATE TABLE IF NOT EXISTS play_sessions (
    token TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    mode TEXT NOT NULL,
    started INTEGER NOT NULL,
    finished INTEGER
);
CREATE TABLE IF NOT EXISTS custom_planets (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    name TEXT NOT NULL,
    people TEXT NOT NULL,
    jumps_to_clear REAL NOT NULL,
    fall_time REAL NOT NULL,
    rise_time REAL NOT NULL,
    colors TEXT NOT NULL,
    created INTEGER NOT NULL,
    updated INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
SQL);
        $this->ensureColumn('profiles', 'last_planet', 'TEXT');
    }

    private function ensureColumn(string $table, string $column, string $ddl): void
    {
        $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
        foreach ($cols as $c) {
            if (($c['name'] ?? '') === $column) {
                return;
            }
        }
        $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
    }

    public function transaction(callable $fn): mixed
    {
        if ($this->txDepth > 0) {
            return $fn();
        }
        $this->pdo->beginTransaction();
        $this->txDepth++;
        try {
            $result = $fn();
            $this->pdo->commit();
            $this->txDepth--;
            return $result;
        } catch (Throwable $e) {
            $this->txDepth--;
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            throw $e;
        }
    }

    /** Tests may freeze the clock without sleeping. */
    public ?int $testNow = null;

    private function now(): int
    {
        return $this->testNow ?? time();
    }

    private function nowf(): float
    {
        return microtime(true);
    }

    private function newId(): string
    {
        return bin2hex(random_bytes(12));
    }

    private function newCode(): string
    {
        $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $len = strlen($alphabet);
        for ($attempt = 0; $attempt < 16; $attempt++) {
            $code = '';
            for ($i = 0; $i < 4; $i++) {
                $code .= $alphabet[random_int(0, $len - 1)];
            }
            $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
            $exists->execute([$code]);
            if (!$exists->fetch()) {
                return $code;
            }
        }
        throw new RuntimeException('Kon geen unieke lobbycode maken.');
    }

    public function lobbyForUser(string $userId): ?array
    {
        $stmt = $this->pdo->prepare(
            'SELECT l.* FROM lobbies l
             JOIN members m ON m.lobby_id = l.id
             WHERE m.user_id = ? AND m.left_at IS NULL
             ORDER BY l.created DESC LIMIT 1'
        );
        $stmt->execute([$userId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function getLobby(string $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function getLobbyByCode(string $code): ?array
    {
        $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
        $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
        $stmt->execute([$code]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    /** @return list<array> */
    public function members(string $lobbyId, bool $includeLeft = false): array
    {
        $sql = 'SELECT * FROM members WHERE lobby_id = ?';
        if (!$includeLeft) {
            $sql .= ' AND left_at IS NULL';
        }
        $sql .= ' ORDER BY joined ASC';
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$lobbyId]);
        return $stmt->fetchAll();
    }

    public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
    {
        return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
            $existing = $this->lobbyForUser($userId);
            if ($existing && $existing['status'] !== 'finished') {
                throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
            }
            if ($existing && $existing['status'] === 'finished') {
                $this->leaveMember($existing['id'], $userId);
            }
            $id = $this->newId();
            $code = $this->newCode();
            $now = $this->now();
            $miss = max(0.0, min(1.0, $missChance));
            $this->pdo->prepare(
                'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
                 VALUES (?,?,?,?,?,?,?)'
            )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
            $choice = $this->choosePlanet($userId, $planetId, false);
            $this->pdo->prepare(
                'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
                 VALUES (?,?,?,0,?,?,?,?)'
            )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
            return $this->getLobby($id);
        });
    }

    public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
    {
        return $this->transaction(function () use ($userId, $name, $code, $planetId) {
            $existing = $this->lobbyForUser($userId);
            if ($existing && $existing['status'] !== 'finished') {
                if (strcasecmp($existing['code'], $code) === 0) {
                    return $existing;
                }
                throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
            }
            $lobby = $this->getLobbyByCode($code);
            if (!$lobby) {
                throw new RuntimeException('Onbekende lobbycode.');
            }
            if ($lobby['status'] !== 'waiting') {
                throw new RuntimeException('Deze lobby is al begonnen.');
            }
            $members = $this->members($lobby['id']);
            if (count($members) >= METEORS_MAX_PLAYERS) {
                throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
            }
            $now = $this->now();
            $choice = $this->choosePlanet($userId, $planetId, false);
            $this->pdo->prepare(
                'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
                 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
                 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
                    name = excluded.name,
                    ready = 0,
                    eliminated = 0,
                    place = NULL,
                    left_at = NULL,
                    joined = excluded.joined,
                    last_seen = excluded.last_seen,
                    score = 0,
                    snapshot = NULL,
                    planet_id = excluded.planet_id,
                    planet_json = excluded.planet_json'
            )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
            return $this->getLobby($lobby['id']);
        });
    }

    private function leaveMember(string $lobbyId, string $userId): void
    {
        $this->pdo->prepare(
            'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
        )->execute([$this->now(), $lobbyId, $userId]);
        $lobby = $this->getLobby($lobbyId);
        if (!$lobby) {
            return;
        }
        $remaining = $this->members($lobbyId);
        if ($lobby['host_id'] === $userId) {
            if ($remaining) {
                $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
                    ->execute([$remaining[0]['user_id'], $lobbyId]);
            } elseif ($lobby['status'] === 'waiting') {
                // Empty waiting lobby can stay; a later join by code still works until we want to close it.
            }
        }
        if ($lobby['status'] === 'playing') {
            $this->assignPlaceIfNeeded($lobbyId, $userId, true);
            $this->maybeFinish($lobbyId);
        }
    }

    public function leaveLobby(string $userId): void
    {
        $this->transaction(function () use ($userId) {
            $lobby = $this->lobbyForUser($userId);
            if (!$lobby) {
                return;
            }
            $this->leaveMember($lobby['id'], $userId);
        });
    }

    public function setReady(string $userId, bool $ready): array
    {
        return $this->transaction(function () use ($userId, $ready) {
            $lobby = $this->lobbyForUser($userId);
            if (!$lobby) {
                throw new RuntimeException('Je zit niet in een lobby.');
            }
            if ($lobby['status'] !== 'waiting') {
                throw new RuntimeException('Het spel is al begonnen.');
            }
            $this->pdo->prepare(
                'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
            )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
            return $this->getLobby($lobby['id']);
        });
    }

    public function startGame(string $userId): array
    {
        return $this->transaction(function () use ($userId) {
            $lobby = $this->lobbyForUser($userId);
            if (!$lobby) {
                throw new RuntimeException('Je zit niet in een lobby.');
            }
            if ($lobby['host_id'] !== $userId) {
                throw new RuntimeException('Alleen de host kan het spel starten.');
            }
            if ($lobby['status'] !== 'waiting') {
                throw new RuntimeException('Het spel is al begonnen.');
            }
            $members = $this->members($lobby['id']);
            if (count($members) < 2) {
                throw new RuntimeException('Er zijn minstens twee spelers nodig.');
            }
            foreach ($members as $m) {
                if (!(int) $m['ready']) {
                    throw new RuntimeException('Niet iedereen is gereed.');
                }
            }
            $this->pdo->prepare(
                'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
            )->execute(['playing', $this->now(), $lobby['id']]);
            $this->pdo->prepare(
                'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
                 WHERE lobby_id = ? AND left_at IS NULL'
            )->execute([$lobby['id']]);
            $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
            return $this->getLobby($lobby['id']);
        });
    }

    /** @param list<array{client_id?:string,color?:int}> $shots */
    public function setPlanet(string $userId, string $planetId): array
    {
        return $this->transaction(function () use ($userId, $planetId) {
            $lobby = $this->lobbyForUser($userId);
            if (!$lobby) {
                throw new RuntimeException('Je zit in geen lobby.');
            }
            if ($lobby['status'] !== 'waiting') {
                throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
            }
            $choice = $this->choosePlanet($userId, $planetId, true);
            $this->pdo->prepare(
                'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
            )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
            return $this->getLobby($lobby['id']);
        });
    }

    /** @param array<string,mixed> $member */
    public function missChanceForMember(array $member): float
    {
        if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
            return max(0.0, min(1.0, $this->testMissOverride));
        }
        if (!empty($member['planet_json'])) {
            $data = json_decode((string) $member['planet_json'], true);
            if (is_array($data)) {
                return Planets::missChance($data);
            }
        }
        $id = (string) ($member['planet_id'] ?? Planets::defaultId());
        return Planets::missChanceForId($id);
    }

    /** @var ?float Tests may force a miss chance without changing the catalog. */
    public ?float $testMissOverride = null;

    public function recordShots(string $userId, array $shots): array
    {
        return $this->transaction(function () use ($userId, $shots) {
            $lobby = $this->lobbyForUser($userId);
            if (!$lobby || $lobby['status'] !== 'playing') {
                return [];
            }
            $me = $this->member($lobby['id'], $userId);
            if (!$me || (int) $me['eliminated']) {
                return [];
            }
            $targets = [];
            foreach ($this->members($lobby['id']) as $m) {
                if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
                    $targets[] = $m;
                }
            }
            $results = [];
            $missChance = $this->missChanceForMember($me);
            $flight = (float) $lobby['flight_duration'];
            $now = $this->nowf();
            $ins = $this->pdo->prepare(
                'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y)
                 VALUES (?,?,?,?,?,?,?,0,?,?,?)'
            );
            foreach ($shots as $shot) {
                $color = isset($shot['color']) ? (int) $shot['color'] : -1;
                $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
                $fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null;
                $fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null;
                $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
                $to = null;
                $toName = null;
                $landCol = null;
                if (!$miss) {
                    $pick = $targets[random_int(0, count($targets) - 1)];
                    $to = $pick['user_id'];
                    $toName = $pick['name'];
                    $landCol = random_int(0, 9);
                }
                $deliver = $now + $flight;
                $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]);
                $results[] = [
                    'id' => (int) $this->pdo->lastInsertId(),
                    'client_id' => $clientId,
                    'from_id' => $userId,
                    'from_user' => $userId,
                    'miss' => $miss,
                    'target_id' => $to,
                    'target_name' => $toName,
                    'deliver_at' => $deliver,
                    'color' => $color,
                    'flight_duration' => $flight,
                    'age' => 0.0,
                    'land_col' => $landCol,
                    'col' => $fromCol,
                    'y' => $fromY,
                ];
            }
            return $results;
        });
    }

    /** @return list<array> undelivered shots whose time has come, marked delivered. */
    public function takeIncoming(string $lobbyId, string $userId): array
    {
        $now = $this->nowf();
        $stmt = $this->pdo->prepare(
            'SELECT * FROM shots
             WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
             ORDER BY deliver_at ASC, id ASC'
        );
        $stmt->execute([$lobbyId, $userId, $now]);
        $rows = $stmt->fetchAll();
        if (!$rows) {
            return [];
        }
        $ids = array_column($rows, 'id');
        $in = implode(',', array_fill(0, count($ids), '?'));
        $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
        $incoming = [];
        foreach ($rows as $r) {
            $incoming[] = [
                'id' => (int) $r['id'],
                'color' => (int) $r['color'],
                'from_user' => $r['from_user'],
                'client_id' => $r['client_id'],
                'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
                'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
                'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
            ];
        }
        return $incoming;
    }

    public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
    {
        $lobby = $this->lobbyForUser($userId);
        if (!$lobby || $lobby['status'] !== 'playing') {
            return;
        }
        $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
        $fields = 'last_seen = ?';
        $args = [$this->now()];
        if ($json !== null) {
            $fields .= ', snapshot = ?';
            $args[] = $json;
        }
        if ($score !== null) {
            $fields .= ', score = ?';
            $args[] = $score;
        }
        $args[] = $lobby['id'];
        $args[] = $userId;
        $this->pdo->prepare(
            "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
        )->execute($args);
        if ($eliminated) {
            $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
            $this->maybeFinish($lobby['id']);
        }
    }

    public function member(string $lobbyId, string $userId): ?array
    {
        $stmt = $this->pdo->prepare(
            'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
        );
        $stmt->execute([$lobbyId, $userId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
    {
        $m = $this->member($lobbyId, $userId);
        if (!$m || $m['place'] !== null) {
            return;
        }
        $active = 0;
        foreach ($this->members($lobbyId) as $row) {
            if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
                $active++;
            }
        }
        // First out gets last place = number of current (incl. this) non-left players.
        $total = count($this->members($lobbyId));
        $alreadyPlaced = 0;
        foreach ($this->members($lobbyId, true) as $row) {
            if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
                if ($row['place'] !== null) {
                    $alreadyPlaced++;
                }
            }
        }
        $place = $active + 1; // remaining others + self → this player's place
        $this->pdo->prepare(
            'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
        )->execute([$place, $lobbyId, $userId]);
    }

    public function maybeFinish(string $lobbyId): void
    {
        $lobby = $this->getLobby($lobbyId);
        if (!$lobby || $lobby['status'] !== 'playing') {
            return;
        }
        $alive = [];
        foreach ($this->members($lobbyId) as $m) {
            if (!(int) $m['eliminated']) {
                $alive[] = $m;
            }
        }
        if (count($alive) > 1) {
            return;
        }
        if (count($alive) === 1) {
            $winner = $alive[0];
            if ($winner['place'] === null) {
                $this->pdo->prepare(
                    'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
                )->execute([$lobbyId, $winner['user_id']]);
            }
        }
        $this->pdo->prepare(
            'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
        )->execute(['finished', $this->now(), $lobbyId]);
    }

    public function maybeResetLobby(string $lobbyId): void
    {
        $lobby = $this->getLobby($lobbyId);
        if (!$lobby || $lobby['status'] !== 'finished') {
            return;
        }
        $finished = (int) ($lobby['finished'] ?? 0);
        if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
            return;
        }
        $this->pdo->prepare(
            'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
        )->execute(['waiting', $lobbyId]);
        $this->pdo->prepare(
            'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
             WHERE lobby_id = ? AND left_at IS NULL'
        )->execute([$lobbyId]);
        $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
    }

    /**
     * Shots still (or just) in flight, for every client in the lobby (t1125).
     * `age` is seconds since `created`, so a late poll can join mid-arc.
     * Window is flight_duration + 0.8 s (one poll slack).
     *
     * @return list<array>
     */
    public function recentFlights(string $lobbyId, ?float $flightDuration = null): array
    {
        $flight = $flightDuration !== null ? (float) $flightDuration : (float) METEORS_FLIGHT_DURATION;
        $now = $this->nowf();
        $window = $flight + 0.8;
        $stmt = $this->pdo->prepare(
            'SELECT * FROM shots
             WHERE lobby_id = ? AND created >= ?
             ORDER BY id ASC'
        );
        $stmt->execute([$lobbyId, $now - $window]);
        $out = [];
        foreach ($stmt->fetchAll() as $r) {
            $to = $r['to_user'];
            $out[] = [
                'id' => (int) $r['id'],
                'client_id' => $r['client_id'],
                'from_id' => $r['from_user'],
                'from_user' => $r['from_user'],
                'target_id' => $to,
                'miss' => $to === null || $to === '',
                'color' => (int) $r['color'],
                'flight_duration' => $flight,
                'age' => $now - (float) $r['created'],
                'deliver_at' => (float) $r['deliver_at'],
                'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
                'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
                'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
            ];
        }
        return $out;
    }

    /** Public view of a lobby for the given user, including incoming shots. */
    public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
    {
        return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
            $touch = $this->lobbyForUser($userId);
            if ($touch && $touch['status'] === 'finished') {
                $this->maybeResetLobby($touch['id']);
            }
            if ($touch && $touch['status'] === 'playing') {
                if ($snapshot !== null || $score !== null || $eliminated) {
                    $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
                } else {
                    $this->pdo->prepare(
                        'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
                    )->execute([$this->now(), $touch['id'], $userId]);
                }
            }
            $shotResults = [];
            if ($outgoing && $touch && $touch['status'] === 'playing') {
                $shotResults = $this->recordShots($userId, $outgoing);
            }
            $lobby = $this->lobbyForUser($userId);
            if (!$lobby) {
                return [
                    'lobby' => null,
                    'incoming' => [],
                    'shot_results' => $shotResults,
                    'shot_flights' => [],
                ];
            }
            $incoming = [];
            if ($lobby['status'] === 'playing') {
                $incoming = $this->takeIncoming($lobby['id'], $userId);
            }
            $flights = [];
            if ($lobby['status'] === 'playing') {
                $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
            }
            $this->maybeAwardOnlineLobby($lobby);
            return [
                'lobby' => $this->presentLobby($lobby, $userId),
                'incoming' => $incoming,
                'shot_results' => $shotResults,
                'shot_flights' => $flights,
            ];
        });
    }

    public function presentLobby(array $lobby, string $userId): array
    {
        $members = $this->members($lobby['id']);
        $players = [];
        foreach ($members as $m) {
            $snap = null;
            if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
                $decoded = json_decode($m['snapshot'], true);
                $snap = is_array($decoded) ? $decoded : null;
            }
            $players[] = [
                'id' => $m['user_id'],
                'name' => $m['name'],
                'ready' => (bool) (int) $m['ready'],
                'eliminated' => (bool) (int) $m['eliminated'],
                'place' => $m['place'] !== null ? (int) $m['place'] : null,
                'is_host' => $m['user_id'] === $lobby['host_id'],
                'is_me' => $m['user_id'] === $userId,
                'score' => (int) $m['score'],
                'snapshot' => $m['user_id'] === $userId ? null : $snap,
                'planet' => $this->presentMemberPlanet($m),
            ];
        }
        $rankings = [];
        if ($lobby['status'] === 'finished' || $lobby['finished']) {
            $all = $this->members($lobby['id'], true);
            foreach ($all as $m) {
                if ($m['place'] !== null) {
                    $rankings[] = [
                        'place' => (int) $m['place'],
                        'id' => $m['user_id'],
                        'name' => $m['name'],
                        'score' => (int) $m['score'],
                    ];
                }
            }
            usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
        }
        $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
        return [
            'id' => $lobby['id'],
            'code' => $lobby['code'],
            'status' => $lobby['status'],
            'host_id' => $lobby['host_id'],
            'miss_chance' => (float) $lobby['miss_chance'],
            'flight_duration' => (float) $lobby['flight_duration'],
            'players' => $players,
            'all_ready' => $allReady,
            'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
            'rankings' => $rankings,
            'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
            'podium_seconds' => METEORS_PODIUM_SECONDS,
        ];
    }

    public const MAX_CUSTOM_PLANETS = 30;
    public const MAX_GAME_POINTS = 10000;
    public const MAX_POINTS_PER_SEC = 4.0;
    public const MIN_PLAY_SECONDS = 3;
    public const PLAY_TOKEN_TTL = 21600;
    public const NAME_MAX = 32;

    /** @return array{planet_id:string,planet_json:?string} */
    public function choosePlanet(string $userId, string $planetId, bool $strict): array
    {
        if ($planetId === '') {
            if ($strict) {
                throw new RuntimeException('Onbekende planeet.');
            }
            return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
        }
        if (Planets::known($planetId)) {
            return ['planet_id' => $planetId, 'planet_json' => null];
        }
        $row = $this->ownedCustom($userId, $planetId);
        if ($row) {
            return [
                'planet_id' => $planetId,
                'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
            ];
        }
        if ($strict) {
            throw new RuntimeException('Onbekende planeet.');
        }
        return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
    }

    /** @param array<string,mixed> $member */
    public function presentMemberPlanet(array $member): array
    {
        if (!empty($member['planet_json'])) {
            $data = json_decode((string) $member['planet_json'], true);
            if (is_array($data) && !empty($data['id'])) {
                return Planets::presentData($data);
            }
        }
        return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
    }

    public function ensureProfile(string $userId): array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
        $stmt->execute([$userId]);
        $row = $stmt->fetch();
        if ($row) {
            return $row;
        }
        $now = $this->now();
        $this->pdo->prepare(
            'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
        )->execute([$userId, $now]);
        return [
            'user_id' => $userId,
            'lifetime_points' => 0,
            'locale' => null,
            'updated' => $now,
        ];
    }

    public function lifetimePoints(string $userId): int
    {
        return (int) $this->ensureProfile($userId)['lifetime_points'];
    }

    public function locale(string $userId): ?string
    {
        $v = $this->ensureProfile($userId)['locale'] ?? null;
        return is_string($v) && $v !== '' ? $v : null;
    }

    /** @var list<string> */
    public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];

    public function setLocale(string $userId, string $locale): string
    {
        $locale = strtolower($locale);
        if (!in_array($locale, self::LOCALES, true)) {
            throw new RuntimeException('Onbekende taal.');
        }
        $this->ensureProfile($userId);
        $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
            ->execute([$locale, $this->now(), $userId]);
        return $locale;
    }

    /**
     * Last chosen planet (t1196): a standard planet id or one of the
     * user's own custom planets. Returns null when nothing is stored or the
     * stored custom planet no longer exists (graceful fallback).
     */
    public function lastPlanet(string $userId): ?string
    {
        $v = $this->ensureProfile($userId)['last_planet'] ?? null;
        if (!is_string($v) || $v === '') {
            return null;
        }
        if (Planets::known($v) || $this->ownedCustom($userId, $v)) {
            return $v;
        }
        return null;
    }

    public function setLastPlanet(string $userId, string $planetId): string
    {
        $planetId = trim($planetId);
        if ($planetId === '' || strlen($planetId) > 64
            || !(Planets::known($planetId) || $this->ownedCustom($userId, $planetId))) {
            throw new RuntimeException('Onbekende planeet.');
        }
        $this->ensureProfile($userId);
        $this->pdo->prepare('UPDATE profiles SET last_planet = ?, updated = ? WHERE user_id = ?')
            ->execute([$planetId, $this->now(), $userId]);
        return $planetId;
    }

    /**
     * Add points once for a unique award_key. Returns the new lifetime total.
     * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
     */
    public function awardPoints(string $userId, int $points, string $key, string $mode): int
    {
        return $this->transaction(function () use ($userId, $points, $key, $mode) {
            $this->ensureProfile($userId);
            $points = max(0, min(self::MAX_GAME_POINTS, $points));
            $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
            $stmt->execute([$key]);
            if ($stmt->fetch()) {
                return $this->lifetimePoints($userId);
            }
            $this->pdo->prepare(
                'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
            )->execute([$key, $userId, $mode, $points, $this->now()]);
            if ($points > 0) {
                $this->pdo->prepare(
                    'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
                )->execute([$points, $this->now(), $userId]);
            }
            return $this->lifetimePoints($userId);
        });
    }

    public function playBegin(string $userId, string $mode): array
    {
        if (!in_array($mode, ['solo', 'offline'], true)) {
            throw new RuntimeException('Onbekende speelmodus.');
        }
        $token = bin2hex(random_bytes(16));
        $this->pdo->prepare(
            'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
        )->execute([$token, $userId, $mode, $this->now()]);
        return ['token' => $token, 'started' => $this->now()];
    }

    public function playFinish(string $userId, string $token, int $score): array
    {
        return $this->transaction(function () use ($userId, $token, $score) {
            $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
            $stmt->execute([$token]);
            $ses = $stmt->fetch();
            if (!$ses || $ses['user_id'] !== $userId) {
                throw new RuntimeException('Ongeldige speelsessie.');
            }
            $key = 'play:' . $token;
            if ($ses['finished'] !== null) {
                return [
                    'lifetime_points' => $this->lifetimePoints($userId),
                    'awarded' => 0,
                    'already' => true,
                ];
            }
            $now = $this->now();
            $started = (int) $ses['started'];
            if ($now - $started > self::PLAY_TOKEN_TTL) {
                $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
                    ->execute([$now, $token]);
                throw new RuntimeException('Speelsessie is verlopen.');
            }
            $duration = max(0, $now - $started);
            $score = max(0, $score);
            $awarded = 0;
            if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
                $awarded = 0;
            } else {
                $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
                $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
            }
            $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
                ->execute([$now, $token]);
            $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
            return [
                'lifetime_points' => $total,
                'awarded' => $awarded,
                'already' => false,
            ];
        });
    }

    /** @param array<string,mixed> $lobby */
    public function maybeAwardOnlineLobby(array $lobby): void
    {
        $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
        foreach ($this->members($lobby['id'], true) as $m) {
            if (!$finished && empty($m['eliminated'])) {
                continue;
            }
            $uid = (string) $m['user_id'];
            $key = 'online:' . $lobby['id'] . ':' . $uid;
            $this->awardPoints($uid, (int) $m['score'], $key, 'online');
        }
    }

    /** @return ?array<string,mixed> */
    public function ownedCustom(string $userId, string $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
        $stmt->execute([$id, $userId]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    /** @return list<array<string,mixed>> */
    public function listCustomPlanets(string $userId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
        );
        $stmt->execute([$userId]);
        $out = [];
        foreach ($stmt->fetchAll() as $row) {
            $out[] = $this->snapshotCustom($row);
        }
        return $out;
    }

    public static function sanitizeName(string $raw, string $field): string
    {
        $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
        $s = strip_tags($s);
        if ($s === '') {
            throw new RuntimeException('Vul een ' . $field . ' in.');
        }
        if (mb_strlen($s) > self::NAME_MAX) {
            $s = mb_substr($s, 0, self::NAME_MAX);
        }
        return $s;
    }

    /**
     * Create or update a custom planet owned by $userId.
     * @param array<string,mixed> $data
     * @return array<string,mixed> snapshot
     */
    public function saveCustomPlanet(string $userId, array $data): array
    {
        return $this->transaction(function () use ($userId, $data) {
            $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
            $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
            $j = Planets::clampGravity((float) ($data['jumpsToClear'] ?? 2));
            $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
            $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
            $ids = $data['colors'] ?? $data['blocks'] ?? [];
            if (!is_array($ids) || count($ids) !== 5) {
                throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
            }
            $points = $this->lifetimePoints($userId);
            $blockIds = [];
            foreach ($ids as $entry) {
                if (is_array($entry)) {
                    $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
                } else {
                    $bid = (string) $entry;
                }
                if ($bid === '' || !Blocks::known($bid)) {
                    throw new RuntimeException('Onbekend blokje.');
                }
                if (!Blocks::unlockedId($bid, $points)) {
                    throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
                }
                if (in_array($bid, $blockIds, true)) {
                    throw new RuntimeException('Elk blokje mag maar in één vak.');
                }
                $blockIds[] = $bid;
            }
            $now = $this->now();
            $id = isset($data['id']) ? (string) $data['id'] : '';
            if ($id !== '') {
                $row = $this->ownedCustom($userId, $id);
                if (!$row) {
                    throw new RuntimeException('Onbekende planeet.');
                }
                $this->pdo->prepare(
                    'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
                )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
            } else {
                $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
                $stmt->execute([$userId]);
                if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
                    throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
                }
                $id = 'c_' . bin2hex(random_bytes(8));
                $this->pdo->prepare(
                    'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
                     VALUES (?,?,?,?,?,?,?,?,?,?)'
                )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
            }
            $row = $this->ownedCustom($userId, $id);
            if (!$row) {
                throw new RuntimeException('Opslaan is mislukt.');
            }
            return $this->snapshotCustom($row);
        });
    }

    public function deleteCustomPlanet(string $userId, string $id): void
    {
        $row = $this->ownedCustom($userId, $id);
        if (!$row) {
            throw new RuntimeException('Onbekende planeet.');
        }
        $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
            ->execute([$id, $userId]);
    }

    /** @param array<string,mixed> $row */
    public function snapshotCustom(array $row): array
    {
        $ids = json_decode((string) $row['colors'], true);
        if (!is_array($ids)) {
            $ids = [];
        }
        $colors = [];
        foreach ($ids as $i => $id) {
            $c = Blocks::asColor((string) $id, (int) $i);
            if ($c === null) {
                continue;
            }
            $colors[] = $c;
        }
        $p = [
            'id' => (string) $row['id'],
            'name' => (string) $row['name'],
            'people' => (string) $row['people'],
            // t1199: old custom planets below 2 clamp up on load.
            'jumpsToClear' => Planets::clampGravity((float) $row['jumps_to_clear']),
            'fallTime' => (float) $row['fall_time'],
            'riseTime' => (float) $row['rise_time'],
            'colors' => $colors,
            'custom' => true,
            'owner_id' => (string) $row['user_id'],
        ];
        return Planets::presentData($p);
    }

    public function profilePayload(string $userId): array
    {
        $points = $this->lifetimePoints($userId);
        return [
            'lifetime_points' => $points,
            'locale' => $this->locale($userId),
            'last_planet' => $this->lastPlanet($userId),
            'blocks' => Blocks::present($points),
            'planets' => $this->listCustomPlanets($userId),
        ];
    }

    private static function clampFloat(float $value, float $lo, float $hi): float
    {
        return max($lo, min($hi, $value));
    }


}
