<?php
declare(strict_types=1);
require __DIR__.'/lib/bootstrap.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.');
    }
    unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);
    $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'];
    $_SESSION['validated'] = time();
    header('Location: '.baseUrl().'/');
} catch (Throwable $e) {
    http_response_code(401);
    echo 'Inloggen is mislukt. '.htmlspecialchars($e->getMessage()).' <a href="auth.php">Opnieuw proberen</a>';
}
