<?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'];

    /*
     * Return only a very recent SETTLED round in which this player had bets.
     * The payout is the ACTUAL sum stored by SettlementService in bets.payout.
     * Nothing is calculated from the UI multiplier.
     */
    $q=$db->prepare("
      SELECT
        r.id round_id,
        r.public_round_id,
        r.winner,
        r.settled_at,
        COALESCE(SUM(CASE WHEN b.status='won' THEN b.payout ELSE 0 END),0) payout,
        SUM(CASE WHEN b.status='won' THEN 1 ELSE 0 END) winning_bets
      FROM rounds r
      JOIN bets b ON b.round_id=r.id AND b.user_id=?
      WHERE r.state='SETTLED'
        AND r.settled_at IS NOT NULL
        AND r.settled_at>=DATE_SUB(NOW(3),INTERVAL 25 SECOND)
      GROUP BY r.id,r.public_round_id,r.winner,r.settled_at
      ORDER BY r.settled_at DESC
      LIMIT 1
    ");
    $q->execute([$uid]);
    $row=$q->fetch(PDO::FETCH_ASSOC);

    $w=$db->prepare("
      SELECT cash_balance,bonus_balance,withdrawable_balance,wager_remaining
      FROM wallets WHERE user_id=? LIMIT 1
    ");
    $w->execute([$uid]);
    $wallet=$w->fetch(PDO::FETCH_ASSOC) ?: [
      'cash_balance'=>0,'bonus_balance'=>0,'withdrawable_balance'=>0,'wager_remaining'=>0
    ];

    if(!$row){
        json_out([
          'ok'=>true,
          'settlement'=>null,
          'wallet'=>$wallet
        ]);
    }

    json_out([
      'ok'=>true,
      'settlement'=>[
        'round_id'=>(int)$row['round_id'],
        'public_round_id'=>$row['public_round_id'],
        'winner'=>$row['winner'],
        'settled_at'=>$row['settled_at'],
        'winning_bets'=>(int)$row['winning_bets'],
        'payout'=>(float)$row['payout']
      ],
      'wallet'=>$wallet
    ]);
}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
