<?php 
namespace modules\activities\components;

use Yii;
use yii\base\Component;
use yii\httpclient\Client;

class GoogleDistanceMatrix extends Component
{
    const DISTANCE_URL = 'https://maps.googleapis.com/maps/api/distancematrix/json';

    public $apiKey;

    public function getDistance($origins, $destinations, $mode = 'driving')
    {
        $params = [
            'origins' => is_array($origins) ? implode('|', $origins) : $origins,
            'destinations' => is_array($destinations) ? implode('|', $destinations) : $destinations,
            'mode' => $mode,
            'key' => $this->apiKey,
        ];

        $url = self::DISTANCE_URL . '?' . http_build_query($params);
        $response = file_get_contents($url);
        $data = json_decode($response, true);

        if ($data['status'] === 'OK') {
            return $data['rows'][0]['elements'][0];
        }

        throw new \Exception('Error fetching distance data: ' . $data['status']);
    }


    public static function Getgoogledm($frompc, $topc, $departuretime)
    {
        $url = 'https://maps.googleapis.com/maps/api/distancematrix/json';
        $client = new Client(['baseUrl' => $url]);
        $response = $client->createRequest()
            ->setMethod('get')
            ->setData(
                [
                    'key' => 'AIzaSyBno6ff2a2Z6pcQnxzEj-xSyLYSk0aY7bc',
                    'mode' => 'driving',
                    'units' => 'imperial',
                    'traffic_model' => 'pessimistic',
                    'departure_time' => $departuretime,
                    'origins' => $frompc,
                    'destinations' => $topc,
                ]
            )
            ->send();
            $out = [
                'distance' => 0,
                'duration_in_traffic' => 0,
                'duration' => 0,
            ];
        $data = $response->data;
        if(is_array($data) == true && isset($data['rows'][0]['elements'][0]['distance']) && $data['rows'][0]['elements'][0]['distance'] == true){
            $out['distance'] = $data['rows'][0]['elements'][0]['distance']['text'];
            $out['duration_in_traffic'] = $data['rows'][0]['elements'][0]['duration_in_traffic']['value'];
            $out['duration'] = $data['rows'][0]['elements'][0]['duration']['value'];
        }
        return $out;
    }
    
}