<?php
require __DIR__.'/_bootstrap.php';

use Zoo\Database;
use Zoo\Auth\PlayerAuthService;

try{
    $db=Database::connect();
    $player=(new PlayerAuthService($db))->authenticate([]);
    $uid=(int)$player['user_id'];

    $input=json_decode(file_get_contents('php://input'),true) ?: [];
    $name=trim((string)($input['display_name']??''));
    $name=preg_replace('/\s+/u',' ',$name);

    if($name==='' || mb_strlen($name)<2 || mb_strlen($name)>24){
        json_out(['ok'=>false,'error'=>'Display name must be 2 to 24 characters.'],422);
    }

    if(!preg_match('/^[\p{L}\p{N} _.\-]+$/u',$name)){
        json_out(['ok'=>false,'error'=>'Display name contains unsupported characters.'],422);
    }

    $q=$db->prepare("UPDATE users SET display_name=? WHERE id=?");
    $q->execute([$name,$uid]);

    json_out([
        'ok'=>true,
        'display_name'=>$name
    ]);
}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
