<?php
require __DIR__.'/lib/bootstrap.php';
try {
    if (!is_string($_GET['state']??null)||!isset($_SESSION['oauth_state'])||!hash_equals($_SESSION['oauth_state'],$_GET['state'])||time()-($_SESSION['oauth_started']??0)>600) throw new RuntimeException('Invalid or expired login state.');
    unset($_SESSION['oauth_state']);
    if (!is_string($_GET['code']??null)) throw new RuntimeException('Login was not completed.');
    $cfg=config();
    $r=authRequest('/oauth/token',['grant_type'=>'authorization_code','code'=>$_GET['code'],'client_id'=>$cfg['client_id'],'client_secret'=>$cfg['client_secret'],'redirect_uri'=>baseUrl().'/callback.php']);
    $profile=authRequest('/api/me',null,$r['access_token'])['user'];
    loginUser('auth:'.$profile['id'],$profile['username']);
    $_SESSION['token']=$r['access_token']; $_SESSION['expires']=time()+(int)$r['expires_in']; $_SESSION['validated']=time();
    $invite=$_SESSION['return_invite']??'';unset($_SESSION['return_invite']);
    $game=$_SESSION['return_game']??'';unset($_SESSION['return_game']);
    $query=http_build_query(array_filter(['invite'=>$invite,'game'=>$game]));
    header('Location: '.baseUrl().'/'.($query?'?'.$query:''));
} catch(Throwable $e) {http_response_code(401);echo 'Sign-in failed. '.htmlspecialchars($e->getMessage()).' <a href="auth.php?'.htmlspecialchars(http_build_query(array_filter(['invite'=>$_SESSION['return_invite']??'','game'=>$_SESSION['return_game']??'']))).'">Try again</a>';}
