<?php

namespace App\Http\Controllers\Api;

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

class TaxiRequestController extends Controller
{
    /**
     * إنشاء طلب تاكسي جديد
     */
    public function createRequest(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'passenger_id' => 'required|string',
                'passenger_name' => 'required|string|max:255',
                'passenger_phone' => 'required|string|max:20',
                'from_latitude' => 'required|numeric',
                'from_longitude' => 'required|numeric',
                'from_address' => 'required|string|max:500',
                'to_latitude' => 'required|numeric',
                'to_longitude' => 'required|numeric',
                'to_address' => 'required|string|max:500',
                'price' => 'required|numeric|min:0',
                'notes' => 'nullable|string|max:1000',
                'estimated_duration' => 'nullable|integer|min:0',
                'estimated_distance' => 'nullable|numeric|min:0',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'بيانات غير صحيحة',
                    'errors' => $validator->errors()
                ], 422);
            }

            $user = Auth::user();

            // إنشاء طلب التاكسي
            $taxiRequest = TaxiRequest::create([
                'passenger_id' => $request->passenger_id,
                'passenger_name' => $request->passenger_name,
                'passenger_phone' => $request->passenger_phone,
                'from_latitude' => $request->from_latitude,
                'from_longitude' => $request->from_longitude,
                'from_address' => $request->from_address,
                'to_latitude' => $request->to_latitude,
                'to_longitude' => $request->to_longitude,
                'to_address' => $request->to_address,
                'price' => $request->price,
                'notes' => $request->notes,
                'status' => 'pending',
                'estimated_duration' => $request->estimated_duration ?? 0,
                'estimated_distance' => $request->estimated_distance ?? 0.0,
                'created_at' => now(),
            ]);

            // إرسال إشعارات للسائقين المتاحين
            try {
                $notificationController = new \App\Http\Controllers\Api\NotificationController();
                $notificationController->notifyNewTaxiRequest(new \Illuminate\Http\Request([
                    'request_id' => (string)$taxiRequest->id,
                    'passenger_name' => $taxiRequest->passenger_name,
                    'from_address' => $taxiRequest->from_address,
                    'to_address' => $taxiRequest->to_address,
                    'price' => $taxiRequest->price,
                ]));
                \Log::info("تم إرسال إشعارات طلب تاكسي جديد للسائقين - الطلب ID: {$taxiRequest->id}");
            } catch (\Exception $e) {
                \Log::error("خطأ في إرسال إشعارات طلب تاكسي: " . $e->getMessage());
                // لا نوقف العملية إذا فشل إرسال الإشعارات
            }

            return response()->json([
                'success' => true,
                'message' => 'تم إنشاء طلب التاكسي بنجاح',
                'data' => [
                    'id' => $taxiRequest->id,
                    'passenger_id' => $taxiRequest->passenger_id,
                    'passenger_name' => $taxiRequest->passenger_name,
                    'passenger_phone' => $taxiRequest->passenger_phone,
                    'from_latitude' => $taxiRequest->from_latitude,
                    'from_longitude' => $taxiRequest->from_longitude,
                    'from_address' => $taxiRequest->from_address,
                    'to_latitude' => $taxiRequest->to_latitude,
                    'to_longitude' => $taxiRequest->to_longitude,
                    'to_address' => $taxiRequest->to_address,
                    'price' => $taxiRequest->price,
                    'notes' => $taxiRequest->notes,
                    'status' => $taxiRequest->status,
                    'estimated_duration' => $taxiRequest->estimated_duration,
                    'estimated_distance' => $taxiRequest->estimated_distance,
                    'created_at' => $taxiRequest->created_at->toISOString(),
                ]
            ], 201);

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

    /**
     * جلب تفاصيل طلب تاكسي
     */
    public function getRequestDetails($id)
    {
        try {
            $taxiRequest = TaxiRequest::findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $taxiRequest->id,
                    'passenger_id' => $taxiRequest->passenger_id,
                    'passenger_name' => $taxiRequest->passenger_name,
                    'passenger_phone' => $taxiRequest->passenger_phone,
                    'driver_id' => $taxiRequest->driver_id,
                    'driver_name' => $taxiRequest->driver_name,
                    'driver_phone' => $taxiRequest->driver_phone,
                    'from_latitude' => $taxiRequest->from_latitude,
                    'from_longitude' => $taxiRequest->from_longitude,
                    'from_address' => $taxiRequest->from_address,
                    'to_latitude' => $taxiRequest->to_latitude,
                    'to_longitude' => $taxiRequest->to_longitude,
                    'to_address' => $taxiRequest->to_address,
                    'price' => $taxiRequest->price,
                    'notes' => $taxiRequest->notes,
                    'status' => $taxiRequest->status,
                    'estimated_duration' => $taxiRequest->estimated_duration,
                    'estimated_distance' => $taxiRequest->estimated_distance,
                    'created_at' => $taxiRequest->created_at->toISOString(),
                    'accepted_at' => $taxiRequest->accepted_at ? $taxiRequest->accepted_at->toISOString() : null,
                    'completed_at' => $taxiRequest->completed_at ? $taxiRequest->completed_at->toISOString() : null,
                ]
            ]);

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

    /**
     * جلب طلبات الراكب
     */
    public function getPassengerRequests(Request $request)
    {
        try {
            $user = Auth::user();
            
            $requests = TaxiRequest::where('passenger_id', $user->id)
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($request) {
                    return [
                        'id' => $request->id,
                        'from_address' => $request->from_address,
                        'to_address' => $request->to_address,
                        'price' => $request->price,
                        'status' => $request->status,
                        'driver_name' => $request->driver_name,
                        'driver_phone' => $request->driver_phone,
                        'created_at' => $request->created_at->toISOString(),
                        'accepted_at' => $request->accepted_at ? $request->accepted_at->toISOString() : null,
                    ];
                });

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

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

    /**
     * إلغاء طلب تاكسي
     */
    public function cancelRequest($id)
    {
        try {
            $taxiRequest = TaxiRequest::findOrFail($id);
            $user = Auth::user();

            // التحقق من أن المستخدم هو صاحب الطلب
            if ($taxiRequest->passenger_id != $user->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'ليس لديك صلاحية لإلغاء هذا الطلب'
                ], 403);
            }

            // التحقق من أن الطلب يمكن إلغاؤه
            if (!in_array($taxiRequest->status, ['pending', 'accepted'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'لا يمكن إلغاء هذا الطلب'
                ], 400);
            }

            $taxiRequest->update([
                'status' => 'cancelled',
                'cancelled_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'تم إلغاء الطلب بنجاح'
            ]);

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

    /**
     * إكمال طلب تاكسي
     */
    public function completeRequest($id)
    {
        try {
            $taxiRequest = TaxiRequest::findOrFail($id);
            $user = Auth::user();

            // التحقق من أن المستخدم هو السائق
            if ($taxiRequest->driver_id != $user->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'ليس لديك صلاحية لإكمال هذا الطلب'
                ], 403);
            }

            // التحقق من أن الطلب يمكن إكماله (مقبول أو قيد التنفيذ أو نشط)
            if (!in_array($taxiRequest->status, ['accepted', 'in_progress', 'active', 'started'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'لا يمكن إكمال هذا الطلب. الحالة الحالية: ' . ($taxiRequest->status ?? 'غير معروف')
                ], 400);
            }

            $taxiRequest->update([
                'status' => 'completed',
                'completed_at' => now(),
            ]);

            $taxiRequest->refresh();
            try {
                PromotionalWheelService::onOrderCompleted('taxi', (int) $taxiRequest->id, (float) $taxiRequest->price);
            } catch (\Throwable $e) {
                \Log::error('PromotionalWheelService taxi: '.$e->getMessage());
            }

            return response()->json([
                'success' => true,
                'message' => 'تم إكمال الطلب بنجاح. يمكنك الآن قبول طلب جديد',
                'data' => [
                    'request_id' => $taxiRequest->id,
                    'status' => 'completed',
                ]
            ]);

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

    /**
     * إنشاء طلب تاكسي للاختبار (بدون مصادقة)
     */
    public function createTestRequest(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'passenger_id' => 'required|string',
                'passenger_name' => 'required|string|max:255',
                'passenger_phone' => 'required|string|max:20',
                'from_latitude' => 'required|numeric',
                'from_longitude' => 'required|numeric',
                'from_address' => 'required|string|max:500',
                'to_latitude' => 'required|numeric',
                'to_longitude' => 'required|numeric',
                'to_address' => 'required|string|max:500',
                'price' => 'required|numeric|min:0',
                'notes' => 'nullable|string|max:1000',
                'estimated_duration' => 'nullable|integer|min:0',
                'estimated_distance' => 'nullable|numeric|min:0',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'بيانات غير صحيحة',
                    'errors' => $validator->errors()
                ], 422);
            }

            // إنشاء طلب التاكسي
            $taxiRequest = TaxiRequest::create([
                'passenger_id' => $request->passenger_id,
                'passenger_name' => $request->passenger_name,
                'passenger_phone' => $request->passenger_phone,
                'from_latitude' => $request->from_latitude,
                'from_longitude' => $request->from_longitude,
                'from_address' => $request->from_address,
                'to_latitude' => $request->to_latitude,
                'to_longitude' => $request->to_longitude,
                'to_address' => $request->to_address,
                'price' => $request->price,
                'notes' => $request->notes,
                'status' => 'pending',
                'estimated_duration' => $request->estimated_duration ?? 0,
                'estimated_distance' => $request->estimated_distance ?? 0.0,
                'created_at' => now(),
            ]);

            // إرسال إشعارات للسائقين المتاحين
            try {
                $notificationController = new \App\Http\Controllers\Api\NotificationController();
                $notificationController->notifyNewTaxiRequest(new \Illuminate\Http\Request([
                    'request_id' => (string)$taxiRequest->id,
                    'passenger_name' => $taxiRequest->passenger_name,
                    'from_address' => $taxiRequest->from_address,
                    'to_address' => $taxiRequest->to_address,
                    'price' => $taxiRequest->price,
                ]));
                \Log::info("تم إرسال إشعارات طلب تاكسي جديد للسائقين (Test) - الطلب ID: {$taxiRequest->id}");
            } catch (\Exception $e) {
                \Log::error("خطأ في إرسال إشعارات طلب تاكسي (Test): " . $e->getMessage());
                // لا نوقف العملية إذا فشل إرسال الإشعارات
            }

            return response()->json([
                'success' => true,
                'message' => 'تم إنشاء طلب التاكسي بنجاح',
                'data' => [
                    'id' => $taxiRequest->id,
                    'passenger_id' => $taxiRequest->passenger_id,
                    'passenger_name' => $taxiRequest->passenger_name,
                    'passenger_phone' => $taxiRequest->passenger_phone,
                    'from_latitude' => $taxiRequest->from_latitude,
                    'from_longitude' => $taxiRequest->from_longitude,
                    'from_address' => $taxiRequest->from_address,
                    'to_latitude' => $taxiRequest->to_latitude,
                    'to_longitude' => $taxiRequest->to_longitude,
                    'to_address' => $taxiRequest->to_address,
                    'price' => $taxiRequest->price,
                    'notes' => $taxiRequest->notes,
                    'status' => $taxiRequest->status,
                    'estimated_duration' => $taxiRequest->estimated_duration,
                    'estimated_distance' => $taxiRequest->estimated_distance,
                    'created_at' => $taxiRequest->created_at->toISOString(),
                ]
            ], 201);

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