<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';

// List of supported coins for OKX
$coins = [
    'BTC' => ['name' => 'Bitcoin', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/btc.png'],
    'ETH' => ['name' => 'Ethereum', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/eth.png'],
    'BNB' => ['name' => 'BNB', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/bnb.png'],
    'SOL' => ['name' => 'Solana', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/sol.png'],
    'OKB' => ['name' => 'OKB', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/okb.png'],
    'LINK' => ['name' => 'Chainlink', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/link.png'],
    'DOT' => ['name' => 'Polkadot', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/dot.png'],
    'ADA' => ['name' => 'Cardano', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/ada.png'],
    'DOGE' => ['name' => 'Dogecoin', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/doge.png'],
    'XRP' => ['name' => 'XRP', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/xrp.png'],
    'AVAX' => ['name' => 'Avalanche', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/avax.png'],
    'MATIC' => ['name' => 'Polygon', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/matic.png'],
    'TRX' => ['name' => 'TRON', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/trx.png'],
    'LTC' => ['name' => 'Litecoin', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/ltc.png'],
    'BCH' => ['name' => 'Bitcoin Cash', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/bch.png'],
    'UNI' => ['name' => 'Uniswap', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/uni.png'],
    'FIL' => ['name' => 'Filecoin', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/fil.png'],
    'APT' => ['name' => 'Aptos', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/apt.png'],
    'ARB' => ['name' => 'Arbitrum', 'icon' => 'https://static.okx.com/cdn/oksupport/asset/currency/icon/arb.png'],
];

function fetchRealPricesOKX() {
    $ch = curl_init();
    $url = "https://www.okx.com/api/v5/market/tickers?instType=SPOT";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

$realData = fetchRealPricesOKX();
$result = [];

// Initialize result with fallback data
foreach ($coins as $symbol => $data) {
    $result[$symbol] = array_merge($data, [
        'price' => 0.00,
        'change' => 0.00,
        'high' => 0.00,
        'low' => 0.00,
        'volume' => 0.00,
    ]);
}

if ($realData && isset($realData['code']) && $realData['code'] == "0" && isset($realData['data'])) {
    foreach ($realData['data'] as $ticker) {
        $instId = $ticker['instId'];
        if (strpos($instId, '-USDT') !== false) {
            $symbol = str_replace('-USDT', '', $instId);
            if (isset($result[$symbol])) {
                $last = (float)$ticker['last'];
                $open = (float)$ticker['open24h'];
                $change = ($open > 0) ? (($last - $open) / $open) * 100 : 0;
                
                $result[$symbol]['price'] = $last;
                $result[$symbol]['change'] = $change;
                $result[$symbol]['high'] = (float)$ticker['high24h'];
                $result[$symbol]['low'] = (float)$ticker['low24h'];
                $result[$symbol]['volume'] = (float)$ticker['vol24h'];
            }
        }
    }
}

// Check for admin price manipulation
try {
    $conn = db();
    if ($conn) {
        $stmt = $conn->prepare("SELECT config_key, config_value FROM system_config WHERE config_key LIKE 'price_%'");
        $stmt->execute();
        $manipulations = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        foreach ($result as $symbol => &$data) {
            $key = 'price_' . $symbol;
            if (isset($manipulations[$key]) && is_numeric($manipulations[$key])) {
                $data['price'] = (float)$manipulations[$key];
            }
        }
    }
} catch (Exception $e) {}

echo json_encode(['success' => true, 'data' => $result]);
