<?php
require_once 'includes/auth_check.php';
require_once '../config/database.php';

header('Content-Type: application/json');

// Validate inputs
$user_id = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
$currency = $_GET['currency'] ?? '';

if (!$user_id || empty($currency)) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $stmt = $db->prepare("SELECT balance FROM account_balances WHERE user_id = ? AND currency = ?");
    $stmt->execute([$user_id, $currency]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result) {
        // Balance found
        echo json_encode([
            'success' => true, 
            'balance' => $result['balance']
        ]);
    } else {
        // No balance record exists for this currency, which is fine.
        echo json_encode([
            'success' => true, 
            'balance' => 0 // Return 0 as the balance
        ]);
    }
} catch (Exception $e) {
    error_log("get_user_balance.php Error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'Database error occurred.'
    ]);
}
