<?php

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$results = [];

// Test CoinEx
$results['coinex'] = testAPI('https://api.coinex.com/v1/market/ticker/all', 'CoinEx');

// Test Binance
$results['binance'] = testAPI('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT', 'Binance');

// Test Nobitex
$results['nobitex'] = testAPI('https://api.nobitex.ir/market/stats', 'Nobitex');

// Test Tetherland
$results['tetherland'] = testAPI('https://api.tetherland.com/currencies', 'Tetherland');

// Test CoinGecko
$results['coingecko'] = testAPI('https://api.coingecko.com/api/v3/ping', 'CoinGecko');

header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'results' => $results,
    'summary' => [
        'total' => count($results),
        'working' => count(array_filter($results, function($r) { return $r['success']; })),
        'failed' => count(array_filter($results, function($r) { return !$r['success']; }))
    ]
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

function testAPI($url, $name)
{
    $start = microtime(true);
    
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        
        $duration = round((microtime(true) - $start) * 1000, 2);
        
        $success = ($httpCode === 200 && $response !== false);
        
        return [
            'name' => $name,
            'url' => $url,
            'success' => $success,
            'http_code' => $httpCode,
            'duration_ms' => $duration,
            'response_size' => strlen($response),
            'error' => $error ?: null,
            'ip' => $info['primary_ip'] ?? null,
            'sample' => $success ? substr($response, 0, 200) : null
        ];
        
    } catch (Exception $e) {
        return [
            'name' => $name,
            'url' => $url,
            'success' => false,
            'error' => $e->getMessage(),
            'duration_ms' => round((microtime(true) - $start) * 1000, 2)
        ];
    }
}
