<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class DistanceCalculatorService
{
    protected $apiKey;

    public function __construct()
    {
        $this->apiKey = env('GOOGLE_MAPS_API_KEY');
    }

    /**
     * Calculate distance between restaurant and customer using Google Maps Distance Matrix API
     * 
     * @param float $restaurantLat
     * @param float $restaurantLng
     * @param float $customerLat
     * @param float $customerLng
     * @return array ['distance_km' => float, 'distance_text' => string, 'duration_text' => string, 'duration_minutes' => int]
     */
    public function calculateDistance($restaurantLat, $restaurantLng, $customerLat, $customerLng)
    {
        try {
            $response = Http::get('https://maps.googleapis.com/maps/api/distancematrix/json', [
                'origins' => "{$restaurantLat},{$restaurantLng}",
                'destinations' => "{$customerLat},{$customerLng}",
                'key' => $this->apiKey,
                'units' => 'metric'
            ]);

            $data = $response->json();

            if ($data['status'] !== 'OK' || empty($data['rows'][0]['elements'][0])) {
                throw new \Exception('Unable to calculate distance');
            }

            $element = $data['rows'][0]['elements'][0];

            if ($element['status'] !== 'OK') {
                throw new \Exception('Distance calculation failed');
            }

            return [
                'distance_km' => round($element['distance']['value'] / 1000, 2),
                'distance_text' => $element['distance']['text'],
                'duration_text' => $element['duration']['text'],
                'duration_minutes' => round($element['duration']['value'] / 60)
            ];
        } catch (\Exception $e) {
            // Fallback to Haversine formula if API fails
            return $this->haversineDistance($restaurantLat, $restaurantLng, $customerLat, $customerLng);
        }
    }

    /**
     * Haversine formula fallback for distance calculation
     */
    private function haversineDistance($lat1, $lon1, $lat2, $lon2)
    {
        $earthRadius = 6371; // km

        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);

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

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

        return [
            'distance_km' => round($distance, 2),
            'distance_text' => round($distance, 2) . ' km',
            'duration_text' => 'N/A',
            'duration_minutes' => round($distance * 3) // Estimate: 3 min per km
        ];
    }
}
