<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Governorate;
use App\Models\City;
use Illuminate\Http\Request;

class LocationController extends Controller
{
    /**
     * Get all governorates
     */
    public function getGovernorates()
    {
        try {
            $governorates = Governorate::active()
                ->ordered()
                ->get();

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

    /**
     * Get cities by governorate
     */
    public function getCitiesByGovernorate(Request $request, $governorateId)
    {
        try {
            $cities = City::where('governorate_id', $governorateId)
                ->active()
                ->ordered()
                ->get();

            return response()->json([
                'success' => true,
                'data' => $cities
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'خطأ في جلب المدن: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all cities
     */
    public function getAllCities()
    {
        try {
            $cities = City::with('governorate')
                ->active()
                ->ordered()
                ->get();

            return response()->json([
                'success' => true,
                'data' => $cities
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'خطأ في جلب المدن: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get location details by coordinates
     */
    public function getLocationByCoordinates(Request $request)
    {
        try {
            $latitude = $request->get('latitude');
            $longitude = $request->get('longitude');

            if (!$latitude || !$longitude) {
                return response()->json([
                    'success' => false,
                    'error' => 'خط العرض وخط الطول مطلوبان'
                ], 400);
            }

            // البحث عن أقرب مدينة
            $city = City::selectRaw('*, 
                (6371 * acos(cos(radians(?)) 
                * cos(radians(latitude)) 
                * cos(radians(longitude) - radians(?)) 
                + sin(radians(?)) 
                * sin(radians(latitude)))) AS distance', 
                [$latitude, $longitude, $latitude])
                ->whereNotNull('latitude')
                ->whereNotNull('longitude')
                ->orderBy('distance')
                ->first();

            if (!$city) {
                return response()->json([
                    'success' => false,
                    'error' => 'لم يتم العثور على موقع قريب'
                ], 404);
            }

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

    /**
     * جلب موقع المستخدم (المحافظة والمدينة)
     */
    public function getUserLocation($userId)
    {
        try {
            $user = \App\Models\User::with(['governorate', 'city'])->find($userId);

            if (!$user) {
                return response()->json([
                    'governorate' => null,
                    'city' => null,
                    'message' => 'المستخدم غير موجود'
                ], 404);
            }

            return response()->json([
                'governorate' => $user->governorate ? $user->governorate->name_ar : null,
                'city' => $user->city ? $user->city->name_ar : null,
                'governorate_id' => $user->governorate_id,
                'city_id' => $user->city_id,
            ]);

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