<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Services\CoinPriceService;

class SimpleCryptoStream extends Command
{
    protected $signature = 'crypto:simple-stream';
    protected $description = 'Simple stream for CoinEx V2 prices';

    public function handle()
    {
        $this->info('Starting simple crypto stream...');
        
        // Get all symbols from DB
        $cryptocurrencies = \App\Cryptocurrency::all();
        $markets = [];
        foreach ($cryptocurrencies as $crypto) {
            if ($crypto->symbol !== 'USDT') {
                $markets[] = $crypto->symbol . 'USDT';
            }
        }
        
        // Fallback if DB is empty
        if (empty($markets)) {
            $markets = ['BTCUSDT', 'ETHUSDT', 'XRPUSDT', 'DOGEUSDT', 'BNBUSDT', 'ADAUSDT', 'TRXUSDT', 'LTCUSDT', 'BCHUSDT', 'SOLUSDT'];
        }
        
        $marketStr = implode(',', $markets);
        $url = "https://api.coinex.com/v2/spot/ticker?market=" . $marketStr;
        
        $this->info("Fetching prices for: " . count($markets) . " coins");
        
        while (true) {
            try {
                // 1. Fetch from CoinEx
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($httpCode === 200 && $response) {
                    $data = json_decode($response, true);
                    
                    if (isset($data['code']) && $data['code'] === 0 && isset($data['data'])) {
                        $prices = [];
                        
                        // 1. Fetch USDT Price from Tetherland
                        $usdtBuy = 117100; // Default fallback
                        try {
                            // Get URL from settings or use default
                            $tetherlandUrl = "https://api.tetherland.com/currencies";
                            try {
                                $settingUrl = getSetting('tetherland_api_url');
                                if ($settingUrl && !empty($settingUrl->value)) {
                                    $tetherlandUrl = $settingUrl->value;
                                }
                            } catch (\Exception $e) {
                                // Ignore setting error
                            }

                            $chT = curl_init();
                            curl_setopt($chT, CURLOPT_URL, $tetherlandUrl);
                            curl_setopt($chT, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($chT, CURLOPT_TIMEOUT, 10);
                            curl_setopt($chT, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($chT, CURLOPT_FOLLOWLOCATION, true);
                            
                            // Add browser-like headers
                            $headers = [
                                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                                'Accept: application/json, text/plain, */*',
                                'Accept-Language: en-US,en;q=0.9',
                                'Referer: https://tetherland.com/',
                                'Origin: https://tetherland.com'
                            ];
                            curl_setopt($chT, CURLOPT_HTTPHEADER, $headers);
                            
                            $respT = curl_exec($chT);
                            $curlErrorT = curl_error($chT);
                            curl_close($chT);
                            
                            if ($curlErrorT) {
                                $this->error("Tetherland cURL Error: $curlErrorT");
                            }
                            
                            $dataT = json_decode($respT, true);
                            
                            // Check for new structure
                            if (isset($dataT['data']['currencies']['USDT']['price'])) {
                                $usdtBuy = (float)$dataT['data']['currencies']['USDT']['price'];
                                //$this->info("Fetched USDT Price: $usdtBuy");
                            } 
                            // Check for old structure
                            elseif (isset($dataT['data']['coinPrice'])) {
                                $usdtBuy = (float)$dataT['data']['coinPrice'];
                            } else {
                                $this->warn("Tetherland: Price not found. Raw: " . substr($respT, 0, 500));
                            }
                        } catch (\Exception $e) {
                            $this->error("Tetherland Error: " . $e->getMessage());
                        }
                        
                        // Add USDT to prices array
                        $prices['USDT'] = [
                            'buy' => $usdtBuy,
                            'sell' => $usdtBuy,
                            'last' => $usdtBuy,
                            'usdt_price' => 1
                        ];
                        
                        // Update prices
                        foreach ($data['data'] as $item) {
                            $market = $item['market'];
                            if (substr($market, -4) === 'USDT') {
                                $symbol = substr($market, 0, -4);
                                $lastPrice = (float)$item['last'];
                                
                                // Calculate 24h change
                                $change24h = 0;
                                if (isset($item['open']) && (float)$item['open'] > 0) {
                                    $open = (float)$item['open'];
                                    $change24h = (($lastPrice - $open) / $open) * 100;
                                }
                                
                                $buyPrice = round($usdtBuy * $lastPrice);
                                $sellPrice = round($usdtBuy * $lastPrice);
                                
                                $prices[$symbol] = [
                                    'last' => $buyPrice,
                                    'buy' => $buyPrice,
                                    'sell' => $sellPrice,
                                    'change_24h' => round($change24h, 2),
                                    'high' => isset($item['high']) ? round($usdtBuy * (float)$item['high']) : 0,
                                    'low' => isset($item['low']) ? round($usdtBuy * (float)$item['low']) : 0,
                                    'volume' => isset($item['volume']) ? (float)$item['volume'] : 0,
                                    'usdt_price' => $lastPrice
                                ];
                                
                                // Update 'digital_moneys' table (Admin side)
                                $cryptoModel = \App\Cryptocurrency::where('symbol', $symbol)->first();
                                if ($cryptoModel) {
                                    $name = $cryptoModel->name;
                                    \App\DigitalMoney::where('name', $name)
                                        ->orWhere('name', $symbol)
                                        ->update([
                                            'buy_money' => $buyPrice,
                                            'sell_money' => $sellPrice
                                        ]);
                                } else {
                                    \App\DigitalMoney::where('name', $symbol)->update([
                                        'buy_money' => $buyPrice,
                                        'sell_money' => $sellPrice
                                    ]);
                                }
                            }
                        }
                        
                        // Update USDT in DB as well
                        \App\DigitalMoney::where('name', 'USDT')->orWhere('name', 'Tether')->update([
                            'buy_money' => $usdtBuy,
                            'sell_money' => $usdtBuy
                        ]);
                        
                        // Save to JSON file in public folder
                        $jsonPath = public_path('prices.json');
                        file_put_contents($jsonPath, json_encode($prices));
                        
                        // Also update Cache
                        Cache::put(CoinPriceService::CACHE_KEY, $prices, 60);
                        
                        $this->info('[' . date('H:i:s') . '] Updated prices. BTC: $' . $prices['BTC']['usdt_price'] . ' | USDT: ' . $usdtBuy . ' IRT');
                    } else {
                        $this->warn('Invalid response format');
                    }
                } else {
                    $this->warn("HTTP Error: $httpCode");
                }
                
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            
            // Wait 1 second
            sleep(1);
        }
        
        return 0;
    }
}
