<?php
header('Content-Type: application/json');
require 'db.php'; // Include your database connection script

$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($user_id > 0) {
    // Check if the wallet row exists for the given user ID
    $sql_check = "SELECT COUNT(*) FROM wallets WHERE user_id = ?";
    if ($stmt_check = $conn->prepare($sql_check)) {
        $stmt_check->bind_param('i', $user_id);
        $stmt_check->execute();
        $stmt_check->bind_result($count);
        $stmt_check->fetch();
        $stmt_check->close();

        if ($count > 0) {
            // Fetch the balance if the wallet exists
            $sql = "SELECT balance FROM wallets WHERE user_id = ?";
            if ($stmt = $conn->prepare($sql)) {
                $stmt->bind_param('i', $user_id);
                $stmt->execute();
                $stmt->bind_result($balance);
                $stmt->fetch();

                if (isset($balance)) {
                    echo json_encode(['balance' => $balance]);
                } else {
                    echo json_encode(['balance' => 0]);
                }

                $stmt->close();
            } else {
                echo json_encode(['error' => 'Failed to prepare statement']);
            }
        } else {
            echo json_encode(['error' => 'No wallet found']);
        }
    } else {
        echo json_encode(['error' => 'Failed to prepare check statement']);
    }
} else {
    echo json_encode(['error' => 'Invalid user ID']);
}

$conn->close();
?>
