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

try {
    if (localDev() && isset($_GET['test'])) {
        $who = $_GET['test'] === '2' ? 'test_user_2' : 'test_user_1';
        loginUser('local:' . $who, $who);
        $next = isset($_GET['next']) && is_string($_GET['next']) ? $_GET['next'] : 'index.html';
        header('Location: ' . $next);
        exit;
    }
    if (!authConfigured()) {
        header('Location: index.html?auth=unconfigured');
        exit;
    }
    $cfg = config();
    // t1193: remember where the login started (menu vs. Online screen).
    $_SESSION['login_return'] = loginReturnTarget($_GET['return'] ?? null);
    $_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>Meteors</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>';
}
