<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once 'wallet_common.php';

try {
    $pdo = getDBConnection();
    walletEnsureSchema($pdo);

    $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
    if ($userId <= 0) {
        walletJson(['success' => false, 'message' => 'User ID is required', 'balance' => 0.0], 400);
    }

    $balance = walletCurrentBalance($pdo, $userId);
    walletSyncUserBalance($pdo, $userId, $balance);

    walletJson([
        'success' => true,
        'message' => 'Balance retrieved successfully',
        'balance' => $balance,
        'user_id' => $userId
    ]);
} catch (Exception $e) {
    walletJson(['success' => false, 'message' => $e->getMessage(), 'balance' => 0.0], 500);
}
?>
