<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Validator;
use GuzzleHttp\Client as GuzzleClient;
use App\Responses;
use App\Helper;
use App\Models\Zone;

class OSMController extends Controller
{
	public function api_geo_addr(Request $req)
	{
		try {
			$now = time();

			$input = [
				'address' => $req->address,
				'country_code' => $req->country_code,
			];
			$rulesInput = [
				'address' => 'required|string|min:45',
				'country_code' => 'required|string|min:2',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$payload = [
				'countrycodes' => $req->country_code,
				'format' => 'geojson',
				'q' => $req->address,
			];
			$payload = http_build_query($payload);
			// $url = env('API_URL_NOMINATIM') . '/search?format=geojson&countrycodes=' . $req->country_code . '&q=' . $req->address;
			$url = env('API_URL_NOMINATIM') . '/search?' . $payload;

			// $respNominatim = Helper::req_get($url, [
			// 	'User-Agent: PostmanRuntime/7.28.4',
			// 	'Accept: */*',
			// 	'Accept-Encoding: gzip, deflate, br',
			// 	'Connection: keep-alive'
			// ]);

			$guzReq = new GuzzleClient();
			$respNominatim = $guzReq->request('GET', $url, [
				'headers' => [
					'Host' => $_SERVER['SERVER_ADDR'] ?? '127.0.0.1',
					'User-Agent' => 'curl/7.65.3',
					'Accept' => '*/*',
					'Accept-Encoding' => 'gzip, deflate, br',
					// 'Connection' => 'keep-alive',
				]
			]);

			if ($respNominatim->getStatusCode() != 200) {
				$apiResp = Responses::bad_request('fail geo address');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

			$body = json_decode($respNominatim->getBody()->getContents());
			$data = null;
			if (count($body->features) > 0) {
				$data = [
					'lat' => $body->features[0]->geometry->coordinates[1],
					'lng' => $body->features[0]->geometry->coordinates[0],
				];
			}

			$apiResp = Responses::success('success geo address');
			$apiResp['data'] = $data;
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}
}
