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

// --- Add XRP and XLM ---
$coinIds = [
    'btc'  => 'bitcoin',
    'eth'  => 'ethereum',
    'ltc'  => 'litecoin',
    'trx'  => 'tron',
    'doge' => 'dogecoin',
    'usdt' => 'tether',
    'bnb'  => 'binancecoin',
    'xrp'  => 'ripple',
    'xlm'  => 'stellar'
];

// Build CoinGecko API URL
$ids = implode(',', array_values($coinIds));
$url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids={$ids}&order=market_cap_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h";

// cURL request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; PHP Script)');
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($httpCode !== 200 || empty($response)) {
    $msg = "API request failed. HTTP: {$httpCode}";
    if ($curlError) $msg .= " | cURL: {$curlError}";
    echo json_encode(['error' => $msg]);
    exit;
}

// Decode JSON safely
$data = json_decode($response, true);
if (!is_array($data)) {
    echo json_encode(['error' => 'Invalid JSON response from CoinGecko']);
    exit;
}

// Build output array
$output = [];
foreach ($data as $coin) {
    $id = $coin['id'] ?? '';
    $key = array_search($id, $coinIds);
    if ($key !== false) {
        $output[$key] = [
            'price'  => floatval($coin['current_price'] ?? 0),
            'change' => floatval($coin['price_change_percentage_24h'] ?? 0)
        ];
    }
}

// Return JSON
echo json_encode($output);
?>