<?php
error_reporting(0);

// Loading Requests
require_once 'vendor/rmccue/requests/library/Requests.php';
// Registering an autoloader
Requests::register_autoloader();
// Preparing the request message
$url = 'https://test.api.amadeus.com/v1/security/oauth2/token';
$auth_data = array(
'client_id' => 'fXzAFuAn3jjcLzuz5UZbo0pJhq1ZJKpA',
'client_secret' => 'or05SCg3KszdyPIJ',
'grant_type' => 'client_credentials'
);
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');

// Sending the request message by POST
$requests_response = Requests::post($url, $headers, $auth_data);
// Server returns a Requests_Response object
//echo 'Response from the authorization server:';
$response_body = json_decode($requests_response->body, true);
echo '<pre>';
$token = $response_body['access_token'];
$access_token = $token;



if (isset($_POST['query'])) {
$inpText = $_POST['query'];
$curl = curl_init();
$tkn = "$access_token";
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://test.api.amadeus.com/v1/reference-data/locations?subType=CITY,AIRPORT&keyword=$inpText",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 2,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer $tkn"
  ),
));

$response = curl_exec($curl);
curl_close($curl);
$result = json_decode($response, true);

//print_r ($result);
$count = $result['meta']['count'];
if($count == 0){
echo"<span>No record found</span>";
}else{
foreach($result['data'] as $element){
	$city     = $element['address']['cityName'];
	$country  = $element['address']['countryName'];
	$cityCode = $element['address']['cityCode'];
	$countryCode = $element['address']['countryCode'];
	$countCode = strtolower("$countryCode");
	$airportName = $element['name'];
	$iataCode = $element['iataCode'];
	
	?>
	<a href="javascript:void(0)" onclick="fromcity('<?php echo $iataCode; ?>'); from_city('<?php echo $city; ?> (<?php echo $iataCode; ?>)');" class="list-group-item list-group-item-action border-1"><img src="https://flagcdn.com/16x12/<?php echo $countCode; ?>.png" width="20" height="15">&nbsp;<?php echo $city; ?>,<?php echo $country;?> (<?php echo $iataCode; ?>)<br>&nbsp;&nbsp;&nbsp;<?php echo $airportName; ?></a>
<?php }}} ?>


<!--$curlUrl = "https://api.flightapi.io/iata/61d67237ce579974df99272/$inpText/airport";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
echo"<pre>";
//print_r($result['data']);
foreach($result['data'] as $list){
	$iata = $list['iata'];
	$name = $list['name'];
	
	echo "<a href='#' class='list-group-item list-group-item-action border-1'>$name,<br>$iata</a>";
}}

	
?>