<?php
include_once("../../connection/setting_jaldhi_class.php");
$porttext = $_REQUEST['q'];

$obj 		= new clsSettings();
$connect	= $obj->funConnectMysqli();

//$url = "https://apiultra1.seametrix.net/api/GetPorts?AccessKey=7oc3y5h2w2f&inText=".str_replace(" ","%20",$porttext);
$url = "https://srtg.navapi.io/api/GetPorts?AccessKey=7oc3y5h2w2f&inText=" . str_replace(" ", "%20", $porttext);

$header = array();
$header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';
$header[] = 'Pragma: ';
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);

// echo '<pre>';

// print_r($url);
// print_r($connect);
// die();


$json_data = array();
$resultdata = json_decode($data, true);
if ($resultdata['resultText'] == 'Success') {
	foreach ($resultdata['ports'] as $resultdata1) {
		$query = "select PortId from port_master where PortName='" . $resultdata1['portName'] . "' and PortCode='" . $resultdata1['portCode'] . "'";
		$result = mysqli_query($connect, $query);
		$num = mysqli_num_rows($result);
		if ($num == 0) {
			$sql3 = "insert into port_master (PortName, COUNTRY_KEY, PortCode, STATUS) values ('" . $resultdata1['portName'] . "', '" . $resultdata1['country'] . "', '" . $resultdata1['portCode'] . "', 1)";
			mysqli_query($connect, $sql3) or die($sql3);
			mysqli_query("commit");

			$sql1  = "select max(PortId) as max from port_master";
			$res1  = mysqli_query($connect, $sql1) or die($sql1);
			$rows1 = mysqli_fetch_assoc($res1);
			$maxid    = $rows1['max'];
			$json_data[] = array('id' => $maxid,	'name' => $resultdata1['portName'] . '(' . $resultdata1['country'] . ')');
		} else {
			$rows = mysqli_fetch_assoc($result);
			$json_data[] = array('id' => $rows['PortId'],	'name' => $resultdata1['portName'] . '(' . $resultdata1['country'] . ')');
		}
	}
}
echo json_encode($json_data);
