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

use Zoo\Database;
use Zoo\Auth\PlayerAuthService;
use Zoo\Auth\UserAuthService;
use Zoo\Account\BindService;
use Zoo\Wallet\WalletQuery;

try{
    $input=input_json();
    $password=(string)($input['password'] ?? '');

    $db=Database::connect();
    $player=(new PlayerAuthService($db))->authenticate($input);

    if(($player['auth_mode'] ?? '')!=='guest'){
        json_out([
            'ok'=>true,
            'already_registered'=>true,
            'user'=>$player,
            'binding'=>(new BindService($db))->status((int)$player['user_id']),
            'wallet'=>(new WalletQuery($db))->get((int)$player['user_id'])
        ]);
    }

    $binding=(new BindService($db))->status((int)$player['user_id']);

    if(empty($binding['phone_verified_at']) || empty($binding['phone_e164'])){
        throw new RuntimeException('Verify and bind your mobile number first');
    }

    $guestToken=(string)($_SERVER['HTTP_X_GUEST_SESSION'] ?? ($input['guest_session_token'] ?? ''));
    if($guestToken===''){
        throw new RuntimeException('Missing guest session token');
    }

    $user=(new UserAuthService($db))->bindGuest(
        $guestToken,
        (string)$binding['phone_e164'],
        $password,
        $_SERVER['HTTP_USER_AGENT'] ?? null,
        $_SERVER['REMOTE_ADDR'] ?? null
    );

    $wallet=(new WalletQuery($db))->get((int)$user['user_id']);

    json_out([
        'ok'=>true,
        'registered'=>true,
        'user'=>$user,
        'binding'=>$binding,
        'wallet'=>$wallet
    ]);
}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
