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

use Zoo\Database;
use Zoo\Auth\PlayerAuthService;
use Zoo\Account\BindService;
use Zoo\Wallet\WalletQuery;
use Zoo\Withdrawal\WithdrawalAccountService;

function mask_phone(?string $value): ?string {
    if(!$value) return null;
    $digits=preg_replace('/\D+/','',(string)$value);
    if(strlen($digits)<7) return $value;
    return substr($digits,0,3).str_repeat('*',max(0,strlen($digits)-6)).substr($digits,-3);
}

try{
    $db=Database::connect();

    // Use the exact same player-session authentication model as the
    // already-working binding / withdrawal / bonus endpoints.
    $player=(new PlayerAuthService($db))->authenticate([]);
    $uid=(int)$player['user_id'];

    $binding=(new BindService($db))->status($uid);
    $wallet=(new WalletQuery($db))->get($uid);

    $withdrawalAccounts=(new WithdrawalAccountService($db))->list($uid);
    $withdrawal=null;
    foreach($withdrawalAccounts as $a){
        if((int)($a['is_active']??0)===1){
            $withdrawal=$a;
            break;
        }
    }
    if(!$withdrawal && $withdrawalAccounts){
        $withdrawal=$withdrawalAccounts[0];
    }

    /*
     * users DOES have created_at, but it does NOT have last_login_at.
     * The previous Step 7 query requested last_login_at from users, which made
     * the entire endpoint fail and left the UI displaying its default values.
     */
    $q=$db->prepare("
      SELECT id,display_name,created_at
      FROM users
      WHERE id=? LIMIT 1
    ");
    $q->execute([$uid]);
    $userRow=$q->fetch(PDO::FETCH_ASSOC)?:[];

    /*
     * last login/activity comes from the real registered-session table.
     * PlayerAuthService updates last_seen_at on every authenticated request.
     */
    $q=$db->prepare("
      SELECT last_seen_at
      FROM user_sessions
      WHERE user_id=?
      ORDER BY last_seen_at DESC,id DESC
      LIMIT 1
    ");
    $q->execute([$uid]);
    $lastLogin=$q->fetchColumn() ?: null;

    $q=$db->prepare("
      SELECT COUNT(*)
      FROM withdrawals
      WHERE user_id=?
        AND status IN ('requested','review','approved','processing')
    ");
    $q->execute([$uid]);
    $pendingWithdrawals=(int)$q->fetchColumn();

    $q=$db->prepare("
      SELECT COUNT(*)
      FROM player_deposits
      WHERE user_id=? AND status='pending'
    ");
    $q->execute([$uid]);
    $pendingDeposits=(int)$q->fetchColumn();

    /*
     * First-deposit popup must stop only after a real completed/credited deposit.
     * Pending/failed/rejected/cancelled deposits do not count.
     */
    $q=$db->prepare("
      SELECT COUNT(*)
      FROM player_deposits
      WHERE user_id=?
        AND status NOT IN ('pending','failed','rejected','cancelled','canceled','expired')
    ");
    $q->execute([$uid]);
    $successfulDeposits=(int)$q->fetchColumn();

    json_out([
      'ok'=>true,
      'account'=>[
        'user_id'=>$uid,
        'public_id'=>$player['public_id']??null,
        'auth_mode'=>$player['auth_mode']??'registered',
        'registered'=>($player['auth_mode']??'')==='registered',
        'created_at'=>$userRow['created_at']??null,
        'display_name'=>$userRow['display_name']??null,
        'last_login_at'=>$lastLogin,

        'phone_verified'=>!empty($binding['phone_verified_at']),
        'phone_masked'=>mask_phone($binding['phone_local']?:$binding['phone_e164']),
        'phone_verified_at'=>$binding['phone_verified_at'],

        'internal_login_bound'=>!empty($binding['internal_login_id']),
        'internal_login_id'=>$binding['internal_login_id'],
        'internal_login_bound_at'=>$binding['internal_login_bound_at'],

        'withdrawal_bound'=>!empty($withdrawal),
        'withdrawal_account'=>$withdrawal,

        'pending_withdrawals'=>$pendingWithdrawals,
        'pending_deposits'=>$pendingDeposits,
        'has_successful_deposit'=>$successfulDeposits>0
      ],
      'wallet'=>$wallet
    ]);
}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
