<?php
require __DIR__.'/lib/bootstrap.php';
try {
    // A random share token grants read-only access to this replay without a session.
    if ($_SERVER['REQUEST_METHOD']==='GET' && ($_GET['action']??'')==='shared_replay') {
        session_write_close();
        $token=$_GET['token']??'';
        if (!is_string($token) || !preg_match('/^[a-f0-9]{48}$/D',$token)) fail('Saved game not found.',404);
        $r=query('SELECT r.a,r.b,r.winner,r.reason,r.ended,p.white,p.moves,p.piece_skin_white,p.piece_skin_black FROM replay_links l JOIN replays p ON p.result_id=l.result_id JOIN results r ON r.id=p.result_id WHERE l.token=?',[$token])->fetch();
        if (!$r) fail('Saved game not found.',404);
        $skinWhite=in_array($r['piece_skin_white']??'',PIECE_COLORS,true)?$r['piece_skin_white']:'White';
        $skinBlack=in_array($r['piece_skin_black']??'',PIECE_COLORS,true)?$r['piece_skin_black']:'Black';
        jsonOut(replayPlayers($r)+['shared'=>true,'shareToken'=>$token,'color'=>'w','ended'=>(int)$r['ended'],'reason'=>$r['reason'],'outcome'=>$r['winner']===null?'Draw':($r['winner']===$r['white']?'White won':'Black won'),'positions'=>replayPositions($r['moves']),'pieceSkinWhite'=>$skinWhite,'pieceSkinBlack'=>$skinBlack,'displayColor'=>$skinWhite,'opponentDisplayColor'=>$skinBlack]);
    }
    $u=user();
    if (!localDev() && time()-($_SESSION['validated']??0)>60) {
        try {
            authRequest('/api/me',null,$_SESSION['token']);
            // Extend when <15 min remain; with 24h auth TTL this still only renews near the end.
            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==='push_config') jsonOut(['publicKey'=>pushKeys()['publicKey']]);
        if ($action==='history' || $action==='replay') {
            $rows=query('SELECT r.id,r.game_id,r.a,r.b,r.winner,r.reason,r.ended,p.white FROM results r JOIN replays p ON p.result_id=r.id WHERE (r.a=? OR r.b=?) ORDER BY r.ended DESC,r.id DESC',[$u,$u])->fetchAll();
            $items=[];
            foreach ($rows as $r) {
                if ($action==='replay' && $r['id']!==(int)($_GET['id']??0)) continue;
                $op=profile($r['a']===$u?$r['b']:$r['a']);
                $item=['id'=>(int)$r['id'],'opponent'=>$op['name'],'opponentId'=>$op['id'],'opponentAvatar'=>$op['avatar'],'opponentRating'=>$op['rating'],'color'=>$r['white']===$u?'w':'b','outcome'=>$r['winner']===null?'draw':($r['winner']===$u?'win':'loss'),'ended'=>(int)$r['ended'],'reason'=>$r['reason']];
                if ($action==='replay') {
                    $item+=replayPlayers($r);
                    $item['shareToken']=replayLink((int)$r['id']);
                    $replayRow=query('SELECT moves,piece_skin_white,piece_skin_black FROM replays WHERE result_id=?',[$r['id']])->fetch();
                    $item['positions']=replayPositions($replayRow['moves']);
                    $item['pieceSkinWhite']=in_array($replayRow['piece_skin_white']??'',PIECE_COLORS,true)?$replayRow['piece_skin_white']:'White';
                    $item['pieceSkinBlack']=in_array($replayRow['piece_skin_black']??'',PIECE_COLORS,true)?$replayRow['piece_skin_black']:'Black';
                    $item['displayColor']=$item['color']==='w'?$item['pieceSkinWhite']:$item['pieceSkinBlack'];
                    $item['opponentDisplayColor']=$item['color']==='w'?$item['pieceSkinBlack']:$item['pieceSkinWhite'];
                    jsonOut($item);
                }
                $items[]=$item;
            }
            if ($action==='replay') fail('Saved game not found.',404);
            jsonOut($items);
        }
        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(),
                'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),
                'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),
                'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),
                'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),
                'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
                'replays'=>array_map(fn($r)=>['id'=>$r['result_id'],'white'=>$r['white'],'positions'=>replayPositions($r['moves'])],query('SELECT p.* FROM replays p JOIN results r ON r.id=p.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll()),
                'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
        }
        if ($action!=='state') fail('Unknown action.',404);
        if ((int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()<=time()-60) {
            db()->exec('BEGIN IMMEDIATE');
            matchPlayers();
            db()->exec('COMMIT');
            pushAfterCommit();
        }
        $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) {
            $f['rating']=(int)profile($f['id'])['rating'];
            $f+=rivalry($u,$f['id']);
        } unset($f);
        $requests=query('SELECT u.id,u.name,av.avatar,r.sender FROM friend_requests r JOIN users u ON u.id=CASE WHEN r.a=? THEN r.b ELSE r.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE r.a=? OR r.b=? ORDER BY r.created,u.id',[$u,$u,$u])->fetchAll();
        foreach ($requests as &$request) {$request['incoming']=$request['sender']!==$u;unset($request['sender']);} unset($request);
        $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']];
        }
        $joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();
        jsonOut(['notificationIntroSeen'=>(bool)query('SELECT 1 FROM notification_intro WHERE user_id=?',[$u])->fetchColumn(),'user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);
    }
    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.');
        if (isset($in['endpoint'])) pushUnsubscribe($u,$in['endpoint']);
        loginUser('local:'.$in['user'],$in['user']);jsonOut(['ok'=>true]);
    }
    if ($action==='logout') {
        if (!localDev() && isset($_SESSION['token'])) authRequest('/api/logout',[],$_SESSION['token']);
        if (isset($in['endpoint'])) pushUnsubscribe($u,$in['endpoint']);
        $_SESSION=[];session_destroy();jsonOut(['ok'=>true]);
    }
    db()->exec('BEGIN IMMEDIATE');
    $out=['ok'=>true];
    if ($action==='claim_notification_intro') {
        $out['show']=query('INSERT OR IGNORE INTO notification_intro(user_id,seen_at) VALUES(?,?)',[$u,time()])->rowCount()===1;
    } elseif ($action==='push_subscribe') {
        pushSubscribe($u,$in);
    } elseif ($action==='push_unsubscribe') {
        pushUnsubscribe($u,$in['endpoint']??null);
    } elseif (in_array($action,['send_friend_request','accept_friend_request','reject_friend_request'],true)) {
        $other=$in['friend']??null;
        if (!is_string($other) || $other===$u) throw new DomainException('Choose another player.');
        $p=pair($u,$other);
        if ($action==='send_friend_request') {
            if (!query('SELECT 1 FROM games WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$other,$other,$u])->fetchColumn()) throw new DomainException('Player not found.');
            if (query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('You are already friends.');
            $sender=query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn();
            if ($sender!==false && $sender!==$u) throw new DomainException('This player has already sent you a friend request.');
            query('INSERT OR IGNORE INTO friend_requests(a,b,sender,created) VALUES(?,?,?,?)',[$p[0],$p[1],$u,time()]);
        } else {
            if (query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn()!==$other) throw new DomainException('This friend request is no longer available.');
            if ($action==='accept_friend_request') befriend($u,$other);
            else query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
        }
    } elseif ($action==='join_matchmaking') {
        query('INSERT INTO matchmaking(user_id,joined) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET joined=excluded.joined WHERE matchmaking.joined<=?',[$u,time(),time()-86400]);
        matchPlayers(true);
    } elseif ($action==='cancel_matchmaking') {
        query('DELETE FROM matchmaking WHERE user_id=?',[$u]);
    } elseif ($action==='set_avatar') {
        $avatar=$in['avatar']??null;
        if ($avatar===null) {
            $avatars=avatarCatalog();
            query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatars[random_int(0,count($avatars)-1)]['id']]);
        }
        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==='set_piece_colors') {
        $mode=$in['colorMode']??'';
        $preferred=$in['preferredColor']??'';
        $alternative=$in['alternativeColor']??'';
        if (!is_string($mode)||!is_string($preferred)||!is_string($alternative)) throw new DomainException('Invalid colour preference.');
        savePieceColorPrefs($u,$mode,$preferred,$alternative);
    } elseif ($action==='set_disable_custom_colours') {
        saveDisableCustomColours($u,!empty($in['disabled']));
    } 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') befriend($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()]);
            pushGame((int)db()->lastInsertId(),'challenge',$other);
        }
    } 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 ($action==='stop_inactive') {
            if (($g['activity_at']??time())>time()-7*86400) throw new DomainException('This game has been active within the last week.');
            query("UPDATE games SET exit_a=1,exit_b=1,rematch_a=0,rematch_b=0,status=CASE WHEN status='ended' THEN status ELSE 'stopped' END,version=version+1 WHERE id=?",[$g['id']]);
        } elseif (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 {
                $white=random_int(0,1)?$g['a']:$g['b'];
                query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[$white,json_encode(Chess::initial()),$g['id']]);
                assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
            }
        } 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]) {
                    $white=$g['white']===$g['a']?$g['b']:$g['a'];
                    query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,piece_skin_white=NULL,piece_skin_black=NULL,version=version+1 WHERE id=?",[$white,json_encode(Chess::initial()),$g['id']]);
                    assignGamePieceSkins((int)$g['id'],$white,$white===$g['a']?$g['b']:$g['a']);
                }
                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.');
                $before=$s;
                $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
                $feedbackStates=[$before,$s];
                $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.');
        }
    }
    if (isset($g) && in_array($action,['move','accept','rematch'],true)) {
        $current=query('SELECT * FROM games WHERE id=?',[$g['id']])->fetch();
        if ($current && $current['status']==='active') pushGame((int)$g['id']);
        elseif ($current && $action==='rematch') pushGame((int)$g['id'],'rematch',$other);
    }
    db()->exec('COMMIT');
    pushAfterCommit();
    if (isset($feedbackStates)) {
        // Release game/session writes before optional computation. Analysis can never undo a saved move.
        session_write_close();
        $out['feedback']=null;
        try {$out['feedback']=(new MoveFeedback())->rate(...$feedbackStates);}
        catch (Throwable $e) {error_log('Move feedback unavailable: '.$e->getMessage());}
    }
    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);
}
