<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Order;
use App\Trade;
use App\User;
use App\TradingPair;
use Illuminate\Support\Facades\DB;

class TradingManagementController extends Controller
{
    /**
     * Trading dashboard
     */
    public function dashboard()
    {
        $stats = [
            'total_orders' => Order::count(),
            'pending_orders' => Order::whereIn('status', ['pending', 'partial'])->count(),
            'total_trades' => Trade::count(),
            'total_volume_24h' => Trade::where('created_at', '>=', now()->subDay())->sum('total'),
            'active_users' => User::whereHas('orders', function($q) {
                $q->where('created_at', '>=', now()->subDay());
            })->count(),
        ];

        $recentTrades = Trade::with('user')
            ->orderBy('created_at', 'desc')
            ->limit(20)
            ->get();

        $topMarkets = Trade::select('market', DB::raw('SUM(total) as volume'))
            ->where('created_at', '>=', now()->subDay())
            ->groupBy('market')
            ->orderBy('volume', 'desc')
            ->limit(10)
            ->get();

        return view('admin.trading.dashboard', compact('stats', 'recentTrades', 'topMarkets'));
    }

    /**
     * All orders
     */
    public function orders()
    {
        $orders = Order::with('user')
            ->orderBy('created_at', 'desc')
            ->paginate(50);

        return view('admin.trading.orders', compact('orders'));
    }

    /**
     * All trades
     */
    public function trades()
    {
        $trades = Trade::with('user', 'order')
            ->orderBy('created_at', 'desc')
            ->paginate(50);

        return view('admin.trading.trades', compact('trades'));
    }

    /**
     * Manage trading pairs
     */
    public function tradingPairs()
    {
        $pairs = TradingPair::orderBy('market')->get();

        return view('admin.trading.pairs', compact('pairs'));
    }

    /**
     * Update trading pair
     */
    public function updatePair(Request $request, $id)
    {
        $request->validate([
            'is_active' => 'required|boolean',
            'maker_fee' => 'required|numeric|min:0|max:1',
            'taker_fee' => 'required|numeric|min:0|max:1',
        ]);

        $pair = TradingPair::findOrFail($id);
        $pair->update($request->only(['is_active', 'maker_fee', 'taker_fee']));

        return back()->with('success', 'جفت ارز به‌روزرسانی شد');
    }

    /**
     * User trading history
     */
    public function userHistory($userId)
    {
        $user = User::findOrFail($userId);
        
        $orders = Order::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();

        $trades = Trade::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();

        return view('admin.trading.user-history', compact('user', 'orders', 'trades'));
    }
}
