<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Trip;
use App\Models\TripRequest;
use App\Models\TaxiRequest;
use App\Services\PromotionalWheelService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TripController extends Controller
{
    /**
     * جلب رحلات السائق
     */
    public function getDriverTrips(Request $request)
    {
        try {
            $driver = Auth::user();
            
            // التحقق من أن المستخدم سائق
            if ($driver->user_type !== 'driver') {
                return response()->json([
                    'success' => false,
                    'message' => 'هذا المستخدم ليس سائق'
                ], 403);
            }

            // فلترة حسب الحالة والفترة
            $status = $request->query('status', 'all');
            $period = $request->query('period', 'all');
            
            $allTrips = collect();
            
            // جلب الرحلات من جدول trips
            $tripsQuery = Trip::with(['passenger:id,name,phone,profile_image'])
                ->where('driver_id', $driver->id);
            
            // فلترة حسب الحالة
            if ($status !== 'all') {
                switch ($status) {
                    case 'active':
                        $tripsQuery->active();
                        break;
                    case 'completed':
                        $tripsQuery->completed();
                        break;
                    case 'cancelled':
                        $tripsQuery->cancelled();
                        break;
                }
            }
            
            // فلترة حسب الفترة
            if ($period !== 'all') {
                $tripsQuery->byPeriod($period);
            }
            
            $trips = $tripsQuery->orderBy('created_at', 'desc')->get();
            
            // جلب الطلبات من trip_requests (النشطة + المكتملة حسب الفلتر)
            $requestsQuery = TripRequest::with(['passenger:id,name,phone,profile_image'])
                ->where('driver_id', $driver->id);
            
            // فلترة حسب الحالة
            if ($status !== 'all') {
                switch ($status) {
                    case 'active':
                    case 'accepted':
                    case 'in_progress':
                    case 'started':
                        $requestsQuery->whereIn('status', ['accepted', 'in_progress', 'active', 'started']);
                        break;
                    case 'completed':
                        $requestsQuery->where('status', 'completed');
                        break;
                    case 'cancelled':
                        $requestsQuery->whereIn('status', ['rejected', 'cancelled']);
                        break;
                }
            } else {
                $requestsQuery->whereIn('status', ['accepted', 'in_progress', 'active', 'started', 'completed']);
            }
            
            // فلترة حسب الفترة
            if ($period !== 'all') {
                $requestsQuery->where(function($q) use ($period) {
                    if ($period === 'today') {
                        $q->whereDate('created_at', today());
                    } elseif ($period === 'week') {
                        $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]);
                    } elseif ($period === 'month') {
                        $q->whereMonth('created_at', now()->month);
                    }
                });
            }
            
            $acceptedRequests = $requestsQuery->orderBy('created_at', 'desc')->get();
            
            // جلب الطلبات المقبولة من taxi_requests (الرحلات النشطة)
            $taxiRequestsQuery = TaxiRequest::where('driver_id', $driver->id)
                ->whereIn('status', ['accepted', 'in_progress', 'active', 'started', 'completed', 'cancelled']);
            
            // فلترة حسب الحالة
            if ($status !== 'all') {
                switch ($status) {
                    case 'active':
                    case 'accepted':
                    case 'in_progress':
                    case 'started':
                        $taxiRequestsQuery->whereIn('status', ['accepted', 'in_progress', 'active', 'started']);
                        break;
                    case 'completed':
                        $taxiRequestsQuery->where('status', 'completed');
                        break;
                    case 'cancelled':
                        $taxiRequestsQuery->where('status', 'cancelled');
                        break;
                }
            }
            
            // فلترة حسب الفترة
            if ($period !== 'all') {
                $taxiRequestsQuery->where(function($q) use ($period) {
                    if ($period === 'today') {
                        $q->whereDate('created_at', today());
                    } elseif ($period === 'week') {
                        $q->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]);
                    } elseif ($period === 'month') {
                        $q->whereMonth('created_at', now()->month);
                    }
                });
            }
            
            $acceptedTaxiRequests = $taxiRequestsQuery->orderBy('created_at', 'desc')->get();
            
            // تنسيق الرحلات من جدول trips
            $tripsArray = [];
            foreach ($trips as $trip) {
                $tripsArray[] = [
                    'id' => $trip->id,
                    'type' => 'trip',
                    'passenger' => [
                        'id' => $trip->passenger->id ?? null,
                        'name' => $trip->passenger->name ?? 'غير محدد',
                        'phone' => $trip->passenger->phone ?? 'غير محدد',
                        'rating' => 0.0,
                        'profile_image' => $trip->passenger->profile_image ?? null,
                    ],
                    'pickup' => $trip->pickup_location ?? 'غير محدد',
                    'destination' => $trip->dropoff_location ?? 'غير محدد',
                    'pickup_lat' => $trip->pickup_latitude ?? 0,
                    'pickup_lng' => $trip->pickup_longitude ?? 0,
                    'destination_lat' => $trip->dropoff_latitude ?? 0,
                    'destination_lng' => $trip->dropoff_longitude ?? 0,
                    'distance' => $trip->distance ? number_format($trip->distance, 1) . ' كم' : 'غير محدد',
                    'distance_value' => $trip->distance ?? 0,
                    'duration' => $trip->duration ? $trip->duration . ' دقيقة' : 'غير محدد',
                    'duration_value' => $trip->duration ?? 0,
                    'final_price' => $trip->fare ?? 0,
                    'status' => $trip->status ?? 'unknown',
                    'status_arabic' => $trip->status_arabic ?? 'غير معروف',
                    'status_color' => $trip->status_color ?? 'grey',
                    'start_time' => $trip->pickup_time ? $trip->pickup_time->format('H:i') : null,
                    'end_time' => $trip->dropoff_time ? $trip->dropoff_time->format('H:i') : null,
                    'driver_notes' => $trip->notes ?? '',
                    'passenger_notes' => $trip->notes ?? '',
                    'driver_rating' => $trip->driver_rating ?? 0,
                    'passenger_rating' => $trip->passenger_rating ?? 0,
                    'remaining_time' => null,
                    'total_earnings' => $trip->status === 'completed' ? ($trip->fare ?? 0) : 0,
                    'created_at' => $trip->created_at->format('Y-m-d H:i'),
                ];
            }
            
            // تنسيق الطلبات من trip_requests
            $tripRequestStatusMap = [
                'accepted' => ['status' => 'active', 'arabic' => 'نشطة', 'color' => 'blue'],
                'in_progress' => ['status' => 'in_progress', 'arabic' => 'قيد التنفيذ', 'color' => 'purple'],
                'active' => ['status' => 'active', 'arabic' => 'نشطة', 'color' => 'blue'],
                'started' => ['status' => 'in_progress', 'arabic' => 'قيد التنفيذ', 'color' => 'purple'],
                'completed' => ['status' => 'completed', 'arabic' => 'مكتملة', 'color' => 'green'],
                'rejected' => ['status' => 'cancelled', 'arabic' => 'ملغاة', 'color' => 'red'],
                'cancelled' => ['status' => 'cancelled', 'arabic' => 'ملغاة', 'color' => 'red'],
            ];
            $requestsArray = [];
            foreach ($acceptedRequests as $request) {
                $passenger = $request->passenger;
                $statusInfo = $tripRequestStatusMap[$request->status] ?? ['status' => $request->status, 'arabic' => 'غير معروف', 'color' => 'grey'];
                $requestsArray[] = [
                    'id' => $request->id,
                    'type' => 'trip_request',
                    'passenger' => [
                        'id' => $passenger->id ?? null,
                        'name' => $passenger->name ?? 'غير محدد',
                        'phone' => $passenger->phone ?? 'غير محدد',
                        'rating' => 0.0,
                        'profile_image' => $passenger->profile_image ?? null,
                    ],
                    'pickup' => $request->pickup_location ?? 'غير محدد',
                    'destination' => $request->destination_location ?? 'غير محدد',
                    'pickup_lat' => $request->pickup_lat ?? 0,
                    'pickup_lng' => $request->pickup_lng ?? 0,
                    'destination_lat' => $request->destination_lat ?? 0,
                    'destination_lng' => $request->destination_lng ?? 0,
                    'distance' => $request->distance ? number_format($request->distance, 1) . ' كم' : 'غير محدد',
                    'distance_value' => $request->distance ?? 0,
                    'duration' => $request->duration ? $request->duration . ' دقيقة' : 'غير محدد',
                    'duration_value' => $request->duration ?? 0,
                    'final_price' => $request->proposed_price ?? 0,
                    'status' => $statusInfo['status'],
                    'status_arabic' => $statusInfo['arabic'],
                    'status_color' => $statusInfo['color'],
                    'start_time' => $request->accepted_time ? $request->accepted_time->format('H:i') : ($request->accepted_at ? $request->accepted_at->format('H:i') : null),
                    'end_time' => $request->status === 'completed' ? ($request->updated_at ? $request->updated_at->format('H:i') : null) : null,
                    'driver_notes' => $request->notes ?? '',
                    'passenger_notes' => $request->notes ?? '',
                    'driver_rating' => 0,
                    'passenger_rating' => 0,
                    'remaining_time' => null,
                    'total_earnings' => $request->status === 'completed' ? ($request->proposed_price ?? 0) : 0,
                    'created_at' => $request->created_at->format('Y-m-d H:i'),
                ];
            }
            
            // تنسيق الطلبات من taxi_requests
            $taxiRequestsArray = [];
            foreach ($acceptedTaxiRequests as $request) {
                $statusMap = [
                    'accepted' => ['status' => 'active', 'arabic' => 'نشطة', 'color' => 'blue'],
                    'in_progress' => ['status' => 'in_progress', 'arabic' => 'قيد التنفيذ', 'color' => 'purple'],
                    'active' => ['status' => 'active', 'arabic' => 'نشطة', 'color' => 'blue'],
                    'started' => ['status' => 'in_progress', 'arabic' => 'قيد التنفيذ', 'color' => 'purple'],
                    'completed' => ['status' => 'completed', 'arabic' => 'مكتملة', 'color' => 'green'],
                    'cancelled' => ['status' => 'cancelled', 'arabic' => 'ملغاة', 'color' => 'red'],
                ];
                
                $statusInfo = $statusMap[$request->status] ?? ['status' => $request->status, 'arabic' => 'غير معروف', 'color' => 'grey'];
                
                $taxiRequestsArray[] = [
                    'id' => $request->id,
                    'type' => 'taxi_request',
                    'passenger' => [
                        'id' => $request->passenger_id ?? null,
                        'name' => $request->passenger_name ?? 'غير محدد',
                        'phone' => $request->passenger_phone ?? 'غير محدد',
                        'rating' => 0.0,
                        'profile_image' => null,
                    ],
                    'pickup' => $request->from_address ?? 'غير محدد',
                    'destination' => $request->to_address ?? 'غير محدد',
                    'pickup_lat' => $request->from_latitude ?? 0,
                    'pickup_lng' => $request->from_longitude ?? 0,
                    'destination_lat' => $request->to_latitude ?? 0,
                    'destination_lng' => $request->to_longitude ?? 0,
                    'distance' => $request->estimated_distance ? number_format($request->estimated_distance, 1) . ' كم' : 'غير محدد',
                    'distance_value' => $request->estimated_distance ?? 0,
                    'duration' => $request->estimated_duration ? $request->estimated_duration . ' دقيقة' : 'غير محدد',
                    'duration_value' => $request->estimated_duration ?? 0,
                    'final_price' => $request->price ?? 0,
                    'status' => $statusInfo['status'],
                    'status_arabic' => $statusInfo['arabic'],
                    'status_color' => $statusInfo['color'],
                    'start_time' => $request->accepted_at ? $request->accepted_at->format('H:i') : null,
                    'end_time' => $request->completed_at ? $request->completed_at->format('H:i') : null,
                    'driver_notes' => $request->notes ?? '',
                    'passenger_notes' => $request->notes ?? '',
                    'driver_rating' => 0,
                    'passenger_rating' => 0,
                    'remaining_time' => null,
                    'total_earnings' => $request->status === 'completed' ? ($request->price ?? 0) : 0,
                    'created_at' => $request->created_at->format('Y-m-d H:i'),
                ];
            }
            
            // دمج القوائم الثلاث
            $allTripsArray = array_merge($tripsArray, $requestsArray, $taxiRequestsArray);
            
            // ترتيب حسب التاريخ (الأحدث أولاً)
            usort($allTripsArray, function ($a, $b) {
                $dateA = strtotime($a['created_at']);
                $dateB = strtotime($b['created_at']);
                return $dateB <=> $dateA; // ترتيب تنازلي
            });
            
            // تنسيق البيانات النهائية
            $formattedTrips = collect($allTripsArray);

            return response()->json([
                'success' => true,
                'data' => $formattedTrips,
                'message' => 'تم جلب رحلات السائق بنجاح',
                'filters' => [
                    'status' => $status,
                    'period' => $period,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في جلب الرحلات: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * جلب إحصائيات رحلات السائق
     */
    public function getDriverStats()
    {
        try {
            $driver = Auth::user();
            
            // التحقق من أن المستخدم سائق
            if ($driver->user_type !== 'driver') {
                return response()->json([
                    'success' => false,
                    'message' => 'هذا المستخدم ليس سائق'
                ], 403);
            }

            $tripCount = Trip::where('driver_id', $driver->id)->count();
            $tripRequestCount = TripRequest::where('driver_id', $driver->id)->count();
            $taxiRequestCount = TaxiRequest::where('driver_id', $driver->id)->count();

            $tripEarnings = (float) Trip::where('driver_id', $driver->id)->completed()->sum('fare');
            $tripRequestEarnings = (float) TripRequest::where('driver_id', $driver->id)->where('status', 'completed')->sum('proposed_price');
            $taxiRequestEarnings = (float) TaxiRequest::where('driver_id', $driver->id)->where('status', 'completed')->sum('price');

            $stats = [
                'total_trips' => $tripCount + $tripRequestCount + $taxiRequestCount,
                'active_trips' => Trip::where('driver_id', $driver->id)->active()->count()
                    + TripRequest::where('driver_id', $driver->id)->whereIn('status', ['accepted', 'in_progress', 'active', 'started'])->count()
                    + TaxiRequest::where('driver_id', $driver->id)->whereIn('status', ['accepted', 'in_progress', 'active', 'started'])->count(),
                'completed_trips' => Trip::where('driver_id', $driver->id)->completed()->count()
                    + TripRequest::where('driver_id', $driver->id)->where('status', 'completed')->count()
                    + TaxiRequest::where('driver_id', $driver->id)->where('status', 'completed')->count(),
                'cancelled_trips' => Trip::where('driver_id', $driver->id)->cancelled()->count()
                    + TripRequest::where('driver_id', $driver->id)->whereIn('status', ['rejected', 'cancelled'])->count()
                    + TaxiRequest::where('driver_id', $driver->id)->whereIn('status', ['rejected', 'cancelled'])->count(),
                'total_earnings' => $tripEarnings + $tripRequestEarnings + $taxiRequestEarnings,
                'average_rating' => Trip::where('driver_id', $driver->id)
                    ->whereNotNull('driver_rating')
                    ->avg('driver_rating') ?? 0,
                'total_distance' => Trip::where('driver_id', $driver->id)->sum('distance'),
                'total_duration' => Trip::where('driver_id', $driver->id)->sum('duration'),
            ];

            $stats['today_trips'] = Trip::where('driver_id', $driver->id)->whereDate('created_at', today())->count()
                + TripRequest::where('driver_id', $driver->id)->whereDate('created_at', today())->count()
                + TaxiRequest::where('driver_id', $driver->id)->whereDate('created_at', today())->count();
            $stats['week_trips'] = Trip::where('driver_id', $driver->id)->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count()
                + TripRequest::where('driver_id', $driver->id)->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count()
                + TaxiRequest::where('driver_id', $driver->id)->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count();
            $stats['month_trips'] = Trip::where('driver_id', $driver->id)->whereMonth('created_at', now()->month)->count()
                + TripRequest::where('driver_id', $driver->id)->whereMonth('created_at', now()->month)->count()
                + TaxiRequest::where('driver_id', $driver->id)->whereMonth('created_at', now()->month)->count();

            return response()->json([
                'success' => true,
                'data' => $stats,
                'message' => 'تم جلب إحصائيات السائق بنجاح'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في جلب الإحصائيات: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * تحديث حالة الرحلة
     */
    public function updateTripStatus(Request $request, $tripId)
    {
        try {
            $driver = Auth::user();
            
            // التحقق من أن المستخدم سائق
            if ($driver->user_type !== 'driver') {
                return response()->json([
                    'success' => false,
                    'message' => 'هذا المستخدم ليس سائق'
                ], 403);
            }

            $request->validate([
                'status' => 'required|in:active,completed,cancelled',
                'notes' => 'nullable|string|max:500',
                'type' => 'nullable|string|in:trip,trip_request,taxi_request',
            ]);

            $tripType = $request->type ?? null;
            $newStatus = $request->status;

            // محاولة تحديد نوع الرحلة تلقائياً إذا لم يتم تحديده
            if (!$tripType) {
                $trip = Trip::where('id', $tripId)->where('driver_id', $driver->id)->first();
                $tripRequest = TripRequest::where('id', $tripId)->where('driver_id', $driver->id)->first();
                $taxiRequest = TaxiRequest::where('id', $tripId)->where('driver_id', $driver->id)->first();
                
                if ($trip) {
                    $tripType = 'trip';
                } elseif ($tripRequest) {
                    $tripType = 'trip_request';
                } elseif ($taxiRequest) {
                    $tripType = 'taxi_request';
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => 'الرحلة غير موجودة'
                    ], 404);
                }
            }

            // معالجة تحديث الحالة حسب النوع
            if ($tripType === 'trip') {
                $trip = Trip::where('id', $tripId)
                    ->where('driver_id', $driver->id)
                    ->first();

                if (!$trip) {
                    return response()->json([
                        'success' => false,
                        'message' => 'الرحلة غير موجودة'
                    ], 404);
                }

                $oldStatus = $trip->status;
                $trip->status = $newStatus;
                
                // تحديث الأوقات حسب الحالة
                if ($newStatus === 'active' && $oldStatus !== 'active') {
                    $trip->pickup_time = $trip->pickup_time ?? now();
                } elseif ($newStatus === 'completed' && $oldStatus !== 'completed') {
                    $trip->dropoff_time = $trip->dropoff_time ?? now();
                }
                
                if ($request->notes) {
                    $trip->driver_notes = $request->notes;
                }
                
                $trip->save();

                if ($newStatus === 'completed' && $oldStatus !== 'completed') {
                    try {
                        $fare = (float) ($trip->fare ?? 0);
                        if ($fare > 0) {
                            \App\Services\DriverCashbackService::addCashbackForCompletedTrip(
                                $driver->id,
                                $fare,
                                $trip->request_id,
                                $trip->id,
                                $trip->driver_rating ? (float) $trip->driver_rating : null
                            );
                        }
                    } catch (\Exception $e) {
                        \Log::warning('Driver cashback error: ' . $e->getMessage());
                    }
                }

                return response()->json([
                    'success' => true,
                    'message' => 'تم تحديث حالة الرحلة بنجاح',
                    'data' => [
                        'trip_id' => $trip->id,
                        'type' => 'trip',
                        'status' => $trip->status,
                        'status_arabic' => $trip->status_arabic ?? 'محدث',
                        'updated_at' => now()->format('Y-m-d H:i:s'),
                    ]
                ]);
            } elseif ($tripType === 'trip_request') {
                $tripRequest = TripRequest::where('id', $tripId)
                    ->where('driver_id', $driver->id)
                    ->first();

                if (!$tripRequest) {
                    return response()->json([
                        'success' => false,
                        'message' => 'الرحلة غير موجودة'
                    ], 404);
                }

                $oldTripRequestStatus = $tripRequest->status;

                // تحويل الحالة
                $statusMap = [
                    'active' => 'in_progress',
                    'completed' => 'completed',
                    'cancelled' => 'cancelled',
                ];
                
                $newRequestStatus = $statusMap[$newStatus] ?? $newStatus;
                
                $tripRequest->update([
                    'status' => $newRequestStatus,
                    'notes' => $request->notes ?? $tripRequest->notes,
                ]);

                if ($newStatus === 'completed') {
                    if (\Schema::hasColumn('trip_requests', 'completed_at')) {
                        $tripRequest->update(['completed_at' => now()]);
                    }
                    $completedFare = (float) ($tripRequest->proposed_price ?? 0);
                    try {
                        if ($completedFare > 0) {
                            \App\Services\DriverCashbackService::addCashbackForCompletedTrip(
                                $driver->id,
                                $completedFare,
                                $tripRequest->id,
                                null,
                                null
                            );
                        }
                    } catch (\Exception $e) {
                        \Log::warning('Driver cashback error: ' . $e->getMessage());
                    }

                    if ($oldTripRequestStatus !== 'completed') {
                        try {
                            PromotionalWheelService::onOrderCompleted(
                                'trip',
                                (int) $tripRequest->id,
                                $completedFare
                            );
                        } catch (\Throwable $e) {
                            \Log::error('PromotionalWheelService trip_request: '.$e->getMessage());
                        }
                    }
                }

                return response()->json([
                    'success' => true,
                    'message' => 'تم تحديث حالة الرحلة بنجاح',
                    'data' => [
                        'trip_id' => $tripRequest->id,
                        'type' => 'trip_request',
                        'status' => $newStatus,
                        'status_arabic' => $newStatus === 'completed' ? 'مكتملة' : ($newStatus === 'cancelled' ? 'ملغاة' : 'قيد التنفيذ'),
                    ]
                ]);
            } else {
                // taxi_request
                $taxiRequest = TaxiRequest::where('id', $tripId)
                    ->where('driver_id', $driver->id)
                    ->first();

                if (!$taxiRequest) {
                    return response()->json([
                        'success' => false,
                        'message' => 'الرحلة غير موجودة'
                    ], 404);
                }

                // تحويل الحالة
                $statusMap = [
                    'active' => 'in_progress',
                    'completed' => 'completed',
                    'cancelled' => 'cancelled',
                ];
                
                $newRequestStatus = $statusMap[$newStatus] ?? $newStatus;
                
                $updateData = [
                    'status' => $newRequestStatus,
                ];
                
                if ($request->notes) {
                    $updateData['notes'] = $request->notes;
                }
                
                if ($newStatus === 'completed') {
                    $updateData['completed_at'] = now();
                } elseif ($newStatus === 'cancelled') {
                    $updateData['cancelled_at'] = now();
                }
                
                $taxiRequest->update($updateData);

                if ($newStatus === 'completed') {
                    try {
                        $fare = (float) ($taxiRequest->price ?? 0);
                        if ($fare > 0) {
                            \App\Services\DriverCashbackService::addCashbackForCompletedTrip(
                                $driver->id,
                                $fare,
                                null,
                                null,
                                null
                            );
                        }
                    } catch (\Exception $e) {
                        \Log::warning('Driver cashback error (taxi_request): ' . $e->getMessage());
                    }
                }

                return response()->json([
                    'success' => true,
                    'message' => 'تم تحديث حالة الرحلة بنجاح',
                    'data' => [
                        'trip_id' => $taxiRequest->id,
                        'type' => 'taxi_request',
                        'status' => $newStatus,
                        'status_arabic' => $newStatus === 'completed' ? 'مكتملة' : ($newStatus === 'cancelled' ? 'ملغاة' : 'قيد التنفيذ'),
                        'updated_at' => now()->format('Y-m-d H:i:s'),
                    ]
                ]);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في تحديث حالة الرحلة: ' . $e->getMessage()
            ], 500);
        }
    }
}
