<?php
// balance.php — JSON API for current user balance info
// Usage: GET /balance.php  →  {"ok":true,"balance":305.00,"wager":0.00,"withdrawable":305.00,"total_deposits":305.00,"total_withdrawn":0.00}
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');
header('Cache-Control: no-store');

require_once __DIR__ . '/config.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['ok' => false, 'error' => 'Not logged in']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT balance, wager, total_deposits, total_withdrawn, is_demo FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([$_SESSION['user_id']]);
    $u = $stmt->fetch();
    if (!$u) { echo json_encode(['ok'=>false,'error'=>'User not found']); exit; }

    $is_demo         = (int)($u['is_demo'] ?? 0);
    $balance         = (float)$u['balance'];
    $wager           = $is_demo ? 0.00 : (float)$u['wager'];
    $withdrawable    = $is_demo ? max(0, $balance) : (($wager <= 0) ? max(0, $balance) : 0.00);
    $total_deposits  = (float)($u['total_deposits'] ?? 0);
    $total_withdrawn = (float)($u['total_withdrawn'] ?? 0);

    echo json_encode([
        'ok'              => true,
        'balance'         => $balance,
        'wager'           => $wager,
        'withdrawable'    => $withdrawable,
        'total_deposits'  => $total_deposits,
        'total_withdrawn' => $total_withdrawn,
    ]);
} catch (Exception $e) {
    echo json_encode(['ok'=>false,'error'=>'DB error']);
}
