<?php

namespace App\Library;

class GeoLib {

    public static function getMunicipalityFromCoords($latitude, $longitude) {
        $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={$latitude},{$longitude}&language=it&key=" . config('google.maps_api_key');
        // $url = "https://plus.codes/api?address={$latitude},{$longitude}&ekey=" . config('google.maps_api_key');
        // dd($url);

        $response = file_get_contents($url);
        $data = (object) json_decode($response, TRUE);
        // dd($data);

        if ($data->status === 'OK') {
            $results = $data->results;
            // dd($results);

            $street_address = array_filter($results, function($result) {
                return $result['types'][0] === 'street_address';
            });
            // dd($street_address);

            if (empty($street_address)) {
                return null;
            }

            $administrative_area_level_3 = array_filter($street_address[0]['address_components'], function($components) {
                return $components['types'][0] === 'administrative_area_level_3';
            });
            // dd($administrative_area_level_3);

            return reset($administrative_area_level_3)['long_name'];
        }
        
        return null;
    }

}
