<?php
// api/get_balance.php - 查詢即時餘額
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

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

if ($user_id <= 0) {
    echo json_encode(["status" => "error", "message" => "未登入"]);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT coins FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $balance = $stmt->fetchColumn();

    // 如果找不到人，回傳 0
    if ($balance === false) $balance = 0;

    echo json_encode(["status" => "success", "balance" => intval($balance)]);
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "讀取失敗"]);
}
?>