<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DailyEarning;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class EarningsController extends Controller
{
    public function today(Request $request)
    {
        $user = $request->user();
        $today = Carbon::today();
        
        // Get or create today's earnings record
        $earning = DailyEarning::firstOrCreate(
            ['user_id' => $user->id, 'date' => $today],
            [
                'total_earnings' => 0,
                'total_profit' => 0,
                'total_loss' => 0,
                'total_trades' => 0,
                'winning_trades' => 0,
                'losing_trades' => 0,
            ]
        );
        
        // Get active bots (for gradual P/L calculation)
        $activeBots = \App\Models\AiTradeBot::where('user_id', $user->id)
            ->where('status', 'active')
            ->get();
        
        // Get closed bots that were closed today (for final P/L)
        $closedBotsToday = \App\Models\AiTradeBot::where('user_id', $user->id)
            ->where('status', 'closed')
            ->whereDate('closed_at', $today)
            ->get();
        
        $botProfit = 0;
        $botLoss = 0;
        $totalBots = 0;
        $winningTrades = 0;
        $losingTrades = 0;
        
        // Calculate gradual P/L for each active bot using same logic as frontend
        foreach ($activeBots as $bot) {
            $gradualPL = $this->calculateGradualPL($bot);
            if ($gradualPL) {
                $botProfit += $gradualPL['totalProfit'];
                $botLoss += $gradualPL['totalLoss'];
            } else {
                // Fallback to database values if calculation not applicable
                $botProfit += (float) $bot->total_profit;
                $botLoss += (float) $bot->total_loss;
            }
            
            $totalBots++;
            $netPL = $gradualPL ? ($gradualPL['totalProfit'] - $gradualPL['totalLoss']) : ((float) $bot->total_profit - (float) $bot->total_loss);
            if ($netPL > 0) {
                $winningTrades++;
            } elseif ($netPL < 0) {
                $losingTrades++;
            }
        }
        
        // Add final P/L from closed bots that were closed today
        // Recalculate final P/L to ensure it follows real trading logic (profit OR loss, not both)
        foreach ($closedBotsToday as $bot) {
            // Recalculate final P/L using same logic as close method
            $finalPL = $this->calculateFinalPLForClosedBot($bot);
            
            if ($finalPL) {
                // Use recalculated final P/L (real trading logic)
                $finalProfit = $finalPL['totalProfit'];
                $finalLoss = $finalPL['totalLoss'];
            } else {
                // Fallback to database values if calculation not applicable
                $finalProfit = (float) $bot->total_profit;
                $finalLoss = (float) $bot->total_loss;
            }
            
            $botProfit += $finalProfit;
            $botLoss += $finalLoss;
            
            $totalBots++;
            $netPL = $finalProfit - $finalLoss;
            if ($netPL > 0) {
                $winningTrades++;
            } elseif ($netPL < 0) {
                $losingTrades++;
            }
        }
        
        // Today's Earning = Active bots (gradual P/L) + Closed bots today (final P/L)
        $totalProfit = $botProfit;
        $totalLoss = $botLoss;
        $totalEarnings = $totalProfit - $totalLoss;
        
        $winRate = $totalBots > 0 
            ? ($winningTrades / $totalBots) * 100 
            : 0;

        // Update earnings record
        $earning->update([
            'total_earnings' => $totalEarnings,
            'total_profit' => $totalProfit,
            'total_loss' => $totalLoss,
            'total_trades' => $totalBots,
            'winning_trades' => $winningTrades,
            'losing_trades' => $losingTrades,
        ]);
        
        // Add win_rate to response (calculated, not stored)
        $earning->win_rate = round($winRate, 2);
        
        return response()->json([
            'success' => true,
            'earning' => $earning
        ]);
    }

    public function history(Request $request)
    {
        $user = $request->user();
        
        $query = DailyEarning::where('user_id', $user->id);
        
        // Filter by date range
        if ($request->has('date_from')) {
            $query->whereDate('date', '>=', $request->date_from);
        }
        if ($request->has('date_to')) {
            $query->whereDate('date', '<=', $request->date_to);
        }
        
        $earnings = $query->orderBy('date', 'desc')->paginate($request->per_page ?? 30);
        
        return response()->json([
            'success' => true,
            'earnings' => $earnings
        ]);
    }
    
    /**
     * Calculate gradual profit/loss simulation for active bot.
     * Uses admin_activated_at; if no trading time set, use default 24 hours (1440 min) so Today's Earning shows live bot result.
     */
    private function calculateGradualPL($bot): ?array
    {
        if (!$bot->admin_activated_at) {
            return null;
        }

        $elapsedMinutes = (int) abs($bot->admin_activated_at->diffInMinutes(now()));
        $totalTime = (int) ($bot->admin_set_trading_time_minutes ?? 1440); // Default 24 hours
        $amount = (float) $bot->amount;
        $maxProfitPercent = (float) ($bot->max_profit_percent ?? 0);
        $maxLossPercent = (float) ($bot->max_loss_percent ?? 0);

        if ($totalTime <= 0 || $amount <= 0) {
            return null;
        }

        $progress = min(1, max(0, $elapsedMinutes / $totalTime));
        
        // Final Net P/L = (Win % - Loss %) * amount
        $netPercent = $maxProfitPercent - $maxLossPercent;
        $finalNetPL = ($netPercent / 100) * $amount;
        
        // Gradually approach final Net P/L with random variation (±10% variation for realistic fluctuation)
        // Use seeded random based on bot ID and elapsed time for consistent variation per bot
        $seed = ($bot->id ?? 0) + floor($elapsedMinutes);
        mt_srand($seed);
        $random = mt_rand() / mt_getrandmax();
        
        // Calculate current Net P/L with gradual progression and random variation
        $variation = 0.9 + ($random * 0.2); // 0.9 to 1.1 (±10%)
        $currentNetPL = $finalNetPL * $progress * $variation;
        
        // Real trading logic: Only show profit OR loss, not both
        $totalProfit = 0;
        $totalLoss = 0;
        
        if ($currentNetPL > 0) {
            // Net P/L is positive → only profit (no loss)
            $totalProfit = $currentNetPL;
            $totalLoss = 0;
        } elseif ($currentNetPL < 0) {
            // Net P/L is negative → only loss (no profit)
            $totalProfit = 0;
            $totalLoss = abs($currentNetPL);
        }
        
        return [
            'totalProfit' => max(0, $totalProfit),
            'totalLoss' => max(0, $totalLoss)
        ];
    }
    
    /**
     * Calculate final P/L for closed bot using admin set win/loss %.
     * Real trading logic: Final Net P/L = (Win % - Loss %) * amount
     * If Net P/L is positive → only profit (no loss)
     * If Net P/L is negative → only loss (no profit)
     */
    private function calculateFinalPLForClosedBot($bot): ?array
    {
        $amount = (float) $bot->amount;
        $maxProfitPercent = (float) ($bot->max_profit_percent ?? 0);
        $maxLossPercent = (float) ($bot->max_loss_percent ?? 0);

        if ($amount <= 0) {
            return null;
        }

        $netPercent = $maxProfitPercent - $maxLossPercent;
        $finalNetPL = ($netPercent / 100) * $amount;

        $totalProfit = $finalNetPL > 0 ? $finalNetPL : 0;
        $totalLoss = $finalNetPL < 0 ? abs($finalNetPL) : 0;

        return [
            'totalProfit' => $totalProfit,
            'totalLoss' => $totalLoss
        ];
    }
}

