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

try {
    $next = safeNext($_GET['next'] ?? null);
    if ($next) {
        $_SESSION['after_login'] = $next;
    }
    if (localDev() && isset($_GET['test'])) {
        $n = (int) $_GET['test'];
        if ($n < 1 || $n > ALLIANTIES_TEST_USERS) {
            throw new RuntimeException('Onbekende testgebruiker.');
        }
        $who = 'test_user_' . $n;
        // Local only: ?avatar=none (no picture) / ?avatar=broken (URL that 404s,
        // like the auth server's /avatar/<id> for users without a picture).
        $avatar = 'images/avatars/' . $who . '.svg';
        $mode = (string) ($_GET['avatar'] ?? '');
        if ($mode === 'none') {
            $avatar = null;
        } elseif ($mode === 'broken') {
            $avatar = 'images/avatars/missing-' . $who . '.png';
        }
        loginUser('local:' . $who, $who, $avatar);
        $dest = $_SESSION['after_login'] ?? (is_string($next) ? $next : 'index.html');
        unset($_SESSION['after_login']);
        header('Location: ' . $dest);
        exit;
    }
    if (!authConfigured()) {
        header('Location: index.html?auth=unconfigured');
        exit;
    }
    $cfg = config();
    $_SESSION['oauth_state'] = bin2hex(random_bytes(32));
    $_SESSION['oauth_started'] = time();
    header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([
        'client_id' => $cfg['client_id'],
        'redirect_uri' => baseUrl() . '/callback.php',
        'response_type' => 'code',
        'state' => $_SESSION['oauth_state'],
    ]));
} catch (Throwable $e) {
    http_response_code(503);
    header('Content-Type: text/html; charset=utf-8');
    $lang = I18n::htmlLang();
    echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Allianties</title>';
    echo '<p>' . htmlspecialchars(I18n::t('auth.unavailable')) . ' ' . htmlspecialchars($e->getMessage()) . '</p>';
    echo '<p><a href="index.html">' . htmlspecialchars(I18n::t('auth.backToGame')) . '</a></p>';
}
