<?php
declare(strict_types=1);

const METEORS_SESSION_TTL = 86400;
const METEORS_DEFAULT_AUTH = 'https://auth.timfalken.com';
const METEORS_DEFAULT_CLIENT_ID = 'projects.timfalken.com';
const METEORS_DEFAULT_BASE = 'https://projects.timfalken.com/meteors';
const METEORS_DEFAULT_MISS = 0.30;
const METEORS_FLIGHT_DURATION = 1.2;
const METEORS_MAX_PLAYERS = 32;
const METEORS_PODIUM_SECONDS = 5;

function dataDir(): string
{
    $override = getenv('METEORS_DATA_DIR');
    if (is_string($override) && $override !== '') {
        return rtrim($override, '/');
    }
    return dirname(__DIR__) . '/data';
}

function ensureDataDir(): string
{
    $dir = dataDir();
    if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new RuntimeException('De datamap moet schrijfbaar zijn.');
    }
    $deny = $dir . '/.htaccess';
    if (!is_file($deny)) {
        @file_put_contents($deny, "Require all denied\n");
    }
    $sessions = $dir . '/sessions';
    if (!is_dir($sessions)) {
        @mkdir($sessions, 0775, true);
    }
    return $dir;
}

function localDev(): bool
{
    $host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
    return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
        && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
}

function config(): array
{
    $dir = ensureDataDir();
    $path = $dir . '/config.php';
    $lock = fopen($dir . '/config.lock', 'c');
    if ($lock === false) {
        throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
    }
    try {
        if (!flock($lock, LOCK_EX)) {
            throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
        }
        if (!is_file($path)) {
            $template = <<<'PHP'
<?php
// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.
// Productie-URL: https://projects.timfalken.com/meteors
// client_id is het geregistreerde domein: projects.timfalken.com.
// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim
// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).
// Voeg daar ook het callback-pad /meteors/callback.php toe.
// Dit bestand wordt niet gedeployed en staat niet in git.
return [
    'auth_url' => 'https://auth.timfalken.com',
    'base_url' => 'https://projects.timfalken.com/meteors',
    'client_id' => 'projects.timfalken.com',
    'client_secret' => '',
];
PHP;
            if (file_put_contents($path, $template) !== strlen($template)) {
                throw new RuntimeException('data/config.php kon niet worden gemaakt.');
            }
        }
        $values = require $path;
        if (!is_array($values)) {
            throw new RuntimeException('data/config.php moet een array teruggeven.');
        }
    } finally {
        flock($lock, LOCK_UN);
        fclose($lock);
    }
    foreach ([
        'auth_url' => 'METEORS_AUTH_URL',
        'base_url' => 'METEORS_BASE_URL',
        'client_id' => 'METEORS_CLIENT_ID',
        'client_secret' => 'METEORS_CLIENT_SECRET',
    ] as $key => $env) {
        if (($values[$key] ?? '') === '') {
            $values[$key] = getenv($env) ?: '';
        }
    }
    if (($values['auth_url'] ?? '') === '') {
        $values['auth_url'] = METEORS_DEFAULT_AUTH;
    }
    if (($values['client_id'] ?? '') === '') {
        $values['client_id'] = METEORS_DEFAULT_CLIENT_ID;
    }
    return $values;
}

function authConfigured(): bool
{
    $c = config();
    return ($c['client_secret'] ?? '') !== ''
        && ($c['client_id'] ?? '') !== ''
        && ($c['base_url'] ?? '') !== '';
}

function baseUrl(): string
{
    if (localDev()) {
        $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
        if ($dir === '/' || $dir === '.') {
            $dir = '';
        }
        return 'http://' . $_SERVER['HTTP_HOST'] . $dir;
    }
    $base = rtrim((string) (config()['base_url'] ?? ''), '/');
    if (!str_starts_with($base, 'https://')) {
        throw new RuntimeException(
            "Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "
            . '(https://projects.timfalken.com/meteors), of zet METEORS_BASE_URL.'
        );
    }
    return $base;
}

function authUrl(): string
{
    $url = rtrim((string) (config()['auth_url'] ?? METEORS_DEFAULT_AUTH), '/');
    return $url !== '' ? $url : METEORS_DEFAULT_AUTH;
}

function authRequest(string $path, ?array $form = null, ?string $token = null): array
{
    $ch = curl_init(authUrl() . $path);
    $headers = ['Accept: application/json', 'User-Agent: Meteors/1.0'];
    if ($token) {
        $headers[] = 'Authorization: Bearer ' . $token;
    }
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => $headers,
    ]);
    if ($form !== null) {
        curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
    }
    $body = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $err = curl_error($ch);
    curl_close($ch);
    $data = is_string($body) ? json_decode($body, true) : null;
    if ($status !== 200 || !is_array($data)) {
        $hint = $err !== '' ? ' (' . $err . ')' : '';
        throw new RuntimeException(
            'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint
        );
    }
    return $data;
}

/** Safe profile-picture URL from auth (https/http or a same-origin path). */
function safeAvatarUrl($url): ?string
{
    if (!is_string($url)) {
        return null;
    }
    $url = trim($url);
    if ($url === '' || strlen($url) > 500) {
        return null;
    }
    if (preg_match('#^(javascript|vbscript|data):#i', $url)) {
        return null;
    }
    if (preg_match('#^https?://#i', $url) || str_starts_with($url, '/')) {
        return $url;
    }
    return null;
}

/**
 * True when $name is missing or only the numeric auth id (e.g. user
 * auth:3 shown as "3"). Local test usernames like test_user_1 are real.
 */
function isPlaceholderName(string $userId, ?string $name): bool
{
    $name = trim((string) $name);
    if ($name === '' || strcasecmp($name, 'Player') === 0) {
        return true;
    }
    if (str_starts_with($userId, 'auth:')) {
        $num = substr($userId, 5);
        return $name === $num || $name === $userId;
    }
    return false;
}

/**
 * Map an auth.timfalken.com OIDC locale claim (BCP 47, e.g. zh-Hans)
 * to a Meteors locale id (zh). Unknown values become null.
 */
function normalizeAuthLocale($claim): ?string
{
    if (!is_string($claim) || $claim === '') {
        return null;
    }
    $id = strtolower(str_replace('_', '-', trim($claim)));
    if ($id === 'zh-hans' || $id === 'zh-cn' || $id === 'zh-sg' || $id === 'zh-my') {
        return 'zh';
    }
    $known = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
    if (in_array($id, $known, true)) {
        return $id;
    }
    $primary = explode('-', $id, 2)[0];
    return in_array($primary, $known, true) ? $primary : null;
}

/** Locale claim from a token or /api/me payload (user.locale or locale). */
function authLocaleFromPayload($data): ?string
{
    if (!is_array($data)) {
        return null;
    }
    if (isset($data['user']) && is_array($data['user'])) {
        $fromUser = normalizeAuthLocale($data['user']['locale'] ?? null);
        if ($fromUser !== null) {
            return $fromUser;
        }
    }
    return normalizeAuthLocale($data['locale'] ?? null);
}

function storeAuthLocale(?string $claim): ?string
{
    $id = normalizeAuthLocale($claim);
    if ($id === null) {
        unset($_SESSION['auth_locale']);
        return null;
    }
    $_SESSION['auth_locale'] = $id;
    return $id;
}

function sessionAuthLocale(): ?string
{
    return normalizeAuthLocale($_SESSION['auth_locale'] ?? null);
}

/**
 * Prefer the session value; when a bearer token is given, refresh from
 * GET /api/me so a language change on auth.timfalken.com is picked up.
 */
function refreshAuthLocale(?string $token): ?string
{
    $current = sessionAuthLocale();
    if (!is_string($token) || $token === '') {
        return $current;
    }
    try {
        $fresh = authLocaleFromPayload(authRequest('/api/me', null, $token));
        if ($fresh !== null) {
            $_SESSION['auth_locale'] = $fresh;
            return $fresh;
        }
    } catch (Throwable $e) {
        // Keep the value from login / the last successful refresh.
    }
    return $current;
}

/** Numeric auth id from a Meteors user id like auth:3, or null. */
function authNumericId(string $userId): ?int
{
    if (!preg_match('/^auth:([1-9][0-9]{0,17})$/', $userId, $m)) {
        return null;
    }
    return (int) $m[1];
}

/**
 * Parse GET /api/profiles from auth.timfalken.com.
 *
 * @return list<array{id:string,name:string,avatar:?string}>
 */
function parseAuthProfiles($data): array
{
    if (!is_array($data) || !isset($data['profiles']) || !is_array($data['profiles'])) {
        return [];
    }
    $out = [];
    foreach ($data['profiles'] as $p) {
        if (!is_array($p) || !isset($p['id'])) {
            continue;
        }
        $raw = $p['id'];
        $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
        if (!$numeric || (int) $raw < 1) {
            continue;
        }
        $name = isset($p['username']) && is_string($p['username']) ? trim($p['username']) : '';
        if ($name === '' || mb_strlen($name) > 64) {
            continue;
        }
        $out[] = [
            'id' => 'auth:' . (int) $raw,
            'name' => $name,
            'avatar' => authAvatarUrl($p),
        ];
    }
    return $out;
}

/** Max ids per GET /api/profiles request (auth limit). */
const AUTH_PROFILES_MAX_IDS = 50;

/**
 * Public names/avatars for auth:* ids via GET /api/profiles, cached
 * in Meteors storage for Store::PROFILES_CACHE_TTL seconds. On auth
 * failure, a stale cache or an empty list is returned (callers keep
 * existing fallbacks).
 *
 * @param list<string> $userIds
 * @return array<string, array{id:string,name:string,avatar:?string}>
 */
function authGetJson(string $path, ?string $token = null): array
{
    $hook = $GLOBALS['METEORS_AUTH_GET'] ?? null;
    if (is_callable($hook)) {
        return $hook($path, $token);
    }
    return authRequest($path, null, $token);
}

function fetchAuthProfiles(Store $store, array $userIds): array
{
    $wanted = [];
    foreach ($userIds as $id) {
        if (!is_string($id)) {
            continue;
        }
        $num = authNumericId($id);
        if ($num !== null) {
            $wanted['auth:' . $num] = $num;
        }
    }
    if ($wanted === []) {
        return [];
    }
    $ids = array_keys($wanted);
    $known = $store->readProfilesCache($ids);
    $missing = [];
    foreach ($ids as $id) {
        if (!isset($known[$id])) {
            $missing[] = $wanted[$id];
        }
    }
    if ($missing === []) {
        return $known;
    }
    $missing = array_values(array_unique($missing));
    try {
        $fetched = [];
        foreach (array_chunk($missing, AUTH_PROFILES_MAX_IDS) as $chunk) {
            $path = '/api/profiles?ids=' . implode(',', $chunk);
            foreach (parseAuthProfiles(authGetJson($path)) as $row) {
                $fetched[] = $row;
                $known[$row['id']] = $row;
            }
        }
        if ($fetched !== []) {
            $store->writeProfilesCache($fetched);
        }
    } catch (Throwable $e) {
        $stale = $store->readProfilesCache($ids, null, true);
        foreach ($stale as $id => $row) {
            if (!isset($known[$id])) {
                $known[$id] = $row;
            }
        }
    }
    return $known;
}

function authAvatarUrl(array $profile): ?string
{
    foreach (['avatar_url', 'avatar', 'picture'] as $k) {
        if (isset($profile[$k]) && is_string($profile[$k])) {
            $url = safeAvatarUrl($profile[$k]);
            if ($url !== null) {
                return $url;
            }
        }
    }
    return null;
}

/**
 * Parse GET /api/friends from auth.timfalken.com into Meteors user ids
 * (`auth:{id}`), names and avatars. Invalid entries are skipped.
 *
 * @return list<array{id:string,name:string,avatar:?string}>
 */
function parseAuthFriends($data): array
{
    if (!is_array($data) || !isset($data['friends']) || !is_array($data['friends'])) {
        return [];
    }
    $out = [];
    foreach ($data['friends'] as $f) {
        if (!is_array($f) || !isset($f['id'])) {
            continue;
        }
        $raw = $f['id'];
        $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
        if (!$numeric || (int) $raw < 1) {
            continue;
        }
        $name = isset($f['username']) && is_string($f['username']) ? trim($f['username']) : '';
        if ($name === '' || mb_strlen($name) > 64) {
            $name = 'auth:' . (int) $raw;
        }
        $out[] = [
            'id' => 'auth:' . (int) $raw,
            'name' => $name,
            'avatar' => authAvatarUrl($f),
        ];
    }
    return $out;
}

/** Local testers test_user_1 and test_user_2 are friends of each other. */
function localTestFriends(string $userId): array
{
    if ($userId === 'local:test_user_1') {
        return [['id' => 'local:test_user_2', 'name' => 'test_user_2', 'avatar' => null]];
    }
    if ($userId === 'local:test_user_2') {
        return [['id' => 'local:test_user_1', 'name' => 'test_user_1', 'avatar' => null]];
    }
    return [];
}

/**
 * Friends of the current viewer from the auth cache, or a fresh
 * GET /api/friends call. Local testers get the built-in pair.
 *
 * @return array{0: list<array{id:string,name:string,avatar:?string}, 1: ?string} friends, error
 */
function fetchViewerFriends(Store $store, array $user, $token): array
{
    $id = (string) ($user['id'] ?? '');
    if ($id === '') {
        return [[], null];
    }
    if (is_string($token) && $token !== '') {
        $cached = $store->readFriendsCache($id);
        if ($cached !== null) {
            return [$cached, null];
        }
        try {
            $friends = parseAuthFriends(authRequest('/api/friends', null, $token));
            $store->writeFriendsCache($id, $friends);
            return [$friends, null];
        } catch (Throwable $e) {
            $stale = $store->readFriendsCache($id, null, true);
            if ($stale !== null) {
                return [$stale, null];
            }
            return [[], $e->getMessage()];
        }
    }
    if (localDev()) {
        return [localTestFriends($id), null];
    }
    return [[], null];
}

/**
 * Viewer's own identity plus friends from auth, keyed by Meteors user id.
 * Also backfills existing profiles so later (guest) requests can show
 * the same names without another auth call.
 *
 * @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}
 */
function leaderboardKnownIdentities(Store $store, ?array $user, $token, array $playerIds = []): array
{
    $known = [];
    $friends = [];
    $error = null;
    if ($user && isset($user['id'], $user['name'])) {
        $known[$user['id']] = [
            'id' => $user['id'],
            'name' => (string) $user['name'],
            'avatar' => $user['avatar'] ?? null,
        ];
        [$friends, $error] = fetchViewerFriends($store, $user, $token);
        foreach ($friends as $f) {
            if (isset($f['id']) && is_string($f['id'])) {
                $known[$f['id']] = $f;
            }
        }
    }
    $ids = $playerIds;
    foreach ($friends as $f) {
        if (isset($f['id']) && is_string($f['id'])) {
            $ids[] = $f['id'];
        }
    }
    if ($user && isset($user['id'])) {
        $ids[] = (string) $user['id'];
    }
    foreach (fetchAuthProfiles($store, $ids) as $id => $ident) {
        $known[$id] = $ident;
    }
    if ($known !== []) {
        $store->rememberIdentities(array_values($known));
    }
    return [$known, $friends, $error];
}

/** @return array{0:string,1:string,2:?string} id, name, avatar */
function authIdentity(array $profile): array
{
    if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
        throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
    }
    $raw = $profile['id'];
    $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
    if (!$numeric || (int) $raw < 1) {
        throw new RuntimeException('Ongeldig account-id.');
    }
    return ['auth:' . (int) $raw, $profile['username'], authAvatarUrl($profile)];
}

/**
 * Where to go after a login (t1193). Only an explicit 'online' (login
 * started from the Online screen) returns to online play; everything else
 * (menu login, missing or unknown value) returns to the main menu.
 */
function loginReturnTarget($param): string
{
    return $param === 'online' ? 'online' : 'menu';
}

/** Relative page to land on after a login for a loginReturnTarget() value. */
function loginReturnPath(?string $target): string
{
    return $target === 'online' ? 'index.html?online=1' : 'index.html';
}

function loginUser(string $id, string $name, ?string $avatar = null): void
{
    if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
        throw new RuntimeException('Ongeldig account.');
    }
    $name = trim($name);
    if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
        throw new RuntimeException('Ongeldige gebruikersnaam.');
    }
    session_regenerate_id(true);
    $_SESSION['user'] = $id;
    $_SESSION['name'] = $name;
    $_SESSION['avatar'] = safeAvatarUrl($avatar);
    $_SESSION['csrf'] = bin2hex(random_bytes(24));
    $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
}

function logoutUser(): void
{
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', [
            'expires' => time() - 3600,
            'path' => $p['path'] ?? '/',
            'secure' => (bool) ($p['secure'] ?? false),
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    }
    session_destroy();
}

function currentUser(): ?array
{
    $id = $_SESSION['user'] ?? null;
    $name = $_SESSION['name'] ?? null;
    if (!is_string($id) || $id === '' || !is_string($name)) {
        return null;
    }
    if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
        return null;
    }
    $avatar = $_SESSION['avatar'] ?? null;
    return [
        'id' => $id,
        'name' => $name,
        'avatar' => is_string($avatar) ? safeAvatarUrl($avatar) : null,
    ];
}

function requireUser(): array
{
    $u = currentUser();
    if (!$u) {
        jsonFail('Log in om verder te gaan.', 401);
    }
    return $u;
}

function csrfToken(): string
{
    if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(24));
    }
    return $_SESSION['csrf'];
}

function requireCsrf(): void
{
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
        return;
    }
    $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
        jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
    }
}

function jsonOut(array $data, int $status = 200): never
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function jsonFail(string $message, int $status = 400): never
{
    jsonOut(['ok' => false, 'error' => $message], $status);
}

function readJsonBody(): array
{
    $raw = file_get_contents('php://input');
    if (!is_string($raw) || $raw === '') {
        return $_POST;
    }
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function startMeteorsSession(): void
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        return;
    }
    $dir = ensureDataDir() . '/sessions';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    session_name('meteors_session');
    ini_set('session.use_strict_mode', '1');
    ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
    session_save_path($dir);
    $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
    if ($path === '//') {
        $path = '/';
    }
    $secure = !localDev();
    session_set_cookie_params([
        'lifetime' => METEORS_SESSION_TTL,
        'path' => $path,
        'secure' => $secure,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
    if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
        setcookie(session_name(), session_id(), [
            'expires' => time() + METEORS_SESSION_TTL,
            'path' => $path,
            'secure' => $secure,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    }
    if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
        $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
    }
}

if (!defined('METEORS_NO_SESSION')) {
    startMeteorsSession();
}
