<?php
/**
 * User Balance API - Returns fresh balance from database
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

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

$userId = $_SESSION['user_id'];

try {
    $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = ?", [$userId]);
    
    if (!$wallet) {
        // Create wallet if not exists
        $demoBalance = defined('DEMO_BALANCE') ? DEMO_BALANCE : 10000;
        dbQuery("INSERT INTO user_wallets (user_id, balance, demo_balance) VALUES (?, 0, ?)", [$userId, $demoBalance]);
        $wallet = ['balance' => 0, 'demo_balance' => $demoBalance, 'total_trades' => 0, 'total_won' => 0, 'total_lost' => 0];
    }
    
    $pendingData = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals WHERE user_id = ? AND status = 'pending'", [$userId]);
    
    echo json_encode([
        'success' => true,
        'balance' => (float)($wallet['balance'] ?? 0),
        'bonus_balance' => (float)($wallet['bonus_balance'] ?? 0),
        'demo_balance' => (float)($wallet['demo_balance'] ?? 10000),
        'pending_withdrawals' => (float)($pendingData['total'] ?? 0),
        'total_trades' => (int)($wallet['total_trades'] ?? 0),
        'total_won' => (int)($wallet['total_won'] ?? 0),
        'total_lost' => (int)($wallet['total_lost'] ?? 0)
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
