<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\DriverLocation;
use App\Models\Load;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DriverManagementController extends Controller
{
    /**
     * Display a listing of drivers with their status
     */
    public function index(Request $request)
    {
        try {
            $query = User::where('role', 'driver')
                ->with(['location', 'driverLoads' => function($q) {
                    $q->latest()->limit(5);
                }])
                ->withCount([
                    'driverLoads',
                    'driverLoads as completed_loads' => function($q) {
                        $q->where('status', 'delivered');
                    },
                    'driverLoads as active_loads' => function($q) {
                        $q->whereIn('status', ['approved', 'in_transit']);
                    },
                ]);

            // Search
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('phone', 'like', "%{$search}%")
                      ->orWhere('national_code', 'like', "%{$search}%");
                });
            }

            // Filter by active status
            if ($request->has('is_active') && $request->is_active !== null) {
                $query->where('is_active', $request->is_active);
            }

            // Filter by online status
            if ($request->has('is_online') && $request->is_online !== null) {
                if ($request->is_online) {
                    $query->whereHas('location', function($q) {
                        $q->where('is_online', true)
                          ->where('last_ping_at', '>=', Carbon::now()->subMinutes(5));
                    });
                } else {
                    $query->whereDoesntHave('location', function($q) {
                        $q->where('is_online', true)
                          ->where('last_ping_at', '>=', Carbon::now()->subMinutes(5));
                    });
                }
            }

            // Sort
            $sortBy = $request->get('sort_by', 'created_at');
            $sortOrder = $request->get('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);

            // Paginate
            $perPage = $request->get('per_page', 15);
            $drivers = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'message' => 'لیست رانندگان با موفقیت دریافت شد',
                'data' => $drivers,
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت لیست رانندگان',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Display the specified driver with detailed information
     */
    public function show($id)
    {
        try {
            $driver = User::where('role', 'driver')
                ->with([
                    'location',
                    'driverLoads' => function($q) {
                        $q->with(['requester:id,name,phone'])
                          ->latest()
                          ->limit(10);
                    }
                ])
                ->withCount([
                    'driverLoads',
                    'driverLoads as completed_loads' => function($q) {
                        $q->where('status', 'delivered');
                    },
                    'driverLoads as active_loads' => function($q) {
                        $q->whereIn('status', ['approved', 'in_transit']);
                    },
                    'driverLoads as cancelled_loads' => function($q) {
                        $q->where('status', 'cancelled');
                    },
                ])
                ->findOrFail($id);

            // Calculate total revenue
            $totalRevenue = Load::where('driver_id', $id)
                ->where('status', 'delivered')
                ->sum('price');

            // Calculate this month revenue
            $monthRevenue = Load::where('driver_id', $id)
                ->where('status', 'delivered')
                ->whereMonth('created_at', Carbon::now()->month)
                ->whereYear('created_at', Carbon::now()->year)
                ->sum('price');

            // Get location history (last 50 points)
            $locationHistory = DriverLocation::where('driver_id', $id)
                ->orderBy('created_at', 'desc')
                ->limit(50)
                ->get();

            return response()->json([
                'success' => true,
                'message' => 'اطلاعات راننده با موفقیت دریافت شد',
                'data' => [
                    'driver' => $driver,
                    'statistics' => [
                        'total_revenue' => (float) $totalRevenue,
                        'month_revenue' => (float) $monthRevenue,
                    ],
                    'location_history' => $locationHistory,
                ],
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'راننده یافت نشد',
                'error' => $e->getMessage(),
            ], 404);
        }
    }

    /**
     * Get all currently active (online) drivers
     */
    public function activeDrivers(Request $request)
    {
        try {
            $drivers = User::where('role', 'driver')
                ->where('is_active', true)
                ->whereHas('location', function($q) {
                    $q->where('is_online', true)
                      ->where('last_ping_at', '>=', Carbon::now()->subMinutes(5));
                })
                ->with(['location', 'driverLoads' => function($q) {
                    $q->whereIn('status', ['approved', 'in_transit'])
                      ->with('requester:id,name,phone');
                }])
                ->get();

            return response()->json([
                'success' => true,
                'message' => 'لیست رانندگان آنلاین با موفقیت دریافت شد',
                'data' => [
                    'count' => $drivers->count(),
                    'drivers' => $drivers,
                ],
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت لیست رانندگان آنلاین',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get location history for a specific driver
     */
    public function locationHistory(Request $request, $id)
    {
        try {
            // Verify driver exists
            $driver = User::where('role', 'driver')->findOrFail($id);

            $query = DriverLocation::where('driver_id', $id);

            // Filter by date range
            if ($request->has('start_date') && $request->start_date) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }

            if ($request->has('end_date') && $request->end_date) {
                $query->whereDate('created_at', '<=', $request->end_date);
            } else {
                // Default to last 24 hours if no end date
                if (!$request->has('start_date')) {
                    $query->where('created_at', '>=', Carbon::now()->subHours(24));
                }
            }

            // Filter by online status
            if ($request->has('is_online') && $request->is_online !== null) {
                $query->where('is_online', $request->is_online);
            }

            // Sort
            $sortOrder = $request->get('sort_order', 'desc');
            $query->orderBy('created_at', $sortOrder);

            // Limit results
            $limit = $request->get('limit', 100);
            if ($limit > 1000) {
                $limit = 1000; // Maximum limit
            }

            $locations = $query->limit($limit)->get();

            // Calculate distance traveled
            $totalDistance = 0;
            $previousLocation = null;
            foreach ($locations as $location) {
                if ($previousLocation) {
                    $distance = DriverLocation::calculateDistance(
                        $previousLocation->latitude,
                        $previousLocation->longitude,
                        $location->latitude,
                        $location->longitude
                    );
                    $totalDistance += $distance;
                }
                $previousLocation = $location;
            }

            return response()->json([
                'success' => true,
                'message' => 'تاریخچه موقعیت راننده با موفقیت دریافت شد',
                'data' => [
                    'driver' => [
                        'id' => $driver->id,
                        'name' => $driver->name,
                        'phone' => $driver->phone,
                    ],
                    'locations' => $locations,
                    'statistics' => [
                        'total_points' => $locations->count(),
                        'distance_traveled_km' => round($totalDistance, 2),
                        'period' => [
                            'start' => $request->start_date ?? Carbon::now()->subHours(24)->format('Y-m-d H:i:s'),
                            'end' => $request->end_date ?? Carbon::now()->format('Y-m-d H:i:s'),
                        ],
                    ],
                ],
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت تاریخچه موقعیت',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Show map with online drivers
     */
    public function map()
    {
        $activeLoadDriverIds = Load::whereIn('status', ['approved', 'in_transit'])
            ->whereNotNull('driver_id')
            ->pluck('driver_id')
            ->unique();

        $locations = DriverLocation::with('driver:id,name,phone,vehicle_plate')
            ->whereNotNull('latitude')
            ->whereNotNull('longitude')
            ->get();

        $drivers = $locations->map(function ($location) use ($activeLoadDriverIds) {
            $isOnline = $location->is_online && $location->last_ping_at && $location->last_ping_at->gte(Carbon::now()->subMinutes(5));
            $status = 'offline';

            if ($isOnline) {
                $status = $activeLoadDriverIds->contains($location->driver_id) ? 'busy' : 'online';
            }

            return [
                'id' => $location->driver_id,
                'name' => $location->driver->name ?? 'نامشخص',
                'phone' => $location->driver->phone ?? '',
                'vehicle_plate' => $location->driver->vehicle_plate,
                'latitude' => (float) $location->latitude,
                'longitude' => (float) $location->longitude,
                'speed' => $location->speed,
                'heading' => $location->heading,
                'driver_status' => $status,
                'last_update' => $location->last_ping_at?->diffForHumans(),
            ];
        })->values();

        $onlineCount = $drivers->where('driver_status', 'online')->count();
        $busyCount = $drivers->where('driver_status', 'busy')->count();
        $offlineCount = $drivers->where('driver_status', 'offline')->count();

        $centerLat = $drivers->count() ? $drivers->avg('latitude') : 35.6892;
        $centerLng = $drivers->count() ? $drivers->avg('longitude') : 51.3890;

        return view('admin.map', [
            'neshanMapApiKey' => config('services.neshan.map_api_key'),
            'drivers' => $drivers,
            'onlineCount' => $onlineCount,
            'busyCount' => $busyCount,
            'offlineCount' => $offlineCount,
            'centerLat' => $centerLat,
            'centerLng' => $centerLng,
        ]);
    }

    /**
     * Refresh map data (AJAX)
     */
    public function mapRefresh()
    {
        try {
            $activeLoadDriverIds = Load::whereIn('status', ['approved', 'in_transit'])
                ->whereNotNull('driver_id')
                ->pluck('driver_id')
                ->unique();

            $drivers = DriverLocation::with('driver:id,name,phone,vehicle_plate')
                ->whereNotNull('latitude')
                ->whereNotNull('longitude')
                ->get()
                ->map(function($location) use ($activeLoadDriverIds) {
                    $isOnline = $location->is_online && $location->last_ping_at && $location->last_ping_at->gte(Carbon::now()->subMinutes(5));
                    $status = 'offline';

                    if ($isOnline) {
                        $status = $activeLoadDriverIds->contains($location->driver_id) ? 'busy' : 'online';
                    }

                    return [
                        'id' => $location->driver_id,
                        'name' => $location->driver->name ?? 'نامشخص',
                        'phone' => $location->driver->phone ?? '',
                        'vehicle_plate' => $location->driver->vehicle_plate,
                        'latitude' => (float) $location->latitude,
                        'longitude' => (float) $location->longitude,
                        'speed' => $location->speed,
                        'heading' => $location->heading,
                        'driver_status' => $status,
                        'last_update' => $location->last_ping_at?->diffForHumans(),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => $drivers,
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات راننده‌ها',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
