<?php
require __DIR__.'/lib/bootstrap.php';
try {
    $u=user();
    if (!localDev() && time()-($_SESSION['validated']??0)>60) {
        try {
            authRequest('/api/me',null,$_SESSION['token']);
            if ($_SESSION['expires']-time()<900) { $extended=authRequest('/api/session/extend',[],$_SESSION['token']);$_SESSION['expires']=time()+(int)$extended['expires_in']; }
            $_SESSION['validated']=time();
        } catch (Throwable $e) {unset($_SESSION['user']);fail('Please sign in again.',401);}
    }
    $method=$_SERVER['REQUEST_METHOD'];
    if ($method==='GET') {
        $action=$_GET['action']??'state';
        if ($action==='export') {
            header('Content-Disposition: attachment; filename="microchess-data.json"');
            jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
                'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),
                'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),
                'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
                'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
        }
        if ($action!=='state') fail('Unknown action.',404);
        $friends=query('SELECT u.*,av.avatar FROM friends f JOIN users u ON u.id=CASE WHEN f.a=? THEN f.b ELSE f.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE f.a=? OR f.b=? ORDER BY u.name',[$u,$u,$u])->fetchAll();
        foreach ($friends as &$f) {
            $rows=query('SELECT winner FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$f['id'],$f['id'],$u])->fetchAll();
            $f['wins']=count(array_filter($rows,fn($r)=>$r['winner']===$u));$f['ties']=count(array_filter($rows,fn($r)=>$r['winner']===null));$f['losses']=count($rows)-$f['wins']-$f['ties'];
        } unset($f);
        $games=query('SELECT * FROM games WHERE (a=? AND exit_a=0) OR (b=? AND exit_b=0) ORDER BY id DESC',[$u,$u])->fetchAll();
        $invite=null;
        if (isset($_GET['invite'])) {
            $l=query('SELECT l.*,u.name FROM links l JOIN users u ON u.id=l.owner WHERE token=?',[(string)$_GET['invite']])->fetch();
            if (!$l || $l['used'] || $l['expires']<=time()) $invite=['error'=>'This invitation has expired or has already been accepted.'];
            elseif ($l['owner']===$u) $invite=['error'=>'This is your invitation. Share the link with someone else.'];
            else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];
        }
        jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite]);
    }
    if ($method!=='POST') fail('Method not allowed.',405);
    if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);
    $in=json_decode(file_get_contents('php://input'),true,32,JSON_THROW_ON_ERROR);
    if (!is_array($in)) throw new DomainException('Invalid request.');
    $action=$in['action']??'';
    if ($action==='switch_user') {
        if (!localDev()) fail('Not available.',403);
        if (!in_array($in['user']??'', ['test_user_1','test_user_2'],true)) throw new DomainException('Unknown test user.');
        loginUser('local:'.$in['user'],$in['user']);jsonOut(['ok'=>true]);
    }
    if ($action==='logout') {
        if (!localDev() && isset($_SESSION['token'])) authRequest('/api/logout',[],$_SESSION['token']);
        $_SESSION=[];session_destroy();jsonOut(['ok'=>true]);
    }
    db()->exec('BEGIN IMMEDIATE');
    $out=['ok'=>true];
    if ($action==='set_avatar') {
        $avatar=$in['avatar']??null;
        if ($avatar===null) query('DELETE FROM user_avatars WHERE user_id=?',[$u]);
        else {
            if (!is_string($avatar)||!in_array($avatar,array_column(avatarCatalog(),'id'),true)) throw new DomainException('Choose an avatar from the available pieces.');
            query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatar]);
        }
    } elseif ($action==='create_link') {
        $kind=$in['kind']??''; if (!in_array($kind,['friend','match'],true)) throw new DomainException('Invalid invitation type.');
        $token=bin2hex(random_bytes(24));
        query('INSERT INTO links(token,owner,kind,expires) VALUES(?,?,?,?)',[$token,$u,$kind,(new DateTimeImmutable())->modify('+1 month')->getTimestamp()]);
        $out['url']=baseUrl().'/?invite='.$token;
    } elseif ($action==='accept_link') {
        $l=query('SELECT * FROM links WHERE token=?',[$in['token']??''])->fetch();
        if (!$l || $l['used'] || $l['expires']<=time()) throw new DomainException('This invitation has expired or has already been accepted.');
        if ($l['owner']===$u) throw new DomainException('You cannot accept your own invitation.');
        if ($l['kind']==='friend') query('INSERT OR IGNORE INTO friends VALUES(?,?)',pair($u,$l['owner']));
        else $out['game']=startGame($l['owner'],$u);
        query('UPDATE links SET used=1 WHERE token=?',[$l['token']]);
    } elseif ($action==='remove_friend' || $action==='challenge') {
        $other=$in['friend']??'';$p=pair($u,$other);
        if (!query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('This person is no longer in your friends list.');
        if ($action==='remove_friend') query('DELETE FROM friends WHERE a=? AND b=?',$p);
        else {
            if (query("SELECT 1 FROM games WHERE status='pending' AND ((a=? AND b=?) OR (a=? AND b=?))",[$u,$other,$other,$u])->fetchColumn()) throw new DomainException('There is already an invitation waiting.');
            query("INSERT INTO games(a,b,status,created) VALUES(?,?,'pending',?)",[$u,$other,time()]);
        }
    } else {
        $g=query('SELECT * FROM games WHERE id=?',[$in['game']??0])->fetch();
        if (!$g || ($g['a']!==$u && $g['b']!==$u)) throw new DomainException('Game not found.');
        $side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';$other=$g[$opSide];
        if ($g['exit_'.$side]) throw new DomainException('You have left this game.');
        if (!isset($in['version']) || $in['version']!==(int)$g['version']) throw new DomainException('The game has changed. Please try again.');
        if (in_array($action,['accept','reject'],true)) {
            if ($g['status']!=='pending' || $g['b']!==$u) throw new DomainException('This invitation is no longer available.');
            if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
            else query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[random_int(0,1)?$g['a']:$g['b'],json_encode(Chess::initial()),$g['id']]);
        } elseif ($action==='exit' || $action==='rematch') {
            if ($g['status']!=='ended') throw new DomainException('The game has not ended.');
            if ($action==='exit') query("UPDATE games SET exit_$side=1,rematch_$side=0,version=version+1 WHERE id=?",[$g['id']]);
            else {
                if ($g['exit_'.$opSide]) throw new DomainException('Your opponent has left this game.');
                if ($g['rematch_'.$side]) throw new DomainException('Your rematch request is already waiting.');
                if ($g['rematch_'.$opSide]) query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,version=version+1 WHERE id=?",[$g['white']===$g['a']?$g['b']:$g['a'],json_encode(Chess::initial()),$g['id']]);
                else query("UPDATE games SET rematch_$side=1,version=version+1 WHERE id=?",[$g['id']]);
            }
        } else {
            if ($g['status']!=='active') throw new DomainException('This game is not active.');
            $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';
            if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
            if ($action==='move') {
                if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
                $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
                $r=Chess::result($s);
                if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
                else query('UPDATE games SET state=?,draw_offer=CASE WHEN draw_offer=? THEN draw_offer ELSE NULL END,version=version+1 WHERE id=?',[json_encode($s),$u,$g['id']]);
            } elseif ($action==='claim_draw') {
                $claim=$s;
                if (isset($in['from'],$in['to'])) $claim=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
                if (!Chess::claimable($claim)) throw new DomainException('A draw cannot be claimed in this position.');
                finishGame($g,null,$claim['halfmove']>=100?'50-move rule':'Threefold repetition',$s);
            } elseif ($action==='offer_draw') {
                if ($g['draw_offer']) throw new DomainException('A draw has already been offered.');
                query('UPDATE games SET draw_offer=?,version=version+1 WHERE id=?',[$u,$g['id']]);
            } elseif ($action==='accept_draw') {
                if ($g['draw_offer']!==$other) throw new DomainException('There is no draw offer to accept.');
                finishGame($g,null,'Draw by agreement',$s);
            } elseif ($action==='resign') finishGame($g,$other,'Resignation',$s);
            else throw new DomainException('Unknown action.');
        }
    }
    db()->exec('COMMIT');jsonOut($out);
} catch (Throwable $e) {
    try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
    if ($e instanceof DomainException || $e instanceof JsonException) fail($e->getMessage(),409);
    error_log((string)$e);fail('Something went wrong. Please try again.',500);
}
