<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Restaurant;
use App\Models\DeliveryBoy;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class AdvancedDashboardController extends Controller
{
    public function getAdvancedStats()
    {
        $today = Carbon::today();
        $yesterday = Carbon::yesterday();
        $thisMonth = Carbon::now()->startOfMonth();
        $lastMonth = Carbon::now()->subMonth()->startOfMonth();
        $lastMonthEnd = Carbon::now()->subMonth()->endOfMonth();

        // Total Orders
        $totalOrders = Order::count();
        $todayOrders = Order::whereDate('created_at', $today)->count();
        $monthOrders = Order::whereDate('created_at', '>=', $thisMonth)->count();
        $lastMonthOrders = Order::whereBetween('created_at', [$lastMonth, $lastMonthEnd])->count();
        $ordersTrend = $lastMonthOrders > 0 ? (($monthOrders - $lastMonthOrders) / $lastMonthOrders) * 100 : 0;

        // Active Orders
        $activeOrders = Order::whereIn('status', ['accepted', 'preparing', 'ready_for_pickup', 'picked_up'])->count();
        $preparingOrders = Order::where('status', 'preparing')->count();
        $onTheWayOrders = Order::where('status', 'picked_up')->count();

        // Late Orders (orders older than estimated delivery time)
        $lateOrders = Order::where('status', '!=', 'delivered')
            ->where('status', '!=', 'cancelled')
            ->whereRaw('TIMESTAMPDIFF(MINUTE, created_at, NOW()) > estimated_delivery_time')
            ->count();
        
        $yesterdayLateOrders = Order::whereDate('created_at', $yesterday)
            ->where('status', '!=', 'delivered')
            ->where('status', '!=', 'cancelled')
            ->whereRaw('TIMESTAMPDIFF(MINUTE, created_at, NOW()) > estimated_delivery_time')
            ->count();
        
        $lateTrend = $yesterdayLateOrders > 0 ? (($lateOrders - $yesterdayLateOrders) / $yesterdayLateOrders) * 100 : 0;
        $avgDelay = Order::where('status', '!=', 'delivered')
            ->where('status', '!=', 'cancelled')
            ->whereRaw('TIMESTAMPDIFF(MINUTE, created_at, NOW()) > estimated_delivery_time')
            ->selectRaw('AVG(TIMESTAMPDIFF(MINUTE, created_at, NOW()) - estimated_delivery_time) as avg_delay')
            ->value('avg_delay') ?? 0;
        
        $criticalLate = Order::where('status', '!=', 'delivered')
            ->where('status', '!=', 'cancelled')
            ->whereRaw('TIMESTAMPDIFF(MINUTE, created_at, NOW()) > (estimated_delivery_time + 30)')
            ->count();

        // Cancelled Orders
        $cancelledOrders = Order::where('status', 'cancelled')->count();
        $todayCancelled = Order::where('status', 'cancelled')->whereDate('created_at', $today)->count();
        $lastMonthCancelled = Order::where('status', 'cancelled')
            ->whereBetween('created_at', [$lastMonth, $lastMonthEnd])
            ->count();
        $cancelledTrend = $lastMonthCancelled > 0 ? (($cancelledOrders - $lastMonthCancelled) / $lastMonthCancelled) * 100 : 0;

        // Revenue
        $totalRevenue = Order::where('status', 'delivered')->sum('total');
        $todayRevenue = Order::where('status', 'delivered')->whereDate('created_at', $today)->sum('total');
        $monthRevenue = Order::where('status', 'delivered')->whereDate('created_at', '>=', $thisMonth)->sum('total');
        $lastMonthRevenue = Order::where('status', 'delivered')
            ->whereBetween('created_at', [$lastMonth, $lastMonthEnd])
            ->sum('total');
        $revenueTrend = $lastMonthRevenue > 0 ? (($monthRevenue - $lastMonthRevenue) / $lastMonthRevenue) * 100 : 0;

        // Platform Commission (15%)
        $platformCommission = $totalRevenue * 0.15;
        $todayCommission = $todayRevenue * 0.15;
        $commissionTrend = $revenueTrend; // Same as revenue trend

        // Pending Settlements
        $pendingSettlements = Order::where('status', 'delivered')
            ->where('settlement_status', '!=', 'settled')
            ->sum('total') * 0.85; // Restaurant share
        
        $pendingCount = Order::where('status', 'delivered')
            ->where('settlement_status', '!=', 'settled')
            ->count();
        
        $pendingRestaurants = Order::where('status', 'delivered')
            ->where('settlement_status', '!=', 'settled')
            ->distinct('restaurant_id')
            ->count('restaurant_id');
        
        $avgSettlementDays = Order::where('status', 'delivered')
            ->where('settlement_status', '!=', 'settled')
            ->selectRaw('AVG(DATEDIFF(NOW(), delivered_at)) as avg_days')
            ->value('avg_days') ?? 0;

        // Refunds
        $refundAmount = Order::where('refund_status', 'refunded')->sum('refund_amount');
        $todayRefunds = Order::where('refund_status', 'refunded')->whereDate('updated_at', $today)->sum('refund_amount');
        $monthRefunds = Order::where('refund_status', 'refunded')->whereDate('updated_at', '>=', $thisMonth)->sum('refund_amount');
        $lastMonthRefunds = Order::where('refund_status', 'refunded')
            ->whereBetween('updated_at', [$lastMonth, $lastMonthEnd])
            ->sum('refund_amount');
        $refundTrend = $lastMonthRefunds > 0 ? (($monthRefunds - $lastMonthRefunds) / $lastMonthRefunds) * 100 : 0;

        return response()->json([
            'success' => true,
            'data' => [
                'totalOrders' => $totalOrders,
                'todayOrders' => $todayOrders,
                'monthOrders' => $monthOrders,
                'ordersTrend' => [
                    'direction' => $ordersTrend >= 0 ? 'up' : 'down',
                    'percentage' => abs(round($ordersTrend, 1))
                ],
                
                'activeOrders' => $activeOrders,
                'preparingOrders' => $preparingOrders,
                'onTheWayOrders' => $onTheWayOrders,
                
                'lateOrders' => $lateOrders,
                'avgDelay' => round($avgDelay),
                'criticalLate' => $criticalLate,
                'lateTrend' => [
                    'direction' => $lateTrend >= 0 ? 'up' : 'down',
                    'percentage' => abs(round($lateTrend, 1))
                ],
                
                'cancelledOrders' => $cancelledOrders,
                'todayCancelled' => $todayCancelled,
                'cancelledTrend' => [
                    'direction' => $cancelledTrend >= 0 ? 'up' : 'down',
                    'percentage' => abs(round($cancelledTrend, 1))
                ],
                
                'totalRevenue' => $totalRevenue,
                'todayRevenue' => $todayRevenue,
                'monthRevenue' => $monthRevenue,
                'revenueTrend' => [
                    'direction' => $revenueTrend >= 0 ? 'up' : 'down',
                    'percentage' => abs(round($revenueTrend, 1))
                ],
                
                'platformCommission' => $platformCommission,
                'todayCommission' => $todayCommission,
                'commissionMargin' => 15.0,
                'commissionTrend' => [
                    'direction' => $commissionTrend >= 0 ? 'up' : 'down',
                    'percentage' => abs(round($commissionTrend, 1))
                ],
                
                'pendingSettlements' => $pendingSettlements,
                'pendingCount' => $pendingCount,
                'pendingRestaurants' => $pendingRestaurants,
                'avgSettlementDays' => round($avgSettlementDays, 1),
                
                'refundAmount' => $refundAmount,
                'todayRefunds' => $todayRefunds,
                'monthRefunds' => $monthRefunds,
                'refundTrend' => [
                    'direction' => $refundTrend >= 0 ? 'up' : 'down',
                    'percentage' => abs(round($refundTrend, 1))
                ]
            ]
        ]);
    }
}