<?php
require __DIR__.'/_bootstrap.php';
use Zoo\Database;
use Zoo\Auth\PlayerAuthService;
use Zoo\Wallet\WalletQuery;
try{
  $db=Database::connect();
  $player=(new PlayerAuthService($db))->authenticate([]);
  $uid=(int)$player['user_id'];

  $q=$db->prepare("SELECT phone_verified_at,phone_binding_bonus_claimed,first_deposit_bonus_claimed FROM users WHERE id=? LIMIT 1");
  $q->execute([$uid]); $u=$q->fetch(PDO::FETCH_ASSOC)?:[];

  $q=$db->prepare("
    SELECT id,type,amount,bonus_delta,reference_type,reference_id,metadata,created_at
    FROM wallet_ledger
    WHERE user_id=? AND (
      type IN ('reward','deposit_bonus','welcome_bonus')
      OR reference_type IN ('phone_binding','phone_binding_bonus','daily_checkin','vip_minute_gift','deposit_bonus','welcome_bonus')
    )
    ORDER BY id DESC LIMIT 50
  ");
  $q->execute([$uid]);
  $rows=[];$total=0.0;
  foreach($q->fetchAll(PDO::FETCH_ASSOC) as $r){
    $impact=(float)$r['bonus_delta'];
    if($impact<=0)$impact=(float)$r['amount'];
    if($impact>0)$total+=$impact;
    $rows[]=[
      'id'=>(int)$r['id'],'kind'=>$r['type'],'amount'=>(float)$r['amount'],
      'impact'=>$impact,'reference_type'=>$r['reference_type'],
      'reference_id'=>$r['reference_id'],'created_at'=>$r['created_at']
    ];
  }

  json_out([
    'ok'=>true,
    'wallet'=>(new WalletQuery($db))->get($uid),
    'status'=>[
      'phone_verified'=>!empty($u['phone_verified_at']),
      'binding_claimed'=>(int)($u['phone_binding_bonus_claimed']??0)===1,
      'welcome_claimed'=>(int)($u['first_deposit_bonus_claimed']??0)===1
    ],
    'total_rewards'=>$total,
    'rewards'=>$rows
  ]);
}catch(Throwable $e){json_out(['ok'=>false,'error'=>$e->getMessage()],422);}
