<?php
session_start();
if (!isset($_SESSION['name'])) {
    http_response_code(401);
    echo json_encode(['message' => 'Unauthorized']);
    die;
}

if (!isset($_GET["latitude"]) || !isset($_GET["longitude"]) || empty($_GET["latitude"]) || empty($_GET["longitude"]) ) {
    http_response_code(400);
    echo json_encode(['message' => 'Invalid input']);
    die;
}

require_once 'config/geocode.php';
$ch = curl_init();


switch ($geocodeType) {
    case 'bigdatacloud':
        $requrl =  $geocodeApiurl . "?latitude=". $_GET["latitude"] ."&longitude=". $_GET["longitude"];
        break;
    case 'photon':
        $requrl = $geocodeApiurl . "?lon=". $_GET["longitude"] ."&lat=". $_GET["latitude"];
        break;
    default:
        http_response_code(401);
        echo json_encode(['message' => 'Invalid request']);
        die;
}    
   
curl_setopt_array($ch, array(
    CURLOPT_URL => $requrl,
    CURLOPT_RETURNTRANSFER => true,
));


if ($geocodeApikey != false) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-Api-Key: '. $geocodeApikey]);
}

$response = json_decode(curl_exec($ch), true);

curl_close($ch);

switch ($geocodeType) {
    case 'bigdatacloud':
        echo json_encode(['city' => $response['city'], 'locality' => $response['locality'], 'countryName' => $response['countryName'],'countryCode' => $response['countryCode']]);
        break;
    case 'photon':
        echo json_encode(['city' => $response['features'][0]['properties']['city'],'countryName' => $response['features'][0]['properties']['country'],'countryCode' => $response['features'][0]['properties']['countrycode']]);
        break;
}    