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

use Zoo\Database;
use Zoo\Auth\UserAuthService;
use Zoo\Wallet\WalletQuery;

try {
    $in = input_json();
    $db = Database::connect();
    $auth = new UserAuthService($db);

    $phone = (string)($in['phone'] ?? '');
    $password = (string)($in['password'] ?? '');
    $guestSessionToken = trim((string)(
        $_SERVER['HTTP_X_GUEST_SESSION']
        ?? ($in['guest_session_token'] ?? '')
    ));

    if ($guestSessionToken !== '') {
        // Upgrade the SAME guest user so wallet, bets and history stay attached.
        $user = $auth->bindGuest(
            $guestSessionToken,
            $phone,
            $password,
            $_SERVER['HTTP_USER_AGENT'] ?? null,
            $_SERVER['REMOTE_ADDR'] ?? null
        );
    } else {
        // Normal first-time registration.
        $user = $auth->register(
            $phone,
            $password,
            $_SERVER['HTTP_USER_AGENT'] ?? null,
            $_SERVER['REMOTE_ADDR'] ?? null
        );
    }

    $wallet = (new WalletQuery($db))->get((int)$user['user_id']);
    json_out(['ok'=>true,'user'=>$user,'wallet'=>$wallet],201);
} catch(Throwable $e) {
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
