<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\WorkingArea;
use App\Models\ServicePoint;
use App\Models\MapSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MapManagementController extends Controller
{
    /**
     * عرض صفحة إدارة الخريطة
     */
    public function index()
    {
        $workingArea = WorkingArea::getActiveArea();
        $mapSettings = MapSetting::getActiveSettings();
        $servicePoints = ServicePoint::with('workingArea')->get();

        return view('admin.maps.index', compact('workingArea', 'mapSettings', 'servicePoints'));
    }

    /**
     * حفظ منطقة العمل
     */
    public function storeWorkingArea(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'city_name' => 'required|string|max:100',
            'city_name_ar' => 'required|string|max:100',
            'center_lat' => 'required|numeric|between:-90,90',
            'center_lng' => 'required|numeric|between:-180,180',
            'zoom_level' => 'required|integer|between:8,18',
            'boundaries' => 'required|array|min:3',
            'boundaries.*.lat' => 'required|numeric|between:-90,90',
            'boundaries.*.lng' => 'required|numeric|between:-180,180',
            'description' => 'nullable|string|max:500',
        ]);

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

        try {
            // إلغاء تفعيل جميع المناطق الأخرى
            WorkingArea::where('is_active', true)->update(['is_active' => false]);

            // إنشاء منطقة جديدة
            $workingArea = WorkingArea::create([
                'city_name' => $request->city_name,
                'city_name_ar' => $request->city_name_ar,
                'center_lat' => $request->center_lat,
                'center_lng' => $request->center_lng,
                'zoom_level' => $request->zoom_level,
                'boundaries' => $request->boundaries,
                'description' => $request->description,
                'is_active' => true,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'تم حفظ منطقة العمل بنجاح',
                'data' => $workingArea
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء حفظ منطقة العمل',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * حفظ نقطة خدمة
     */
    public function storeServicePoint(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:100',
            'name_ar' => 'required|string|max:100',
            'type' => 'required|in:taxi,restaurant,gas',
            'lat' => 'required|numeric|between:-90,90',
            'lng' => 'required|numeric|between:-180,180',
            'service_radius' => 'required|integer|min:100|max:50000',
            'address' => 'nullable|string|max:500',
            'description' => 'nullable|string|max:500',
            'working_area_id' => 'required|exists:working_areas,id',
        ]);

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

        try {
            $servicePoint = ServicePoint::create($request->all());

            return response()->json([
                'success' => true,
                'message' => 'تم حفظ نقطة الخدمة بنجاح',
                'data' => $servicePoint
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء حفظ نقطة الخدمة',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * تحديث نقطة خدمة
     */
    public function updateServicePoint(Request $request, $id)
    {
        $servicePoint = ServicePoint::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:100',
            'name_ar' => 'required|string|max:100',
            'type' => 'required|in:taxi,restaurant,gas',
            'lat' => 'required|numeric|between:-90,90',
            'lng' => 'required|numeric|between:-180,180',
            'service_radius' => 'required|integer|min:100|max:50000',
            'address' => 'nullable|string|max:500',
            'description' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

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

        try {
            $servicePoint->update($request->all());

            return response()->json([
                'success' => true,
                'message' => 'تم تحديث نقطة الخدمة بنجاح',
                'data' => $servicePoint
            ]);

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

    /**
     * حذف نقطة خدمة
     */
    public function deleteServicePoint($id)
    {
        try {
            $servicePoint = ServicePoint::findOrFail($id);
            $servicePoint->delete();

            return response()->json([
                'success' => true,
                'message' => 'تم حذف نقطة الخدمة بنجاح'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء حذف نقطة الخدمة',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * حفظ إعدادات الخريطة
     */
    public function storeMapSettings(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'google_maps_api_key' => 'required|string',
            'default_map_style' => 'required|in:roadmap,satellite,hybrid,terrain',
            'max_zoom' => 'required|integer|between:10,20',
            'min_zoom' => 'required|integer|between:5,15',
            'default_lat' => 'required|numeric|between:-90,90',
            'default_lng' => 'required|numeric|between:-180,180',
            'default_zoom' => 'required|integer|between:8,18',
        ]);

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

        try {
            $data = $request->all();
            // إزالة mapbox_access_token إذا كان موجوداً
            unset($data['mapbox_access_token']);
            
            $mapSettings = MapSetting::updateOrCreateSettings($data);

            return response()->json([
                'success' => true,
                'message' => 'تم حفظ إعدادات الخريطة بنجاح',
                'data' => $mapSettings
            ]);

        } catch (\Exception $e) {
            \Log::error('Map Settings Save Error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString(),
                'request' => $request->all()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء حفظ إعدادات الخريطة: ' . $e->getMessage(),
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * الحصول على بيانات الخريطة
     */
    public function getMapData()
    {
        try {
            $workingArea = WorkingArea::getActiveArea();
            $mapSettings = MapSetting::getActiveSettings();
            $servicePoints = ServicePoint::with('workingArea')->get();

            return response()->json([
                'success' => true,
                'data' => [
                    'working_area' => $workingArea,
                    'map_settings' => $mapSettings,
                    'service_points' => $servicePoints,
                ]
            ]);

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