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

try {
    $state = $_GET['state'] ?? null;
    if (!is_string($state) || !isset($_SESSION['oauth_state'])
        || !hash_equals((string) $_SESSION['oauth_state'], $state)
        || time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {
        throw new RuntimeException('Ongeldige of verlopen login.');
    }
    $loginReturn = loginReturnTarget($_SESSION['login_return'] ?? null);
    unset($_SESSION['oauth_state'], $_SESSION['oauth_started'], $_SESSION['login_return']);
    $code = $_GET['code'] ?? null;
    if (!is_string($code) || $code === '') {
        throw new RuntimeException('De login is niet afgerond.');
    }
    $cfg = config();
    $token = authRequest('/oauth/token', [
        'grant_type' => 'authorization_code',
        'code' => $code,
        'client_id' => $cfg['client_id'],
        'client_secret' => $cfg['client_secret'],
        'redirect_uri' => baseUrl() . '/callback.php',
    ]);
    if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {
        throw new RuntimeException('Geen toegangstoken ontvangen.');
    }
    $me = authRequest('/api/me', null, $token['access_token']);
    if (!isset($me['user']) || !is_array($me['user'])) {
        throw new RuntimeException('Het profiel ontbreekt.');
    }
    [$id, $name] = authIdentity($me['user']);
    loginUser($id, $name);
    $_SESSION['token'] = $token['access_token'];
    $_SESSION['expires'] = time() + (int) $token['expires_in'];
    // t1193: back to the main menu unless the login started from Online.
    header('Location: ' . baseUrl() . '/' . loginReturnPath($loginReturn));
} catch (Throwable $e) {
    http_response_code(401);
    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 htmlspecialchars(I18n::t('auth.failed')) . ' ' . htmlspecialchars($e->getMessage());
    echo ' <a href="auth.php">' . htmlspecialchars(I18n::t('auth.retry')) . '</a> · <a href="index.html">' . htmlspecialchars(I18n::t('auth.back')) . '</a>';
}
