<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\WorkingArea;
use App\Models\DriverWorkArea;
use App\Models\DriverCustomArea;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DriverController extends Controller
{
    /**
     * Get available work areas for the driver based on their province
     */
    public function getAvailableWorkAreas()
    {
        try {
            // افتراض أن السائق من الناصرية (يمكن تغيير هذا لاحقاً)
            $driverProvince = 'ذي قار';
            
            $workAreas = WorkingArea::where('province_ar', $driverProvince)
                ->where('is_active', true)
                ->get();
            
            return response()->json([
                'success' => true,
                'data' => $workAreas,
                'message' => 'تم جلب مناطق العمل المتاحة بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في جلب مناطق العمل: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get selected work areas for the driver
     */
    public function getSelectedWorkAreas()
    {
        try {
            $driverId = Auth::id();
            
            $selectedAreas = DriverWorkArea::with('workingArea')
                ->where('driver_id', $driverId)
                ->where('is_active', true)
                ->orderBy('priority', 'asc')
                ->get();
            
            return response()->json([
                'success' => true,
                'data' => $selectedAreas,
                'message' => 'تم جلب مناطق العمل المختارة بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في جلب المناطق المختارة: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Select work areas for the driver
     */
    public function selectWorkAreas(Request $request)
    {
        try {
            $request->validate([
                'work_area_ids' => 'required|array|min:1',
                'work_area_ids.*' => 'integer|exists:working_areas,id',
                'priorities' => 'required|array|min:1',
                'priorities.*' => 'integer|min:1',
            ]);

            $driverId = Auth::id();
            
            // حذف الاختيارات السابقة
            DriverWorkArea::where('driver_id', $driverId)->delete();
            
            // إضافة الاختيارات الجديدة
            foreach ($request->work_area_ids as $index => $workAreaId) {
                DriverWorkArea::create([
                    'driver_id' => $driverId,
                    'working_area_id' => $workAreaId,
                    'priority' => $request->priorities[$index] ?? ($index + 1),
                    'is_active' => true,
                ]);
            }
            
            return response()->json([
                'success' => true,
                'message' => 'تم حفظ اختيارات مناطق العمل بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في حفظ اختيارات المناطق: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * جلب المناطق المخصصة المرسومة من السائق
     */
    public function getCustomAreas()
    {
        try {
            $driverId = Auth::id();
            $areas = DriverCustomArea::where('driver_id', $driverId)
                ->where('is_active', true)
                ->orderBy('created_at', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $areas,
                'message' => 'تم جلب المناطق المخصصة بنجاح',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * حفظ منطقة مخصصة مرسومة على الخريطة
     */
    public function saveCustomArea(Request $request)
    {
        try {
            $request->validate([
                'name' => 'nullable|string|max:100',
                'boundaries' => 'required|array',
                'center_lat' => 'required|numeric',
                'center_lng' => 'required|numeric',
            ]);

            $driverId = Auth::id();

            DriverCustomArea::create([
                'driver_id' => $driverId,
                'name' => $request->name ?? 'منطقتي',
                'boundaries' => $request->boundaries,
                'center_lat' => $request->center_lat,
                'center_lng' => $request->center_lng,
                'is_active' => true,
            ]);

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

    /**
     * حذف منطقة مخصصة
     */
    public function deleteCustomArea($areaId)
    {
        try {
            $driverId = Auth::id();
            DriverCustomArea::where('driver_id', $driverId)
                ->where('id', $areaId)
                ->delete();

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

    /**
     * Remove a work area from driver's selection
     */
    public function removeWorkArea($workAreaId)
    {
        try {
            $driverId = Auth::id();
            
            DriverWorkArea::where('driver_id', $driverId)
                ->where('working_area_id', $workAreaId)
                ->delete();
            
            return response()->json([
                'success' => true,
                'message' => 'تم إزالة منطقة العمل بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في إزالة منطقة العمل: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update driver location
     */
    public function updateLocation(Request $request)
    {
        try {
            $request->validate([
                'latitude' => 'required|numeric',
                'longitude' => 'required|numeric',
            ]);

            $user = Auth::user();
            $user->update([
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
            ]);

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

    /**
     * Get driver dashboard data
     */
    public function dashboard()
    {
        try {
            $driverId = Auth::id();
            
            // إحصائيات بسيطة
            $selectedAreasCount = DriverWorkArea::where('driver_id', $driverId)
                ->where('is_active', true)
                ->count();
            
            return response()->json([
                'success' => true,
                'data' => [
                    'selected_areas_count' => $selectedAreasCount,
                    'driver_info' => Auth::user(),
                ],
                'message' => 'تم جلب بيانات لوحة التحكم بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطأ في جلب بيانات لوحة التحكم: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all drivers (for passengers to see available drivers)
     */
    public function getAllDrivers(Request $request)
    {
        try {
            $query = User::with(['governorate', 'city'])
                ->where('user_type', 'driver')
                ->where('status', 'active')
                ->select([
                    'id', 'name', 'phone', 'email', 'profile_image', 
                    'latitude', 'longitude', 'status', 'created_at', 'updated_at',
                    'governorate_id', 'city_id'
                ]);

            // تصفية حسب المحافظة إذا تم توفيرها
            if ($request->has('governorate_id') && $request->governorate_id) {
                $query->where('governorate_id', $request->governorate_id);
                \Log::info('تصفية السائقين حسب المحافظة: ' . $request->governorate_id);
            }

            // تصفية حسب المدينة إذا تم توفيرها
            if ($request->has('city_id') && $request->city_id) {
                $query->where('city_id', $request->city_id);
                \Log::info('تصفية السائقين حسب المدينة: ' . $request->city_id);
            }

            $drivers = $query->get()->map(function ($driver) {
                $vehicle = \App\Models\Vehicle::where('driver_id', $driver->id)->first();
                return [
                    'id' => $driver->id,
                    'name' => $driver->name,
                    'phone' => $driver->phone,
                    'email' => $driver->email,
                    'profile_image' => $driver->profile_image,
                    'rating' => 4.0, // قيمة افتراضية
                    'total_trips' => 0, // قيمة افتراضية
                    'vehicle_info' => $vehicle ? [
                        'type' => $vehicle->vehicle_type ?? 'سيارة',
                        'color' => $vehicle->color ?? 'غير محدد',
                        'license_plate' => $vehicle->plate_number ?? 'غير محدد',
                        'brand' => $vehicle->brand ?? '',
                        'model' => $vehicle->model ?? '',
                        'year' => $vehicle->year ?? null,
                        'has_ac' => (bool) ($vehicle->has_ac ?? true),
                        'passenger_count' => (int) ($vehicle->passenger_count ?? 4),
                        'is_4wd' => (bool) ($vehicle->is_4wd ?? false),
                        'service_type' => $vehicle->service_type ?? 'taxi',
                    ] : [
                        'type' => 'سيارة',
                        'color' => 'غير محدد',
                        'license_plate' => 'غير محدد',
                        'has_ac' => true,
                        'passenger_count' => 4,
                        'is_4wd' => false,
                        'service_type' => 'taxi',
                    ],
                    'location' => [
                        'latitude' => $driver->latitude ?? 33.3152,
                        'longitude' => $driver->longitude ?? 44.3661,
                        'city' => $driver->city ? $driver->city->name : 'غير محدد',
                        'governorate' => $driver->governorate ? $driver->governorate->name : 'غير محدد'
                    ],
                    'governorate_id' => $driver->governorate_id,
                    'city_id' => $driver->city_id,
                    'status' => $driver->status,
                    'last_seen' => $driver->updated_at,
                    'current_status' => 'idle',
                    'is_online' => $driver->status === 'active',
                ];
            });

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

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

    /**
     * Get nearby drivers
     */
    public function getNearbyDrivers(Request $request)
    {
        try {
            $request->validate([
                'lat' => 'required|numeric',
                'lng' => 'required|numeric',
                'radius' => 'numeric|min:1|max:100'
            ]);

            $lat = $request->lat;
            $lng = $request->lng;
            $radius = $request->radius ?? 10; // 10 كم افتراضي

            // حساب المسافة باستخدام Haversine formula
            $drivers = User::with(['governorate', 'city'])
                ->where('user_type', 'driver')
                ->where('status', 'active')
                ->whereNotNull('latitude')
                ->whereNotNull('longitude')
                ->select([
                    'id', 'name', 'phone', 'email', 'profile_image', 
                    'latitude', 'longitude', 'status', 'created_at', 'updated_at',
                    'governorate_id', 'city_id',
                    DB::raw("(6371 * acos(cos(radians($lat)) * cos(radians(latitude)) * cos(radians(longitude) - radians($lng)) + sin(radians($lat)) * sin(radians(latitude)))) AS distance")
                ])
                ->having('distance', '<=', $radius)
                ->orderBy('distance')
                ->get()
                ->map(function ($driver) {
                    $vehicle = \App\Models\Vehicle::where('driver_id', $driver->id)->first();
                    return [
                        'id' => $driver->id,
                        'name' => $driver->name,
                        'phone' => $driver->phone,
                        'email' => $driver->email,
                        'profile_image' => $driver->profile_image,
                        'rating' => 4.0, // قيمة افتراضية
                        'total_trips' => 0, // قيمة افتراضية
                        'vehicle_info' => $vehicle ? [
                            'type' => $vehicle->vehicle_type ?? 'سيارة',
                            'color' => $vehicle->color ?? 'غير محدد',
                            'license_plate' => $vehicle->plate_number ?? 'غير محدد',
                            'brand' => $vehicle->brand ?? '',
                            'model' => $vehicle->model ?? '',
                            'year' => $vehicle->year ?? null,
                            'has_ac' => (bool) ($vehicle->has_ac ?? true),
                            'passenger_count' => (int) ($vehicle->passenger_count ?? 4),
                            'is_4wd' => (bool) ($vehicle->is_4wd ?? false),
                            'service_type' => $vehicle->service_type ?? 'taxi',
                        ] : [
                            'type' => 'سيارة',
                            'color' => 'غير محدد',
                            'license_plate' => 'غير محدد',
                            'has_ac' => true,
                            'passenger_count' => 4,
                            'is_4wd' => false,
                            'service_type' => 'taxi',
                        ],
                        'location' => [
                            'latitude' => $driver->latitude,
                            'longitude' => $driver->longitude,
                            'city' => $driver->city ? $driver->city->name : 'غير محدد',
                            'governorate' => $driver->governorate ? $driver->governorate->name : 'غير محدد'
                        ],
                        'governorate_id' => $driver->governorate_id,
                        'city_id' => $driver->city_id,
                        'status' => $driver->status,
                        'last_seen' => $driver->updated_at,
                        'current_status' => 'idle',
                        'is_online' => $driver->status === 'active',
                        'distance' => round($driver->distance, 2)
                    ];
                });

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

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

    /**
     * Request taxi from specific driver - FIXED VERSION
     */
    public function requestTaxi(Request $request, $driverId)
    {
        try {
            // Validation
            $request->validate([
                'pickup_lat' => 'required|numeric',
                'pickup_lng' => 'required|numeric',
                'destination_lat' => 'required|numeric',
                'destination_lng' => 'required|numeric',
                'fare' => 'nullable|numeric|min:0',
                'notes' => 'nullable|string|max:500',
                'pickup_address' => 'required|string|max:500',
                'destination_address' => 'required|string|max:500',
            ], [
                'pickup_address.required' => 'عنوان نقطة الانطلاق مطلوب',
                'destination_address.required' => 'عنوان الوجهة مطلوب',
                'pickup_lat.required' => 'خط عرض نقطة الانطلاق مطلوب',
                'pickup_lng.required' => 'خط طول نقطة الانطلاق مطلوب',
                'destination_lat.required' => 'خط عرض الوجهة مطلوب',
                'destination_lng.required' => 'خط طول الوجهة مطلوب',
            ]);

            $passenger = Auth::user();
            $driver = User::where('id', $driverId)
                         ->where('user_type', 'driver')
                         ->where('status', 'active')
                         ->first();

            if (!$driver) {
                return response()->json([
                    'success' => false,
                    'message' => 'السائق غير متاح'
                ], 404);
            }

            // حساب المسافة التقريبية
            $distance = $this->calculateDistance(
                $request->pickup_lat, $request->pickup_lng,
                $request->destination_lat, $request->destination_lng
            );
            
            // استخدام العنوان الفعلي من الطلب
            $pickupAddress = $request->pickup_address ?? 'موقع الراكب';
            $destinationAddress = $request->destination_address ?? 'الوجهة المطلوبة';
            
            // استخدام Model بدلاً من DB::table لتجنب مشاكل الأعمدة
            $tripRequest = \App\Models\TripRequest::create([
                'passenger_id' => $passenger->id,
                'driver_id' => $driverId,
                'pickup_location' => $pickupAddress,
                'pickup_location_ar' => $pickupAddress,
                'pickup_lat' => $request->pickup_lat,
                'pickup_lng' => $request->pickup_lng,
                'destination_location' => $destinationAddress,
                'destination_location_ar' => $destinationAddress,
                'destination_lat' => $request->destination_lat,
                'destination_lng' => $request->destination_lng,
                'distance' => $distance, // إضافة المسافة المحسوبة
                'duration' => max(1, (int)($distance * 2)), // تقدير المدة (دقائق) - على الأقل دقيقة واحدة
                'proposed_price' => $request->fare ?? ($distance * 1000), // استخدام السعر المرسل أو حساب تلقائي بناءً على المسافة
                'notes' => $request->notes ?? '',
                'status' => 'pending',
                'request_time' => now(),
                'expires_at' => now()->addMinutes(10), // انتهاء صلاحية الطلب بعد 10 دقائق
            ]);

            return response()->json([
                'success' => true,
                'data' => [
                    'trip_request_id' => $tripRequest->id,
                    'driver' => [
                        'id' => $driver->id,
                        'name' => $driver->name,
                        'phone' => $driver->phone
                    ]
                ],
                'message' => 'تم إرسال طلب التاكسي بنجاح'
            ], 200, [], JSON_UNESCAPED_UNICODE);

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

    /**
     * جلب طلبات التاكسي للمستخدم الحالي
     */
    public function getMyTripRequests()
    {
        try {
            $user = Auth::user();
            
            // إنشاء طلب تجريبي إذا لم توجد طلبات
            $existingRequests = \App\Models\TripRequest::where('passenger_id', $user->id)->count();
            
            if ($existingRequests == 0) {
                // إنشاء طلب تجريبي
                \App\Models\TripRequest::create([
                    'passenger_id' => $user->id,
                    'driver_id' => 1, // سائق افتراضي
                    'pickup_location' => 'موقع تجريبي',
                    'pickup_location_ar' => 'موقع تجريبي',
                    'destination_location' => 'وجهة تجريبية',
                    'destination_location_ar' => 'وجهة تجريبية',
                    'pickup_lat' => 31.0473367,
                    'pickup_lng' => 46.3071033,
                    'destination_lat' => 31.044510,
                    'destination_lng' => 46.270650,
                    'distance' => 3.5,
                    'duration' => 7,
                    'proposed_price' => 15000,
                    'notes' => 'طلب تجريبي للاختبار',
                    'status' => 'pending',
                    'request_time' => now(),
                    'expires_at' => now()->addMinutes(10),
                ]);
            }
            
            $tripRequests = \App\Models\TripRequest::where('passenger_id', $user->id)
                ->with(['driver'])
                ->orderBy('created_at', 'desc')
                ->get();

            $formattedRequests = $tripRequests->map(function ($request) {
                return [
                    'id' => $request->id,
                    'status' => $request->status,
                    'pickup_location' => $request->pickup_location,
                    'pickup_location_ar' => $request->pickup_location_ar,
                    'destination_location' => $request->destination_location,
                    'destination_location_ar' => $request->destination_location_ar,
                    'pickup_lat' => $request->pickup_lat,
                    'pickup_lng' => $request->pickup_lng,
                    'destination_lat' => $request->destination_lat,
                    'destination_lng' => $request->destination_lng,
                    'distance' => $request->distance,
                    'duration' => $request->duration,
                    'proposed_price' => $request->proposed_price,
                    'notes' => $request->notes,
                    'request_time' => $request->request_time,
                    'expires_at' => $request->expires_at,
                    'accepted_at' => $request->accepted_at,
                    'rejected_at' => $request->rejected_at,
                    'wheel_milestone_pending' => (bool) ($request->wheel_milestone_pending ?? false),
                    'wheel_promo_fee_amount' => $request->wheel_promo_fee_amount,
                    'wheel_result' => $request->wheel_result,
                    'wheel_spun_at' => $request->wheel_spun_at,
                    'driver' => $request->driver ? [
                        'id' => $request->driver->id,
                        'name' => $request->driver->name,
                        'phone' => $request->driver->phone,
                        'rating' => $request->driver->rating ?? 4.0,
                        'vehicle_info' => $request->driver->vehicle_info,
                    ] : [
                        'id' => 1,
                        'name' => 'سائق تجريبي',
                        'phone' => '07801234567',
                        'rating' => 4.5,
                        'vehicle_info' => 'تويوتا كامري - 2020',
                    ],
                    'created_at' => $request->created_at,
                ];
            });

            return response()->json([
                'success' => true,
                'data' => [
                    'trip_requests' => $formattedRequests
                ],
                'message' => 'تم جلب طلبات التاكسي بنجاح'
            ], 200, [], JSON_UNESCAPED_UNICODE);

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

    /**
     * حساب المسافة بين نقطتين باستخدام Haversine formula
     */
    private function calculateDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6371; // نصف قطر الأرض بالكيلومتر

        $dLat = deg2rad($lat2 - $lat1);
        $dLng = deg2rad($lng2 - $lng1);

        $a = sin($dLat/2) * sin($dLat/2) +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($dLng/2) * sin($dLng/2);

        $c = 2 * atan2(sqrt($a), sqrt(1-$a));

        return $earthRadius * $c; // المسافة بالكيلومتر
    }
}
