<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\BinanceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ChartController extends Controller
{
    protected $binanceService;

    public function __construct(BinanceService $binanceService)
    {
        $this->binanceService = $binanceService;
    }

    /**
     * Get klines (candlestick) data for charting
     */
    public function getKlines(Request $request)
    {
        try {
            $request->validate([
                'symbol' => 'required|string',
                'interval' => 'required|string|in:1m,5m,15m,1h,4h,1d',
                'limit' => 'sometimes|integer|min:1|max:1000',
                'startTime' => 'sometimes|integer|min:0',
                'endTime' => 'sometimes|integer|min:0',
            ]);

            $symbol = strtoupper($request->input('symbol'));
            $interval = $request->input('interval', '15m');
            $limit = $request->input('limit', 500);
            $startTime = $request->input('startTime');
            $endTime = $request->input('endTime');

            // Ensure symbol ends with USDT
            if (!str_ends_with($symbol, 'USDT')) {
                $symbol = $symbol . 'USDT';
            }

            $klines = $this->binanceService->getKlines($symbol, $interval, $limit, $startTime, $endTime);

            if ($klines === null) {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to fetch chart data'
                ], 500);
            }

            // Get current ticker data for price and change
            // IMPORTANT: Get ticker FIRST to ensure klines match ticker price
            $ticker = $this->binanceService->getTickerData($symbol);
            
            // Ensure last kline close price matches ticker price (for consistency)
            if ($ticker && count($klines) > 0) {
                $lastKline = &$klines[count($klines) - 1];
                $tickerPrice = (float) $ticker['price'];
                
                // Update last kline to match ticker price exactly
                $lastKline['close'] = $tickerPrice;
                $lastKline['high'] = max($lastKline['high'], $tickerPrice);
                $lastKline['low'] = min($lastKline['low'], $tickerPrice);
            }

            return response()->json([
                'success' => true,
                'symbol' => $symbol,
                'interval' => $interval,
                'klines' => $klines,
                'ticker' => $ticker,
            ]);
        } catch (\Exception $e) {
            Log::error('Chart API Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error fetching chart data: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get available trading pairs
     * Matches MarketPriceController topMarkets (12 coins total)
     */
    public function getTradingPairs()
    {
        // Popular trading pairs - Top 12 coins (matches MarketPriceController)
        // Removed MATIC, ATOM, UNI to match market page (12 coins total)
        $pairs = [
            'BTCUSDT',  // Bitcoin
            'ETHUSDT',  // Ethereum
            'BNBUSDT',  // Binance Coin
            'SOLUSDT',  // Solana
            'XRPUSDT',  // Ripple
            'ADAUSDT',  // Cardano
            'DOGEUSDT', // Dogecoin
            'DOTUSDT',  // Polkadot
            'LTCUSDT',  // Litecoin
            'AVAXUSDT', // Avalanche
            'TRXUSDT',  // Tron
            'LINKUSDT', // Chainlink
        ];

        // Get default trading interval from system settings (admin configurable)
        $defaultInterval = \App\Models\SystemSetting::get('default_trading_interval', '15m');

        return response()->json([
            'success' => true,
            'pairs' => $pairs,
            'default_interval' => $defaultInterval,
        ]);
    }
}

