<?php
declare(strict_types=1);
require __DIR__ . '/lib/bootstrap.php';
require __DIR__ . '/lib/Store.php';

$action = $_GET['action'] ?? $_POST['action'] ?? '';
if ($action === '') {
    $body = readJsonBody();
    $action = (string) ($body['action'] ?? '');
} else {
    $body = readJsonBody();
}

try {
    $configured = authConfigured();
    $local = localDev();
    $user = currentUser();

    if ($action === 'me' || $action === '') {
        $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
        $profile = [
            'lifetime_points' => 0,
            'locale' => null,
            'last_planet' => null,
            'blocks' => [],
            'planets' => [],
        ];
        if ($user) {
            $store = Store::open();
            $view = $store->viewFor($user['id']);
            $profile = $store->profilePayload($user['id']);
        }
        jsonOut([
            'ok' => true,
            'configured' => $configured,
            'local' => $local,
            'csrf' => csrfToken(),
            'me' => $user,
            'lobby' => $view['lobby'],
            'incoming' => $view['incoming'],
            'shot_results' => $view['shot_results'],
            'shot_flights' => $view['shot_flights'] ?? [],
            'miss_chance_default' => METEORS_DEFAULT_MISS,
            'flight_duration' => METEORS_FLIGHT_DURATION,
            'login_url' => 'auth.php',
            'logout_url' => 'logout.php',
            'lifetime_points' => $profile['lifetime_points'],
            'locale' => $profile['locale'],
            'last_planet' => $profile['last_planet'],
            'blocks' => $profile['blocks'],
            'planets' => $profile['planets'],
        ]);
    }

    if ($action === 'test_login') {
        if (!localDev()) {
            jsonFail('Niet beschikbaar.', 403);
        }
        requireCsrf();
        $who = (string) ($body['user'] ?? $_GET['user'] ?? '');
        if (!in_array($who, ['test_user_1', 'test_user_2'], true)) {
            jsonFail('Onbekende testgebruiker.');
        }
        loginUser('local:' . $who, $who);
        jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
    }

    if (!$user && $action !== 'me') {
        jsonFail('Log in om verder te gaan.', 401);
    }

    requireCsrf();
    $store = Store::open();
    $userId = $user['id'];
    $name = $user['name'];

    switch ($action) {
        case 'lobby_create':
            $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
            $planet = (string) ($body['planet_id'] ?? '');
            $lobby = $store->createLobby($userId, $name, $miss, $planet);
            jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);

        case 'lobby_join':
            $code = (string) ($body['code'] ?? '');
            $planet = (string) ($body['planet_id'] ?? '');
            $lobby = $store->joinLobby($userId, $name, $code, $planet);
            jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);

        case 'lobby_set_planet':
            $planet = (string) ($body['planet_id'] ?? '');
            $lobby = $store->setPlanet($userId, $planet);
            jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);

        case 'lobby_leave':
            $store->leaveLobby($userId);
            jsonOut(['ok' => true, 'lobby' => null, 'csrf' => csrfToken()]);

        case 'lobby_ready':
            $ready = (bool) ($body['ready'] ?? true);
            $lobby = $store->setReady($userId, $ready);
            jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);

        case 'lobby_start':
            $lobby = $store->startGame($userId);
            jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);

        case 'poll':
            $snapshot = isset($body['snapshot']) && is_array($body['snapshot']) ? $body['snapshot'] : null;
            $score = isset($body['score']) ? (int) $body['score'] : null;
            $eliminated = !empty($body['eliminated']);
            $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
            $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
            $profile = $store->profilePayload($userId);
            jsonOut([
                'ok' => true,
                'csrf' => csrfToken(),
                'me' => $user,
                'lobby' => $view['lobby'],
                'incoming' => $view['incoming'],
                'shot_results' => $view['shot_results'],
                'shot_flights' => $view['shot_flights'] ?? [],
                'lifetime_points' => $profile['lifetime_points'],
                'locale' => $profile['locale'],
                'last_planet' => $profile['last_planet'],
                'blocks' => $profile['blocks'],
                'planets' => $profile['planets'],
            ]);

        case 'play_begin':
            $mode = (string) ($body['mode'] ?? 'solo');
            $ses = $store->playBegin($userId, $mode);
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);

        case 'play_finish':
            $token = (string) ($body['token'] ?? '');
            $score = isset($body['score']) ? (int) $body['score'] : 0;
            $result = $store->playFinish($userId, $token, $score);
            jsonOut([
                'ok' => true,
                'csrf' => csrfToken(),
                'lifetime_points' => $result['lifetime_points'],
                'awarded' => $result['awarded'],
                'already' => $result['already'],
                'blocks' => Blocks::present($result['lifetime_points']),
            ]);

        case 'planet_save':
            $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
            jsonOut([
                'ok' => true,
                'csrf' => csrfToken(),
                'planet' => $snap,
                'planets' => $store->listCustomPlanets($userId),
            ]);

        case 'planet_delete':
            $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
            jsonOut([
                'ok' => true,
                'csrf' => csrfToken(),
                'planets' => $store->listCustomPlanets($userId),
            ]);

        case 'set_last_planet':
            $pid = $store->setLastPlanet($userId, (string) ($body['planet_id'] ?? ''));
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'last_planet' => $pid]);

        case 'set_locale':
            $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
            jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);

        default:
            jsonFail('Onbekende actie.', 404);
    }
} catch (RuntimeException $e) {
    jsonFail($e->getMessage(), 400);
} catch (Throwable $e) {
    jsonFail('Interne fout.', 500);
}
