<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

	public $mainUserData ;
	private static $API_ACCESS_KEY = 'AAAA0fmpmhQ:APA91bHnlEqJ_4gPUHqgGmCDoWsSWBz3GW41jqXtpgjdLtSyzTwCfLzdc0y6o4cu1fs6AHpemV1g02AUnjcXGA8huEC6AC12jOKty1ViJNvpUhVjd9nus3_pCXxGkrso2y0AwKDmjkOO';

	function __construct()
	{
		parent::__construct();
		
		$this->load->library('curl');
		$this->load->helper(['jwt', 'authorization']); 
		$this->load->model('users') ;
		
		$currentMethod  =  $this->router->fetch_method();
		
		$arrayFunctions = ['login', 'haversineGreatCircleDistance', 'vincentyGreatCircleDistance', 'validateLatLong', 'getAllSitesGeocode', 'sendNotificationsWakeSleepModeDevices'] ;
		
		if(!in_array($currentMethod, $arrayFunctions)) {
			
			$jwtToken = $this->input->get_request_header('Authorization', TRUE) ;
			$UserId	  = $this->input->get_request_header('UserId', True) ;
			
			if($jwtToken && $UserId) {
				
				$chek_user_authentication = $this->users->chek_user_authentication($jwtToken, $UserId) ;
				
				if (!$chek_user_authentication) {
					echo json_encode([ 'status' => 401, 'message' => 'Unauthorized']) ;
					exit ;
				} else {
					$this->mainUserData = $chek_user_authentication ;
				}
				
			} else {
				echo json_encode([ 'status' => 401, 'message' => 'Unauthorized']) ;
				exit ;
			}
		} 
	}
	
	public function login() {

		$username 			 = $this->input->post('username') ;
		$password  			 = $this->input->post('password') ;
		$googleFirebaseToken = $this->input->post('googleFirebaseToken') ;
		
		//$username 				= 'ServiceSentryEngineer' ;
		//$password  				= 'Star@1!' ;
		// list log header identifier 152112
		
		//New credentials for testing
		//~ $username 				= 'servicesentryengineer1' ;
		//~ $password  				= 'Orbis2020!' ;
		
		
		/***
		 * Username: orbismonitoringapptest2
		   Password: Splendid34$
		 */
		
		$linkAccountNumber		= '12345' ;
		
		
		$user_id 		 = "" ;
		$user_jwt_token  =  "" ;
		$name			 = "" ;
		$armDisarmStatus = "" ; 
		$disarmRange 	 = "" ;
		$disarmTime 	 = "" ;
		
		
		if ( $username && $password) {
			
			$url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/GetLinkAccount";
			$xml = '<?xml version="1.0" encoding="utf-8"?>
			<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			xmlns:xsd="http://www.w3.org/2001/XMLSchema"
			xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
			<soap:Body>
			<GetLinkAccount xmlns="http://www.monitorsoft.com/SentinelXS/clsSentinelXS">
			<getLinkAccountRequestKey>
			<UserName>'.$username.'</UserName>
			<Password>'.$password.'</Password>
			<LinkAccountNumber>' .$linkAccountNumber. '</LinkAccountNumber>
			</getLinkAccountRequestKey>
			</GetLinkAccount>
			</soap:Body>
			</soap:Envelope>';
			
			$curl_send = $this->curl->curl_send($xml, $url);
			$xmlToArray = $this->curl->xmlToArray($curl_send);
			//debug($xmlToArray, 1) ;
			if ( $xmlToArray ) {
				
				if( isset( $xmlToArray['soapFault'] ) ) {
					$status  		 = "200";
					$message  		 = ( isset( $xmlToArray['soapFault']['faultstring'] ) ? $xmlToArray['soapFault']['faultstring'] :  'Fault String.');
					$loginStatus	 = "false"	;
				} elseif( isset( $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult']['Errors']['Message']['MessageID'] ) && $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult']['Errors']['Message']['MessageID'] == "SXSWS_1" ) {
					$status  		 = "200";
					$message  		 = "Invalid credentials.";
					$loginStatus	 = "false"	;
				} elseif( (isset( $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult'] ) && empty( $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult'] )) || (isset( $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult']['Warnings'] ))  ||  (isset( $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult']['Errors']['Message']['MessageID'] ) && $xmlToArray['GetLinkAccountResponse']['GetLinkAccountResult']['Errors']['Message']['MessageID'] == "SXSWS_54")    ) {
					
					$status  		 = "200";
					
					// Create a token
					$tokenData = time();
					$token = AUTHORIZATION::generateToken($tokenData);
					
					$insertData = $this->users->insert_user_data($token, $username, $password, $googleFirebaseToken) ; 
					
					if ( $insertData && $token) {
						$message  		 = "Valid credentials.";
						$loginStatus	 = "true"	;
						$user_id 		 =  $insertData['user_id'];
						$user_jwt_token  =  $token;
						$name			 =  "Need to make name dynamic." ;
						$armDisarmStatus =  $insertData['auto_arm_disarm_status']; 
						$disarmRange 	 =  $insertData['disarm_range'];
						$disarmTime 	 =  $insertData['disarm_time'];
					} else {
						$message  		 = "Network error.";
						$loginStatus	 = "false"	;
					}
					
				} else {
					$status  		 = "200";
					$message  		 = "No matched record from the XML response.";
					$loginStatus	 = "false"	;	
				}
				
				
			} else {
				
				$status  		 = "500";
				$message  		 = "No response from the API.";
				$loginStatus	 = "false"	;
				
			}
			
			//debug($xmlToArray, 1) ;
			
		} else {
			
			if (!$username && !$password ) {
				$status  		 = "500";
				$message  		 = "Username and Password is required.";
				$loginStatus	 = "false"	;
			} elseif (!$username) {
				$status  		 = "500";
				$message  		 = "Username is required.";
				$loginStatus	 = "false"	;
			} elseif(!$password) {
				$status  		 = "500";
				$message  		 = "Password is required.";
				$loginStatus	 = "false"	;
			}
		}
		
		echo json_encode([ 'status' => $status, 'message' => $message, 'loginStatus' =>  $loginStatus, 'user_id' => $user_id, 'user_jwt_token' => $user_jwt_token, 'name' => $name, 'armDisarmStatus' => $armDisarmStatus, 'disarmRange' => $disarmRange, 'disarmTime' => $disarmTime]) ;
	}
	
	public function logout_user(){
		
		//$user_id	= $this->input->post('user_id') ;
		$dataUser 	= $this->mainUserData ;
		
		if ( isset($dataUser['user_id']) && $dataUser['user_id']) {
			$deleteUserData = $this->users->delete_user_data($dataUser['user_id']) ;
			$status  		 = "200";
			$message  		 = $deleteUserData;
			$apiStatus	 	 = "true"	;
		} else {
			$status  		 = "500";
			$message  		 = "User id is required.";
			$apiStatus	 	 = "false"	;
		}
		
		echo json_encode([ 'status' => $status, 'message' => $message, 'apiStatus' =>  $apiStatus]) ;
				
	} 
	
	public function getSites() {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		
		try {
			$conexion = new PDO("informix:host=".$this->config->item('pdo_connect')['host'].";service=".$this->config->item('pdo_connect')['service'].";database=".$this->config->item('pdo_connect')['database'].";server=".$this->config->item('pdo_connect')['server'].";protocol=".$this->config->item('pdo_connect')['protocol'].";EnableScrollableCursors=".$this->config->item('pdo_connect')['EnableScrollableCursors'].";client_locale=".$this->config->item('pdo_connect')['client_locale'].";db_locale=".$this->config->item('pdo_connect')['db_locale'] ,$this->config->item('pdo_connect')['db_user'],$this->config->item('pdo_connect')['db_pass']);
		} catch( PDOException $Exception ) {
			echo json_encode([ 'status' => 500, 'message' => "Internal server error."]) ;
			exit ;
		}
		
		$sql    = 'select * from webusers where name = "'.$username.'" and agctype = 4';
		$prep   = $conexion->prepare($sql);
		$prep->execute();
		$result = $prep->fetchAll(PDO::FETCH_ASSOC);
		
		if ( isset($result[0]['AGCNO']) && $result[0]['AGCNO'] ) {
			
			
			$linkAccountId = $result[0]['AGCNO'] ;
			
			$eventType    =  $this->input->post('search_by') ;
			$eventValue   =  $this->input->post('search_value') ;
			$showUncomDecomSites =  $this->input->post('show_uncom_decom_sites') ;   // Wether to search for uncommisioned and decommisioned sites
			
			/*
			 *
			 *  search_by:    siteName      sitePostcode      siteTransmitterId     allSites
			 * 
			 */
			 
			 if ($eventType == "allSites") {
				 
				 if ( $showUncomDecomSites == "yes" ) {
				 $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno 
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) ORDER BY T01.serialno desc";
				} else {
				
					$sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno and T02.commstate = 1
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) ORDER BY T01.serialno desc";
				
				}
				 
				 
			 } elseif($eventType == "siteName" && $eventValue) {
				 
				 $eventValue = trim($eventValue) ;
				 $eventValue = str_replace(' ', '%', $eventValue) ;
				 if ( $showUncomDecomSites == "yes" ) {
				 $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno 
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND UPPER(T01.name) LIKE '%".strtoupper($eventValue)."%' ORDER BY T01.serialno desc";
			 } else {
				$sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno and T02.commstate = 1
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND UPPER(T01.name) LIKE '%".strtoupper($eventValue)."%' ORDER BY T01.serialno desc";
			 }
				 
				 
			 } elseif($eventType == "sitePostcode" && $eventValue) {
				 
				 $eventValue = trim($eventValue) ;
				 $eventValue = str_replace(' ', '%', $eventValue) ;
				 if ( $showUncomDecomSites == "yes" ) {
				 $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno 
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND UPPER(T01.address_postcode) LIKE '%".strtoupper($eventValue)."%' ORDER BY T01.serialno desc";
			  } else {
					$sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno and T02.commstate = 1
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND UPPER(T01.address_postcode) LIKE '%".strtoupper($eventValue)."%' ORDER BY T01.serialno desc";
			  }
				 
			 } elseif($eventType == "siteTransmitterId" && $eventValue) {
				 
				  $eventValue = (int)$eventValue ;
				 
				  if ( $showUncomDecomSites == "yes" ) {
				  $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND T04.panelid = '".$eventValue."' ORDER BY T01.serialno desc";
				} else {
				
					 $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno and T02.commstate = 1
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND T04.panelid = '".$eventValue."' ORDER BY T01.serialno desc";
				
				}
			 } else {
				echo json_encode([ 'status' => 500, 'message' => "No search parameter sent."]) ;
				exit;
			 }
			 
			 $prepCon   = $conexion->prepare($sqlNew);
			 $prepCon->execute();
			 $resultTotal = $prepCon->fetchAll(PDO::FETCH_ASSOC);
			 
			 if ($resultTotal) {
				echo json_encode([ 'status' => 200, 'message' => "Data found.", 'dataStatus' => 'true', 'data' => $resultTotal]) ;
			 } else {
				echo json_encode([ 'status' => 200, 'message' => "No data found.", 'dataStatus' => 'false', 'data' => $resultTotal]) ;
			 }
			 
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Internal server error."]) ;
		}
		
		//debug($result, 1); 
	}
	
	
	public function getEvents() {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		
		$eventFor 		= $this->input->post('event_for') ;
		$serialNumber	= $this->input->post('serial_number') ;
		
		
		if ($serialNumber) {
		
			if ($eventFor == "today") {
				
				$startDate = date('Y-m-d') . "T00:00:00";
				$endDate   = date('Y-m-d')."T".date('H:i:s', strtotime("+1 hour")) ;
				
			} elseif($eventFor == "last24Hours") {
				
				$startDate =  date('Y-m-d', strtotime("-1 day")) ."T".   date('H:i:s', strtotime("-1 day")) ;
				$endDate   =  date('Y-m-d')."T".date('H:i:s', strtotime("+1 hour")) ;
				
			} elseif($eventFor == "last7Days") {
							
				$startDate =  date('Y-m-d', strtotime("-6 days")) . "T00:00:00";
				$endDate   =  date('Y-m-d')."T".date('H:i:s', strtotime("+1 hour")) ;
				
			} elseif($eventFor == "calendar") {
							
				$startDate =  $this->input->post('start_date')."T00:00:00" ;
				$endDate   =  $this->input->post('end_date')."T23:59:59" ;
				
				if (!$startDate && !$endDate ) {
					echo json_encode([ 'status' => 500, 'message' => "Start/End date is required."]) ;
					exit;
				}
				
			} else {
				echo json_encode([ 'status' => 500, 'message' => "No parameters for event are sent."]) ;
				exit;
			}
			
			$url_alarm = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/ListLogDetailItems";
			
			$xml_post_string_alarm = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
							<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
							   <soap:Header/>
							   <soap:Body>
								  <cls:ListLogDetailItems>
									 <!--Optional:-->
									 <cls:listLogDetailItemsRequestKey>
										<cls:ServiceVersion>Version_1_110_4</cls:ServiceVersion>
										<!--Optional:-->
										<cls:UserName>'.$username.'</cls:UserName>
										<!--Optional:-->
										<cls:Password>'.$password.'</cls:Password>
										<!--Optional:-->
										<cls:LogDetailFilter>
										   <!--Optional:-->

										   <cls:FilterList>
											  <cls:LogDetailFilterListItem>
												 <cls:FilterAttribute  xsi:type="cls:SerialNumberLogDetailFilterAttribute"/>
												 <cls:FilterOperator  xsi:type="cls:EqualityLogDetailFilterOperator"/>
												 <cls:FilterValue  xsi:type="cls:LogDetailFilterComparisonInteger">
												 <cls:Value>'.$serialNumber.'</cls:Value>
												 </cls:FilterValue>
											  </cls:LogDetailFilterListItem>


											   <cls:LogDetailFilterListItem>

																<cls:FilterAttribute xsi:type="cls:DateRangeLogDetailFilterAttribute" />

													 <cls:FilterOperator xsi:type="cls:EqualityLogDetailFilterOperator" />

													 <cls:FilterValue xsi:type="cls:LogDetailFilterComparisonDateRange">

														  <cls:FromValue>'.$startDate.'</cls:FromValue>

														  <cls:ToValue>'.$endDate.'</cls:ToValue>

													 </cls:FilterValue>

											   </cls:LogDetailFilterListItem>
																 <cls:LogDetailFilterListItem>
															<cls:FilterAttribute xsi:type="cls:LogCategoryLogDetailFilterAttribute" />
															<cls:FilterOperator xsi:type="cls:InLogDetailFilterOperator" />
															<cls:FilterValue xsi:type="cls:LogDetailFilterComparisonLogCategoryList">
																		<cls:Value>
																			<cls:BaseLogCategoryListItem xsi:type="cls:SignalLogCategoryListItem" />

																			<cls:BaseLogCategoryListItem xsi:type="cls:AlarmLogCategoryListItem" />

																			<cls:BaseLogCategoryListItem xsi:type="cls:TrackingLogCategoryListItem" />

																			<cls:BaseLogCategoryListItem xsi:type="cls:AudioLogCategoryListItem" />

																			<cls:BaseLogCategoryListItem xsi:type="cls:CctvLogCategoryListItem" />
																	 </cls:Value>
															</cls:FilterValue>
												</cls:LogDetailFilterListItem>
										   </cls:FilterList>
										</cls:LogDetailFilter>
									 </cls:listLogDetailItemsRequestKey>
								  </cls:ListLogDetailItems>
							   </soap:Body>
							</soap:Envelope>';


			$curl_send_alarm = $this->curl->curl_send($xml_post_string_alarm, $url_alarm);
			$data = array();
			$xmlToArray_alarm = $this->curl->xmlParse($curl_send_alarm);

			$list_log_header_xml = ( isset( $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] )  && $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] ? $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] : '' );
			
			
			if ($list_log_header_xml) {
				
				if( !isset( $list_log_header_xml[0]['SerialNumber'] ) ) {
					$result[] = $list_log_header_xml ;
				} else {
					$result  =  $list_log_header_xml ;
				} 
				
				
				echo json_encode([ 'status' => 200, 'message' => "Data found.", 'dataStatus' => 'true', 'data' => $result]) ;
			} else {
				$result = [] ;
				echo json_encode([ 'status' => 200, 'message' => "No data found.", 'dataStatus' => 'false', 'data' => $result]) ;
			}
			
			//debug($list_log_header_xml, 1) ;
			
			
			
			
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Serial number is required."]) ;
		}
		
	}
	
	public function listMedia() {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		
		$logHeaderIdentifier 		= $this->input->post('log_header_identifier') ;
		$serialNumber				= $this->input->post('serial_number') ;
		
		
		
		if ($logHeaderIdentifier && $serialNumber) {
			/***List Media API***/
			
			$ListMediaRequest = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/ListMedia";
			$ListMediaRequest_xml = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>

            <SOAP-ENV:Envelope

            xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"

            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

            xmlns:xsd="http://www.w3.org/2001/XMLSchema">

            <SOAP-ENV:Body>

                         <ListMedia xmlns="http://www.monitorsoft.com/SentinelXS/clsSentinelXS">

                     <listMediaRequestKey>

                    <UserName>'.$username.'</UserName>
					 <Password>'.$password.'</Password>

                        <ServiceVersion>Version_1_104_1</ServiceVersion>

                            <MediaFilter>

                                <FilterList>

                                <MediaFilterListItem>

                                    <FilterAttribute xsi:type="LogHeaderIdentifierMediaFilterAttribute"/>

                                    <FilterOperator xsi:type="EqualityMediaFilterOperator"/>

                                    <FilterValue xsi:type="MediaFilterComparisonInteger">

                                    <Value>'.$logHeaderIdentifier.'</Value>

                                    </FilterValue>

                                </MediaFilterListItem>

                                <MediaFilterListItem>
                            		<FilterAttribute xsi:type="SerialNumberMediaFilterAttribute"/>
                            		<FilterOperator xsi:type="EqualityMediaFilterOperator"/>
                            		<FilterValue xsi:type="MediaFilterComparisonInteger">
                             			<Value>'.$serialNumber.'</Value>
                            		</FilterValue>
                        		</MediaFilterListItem>

                                </FilterList>

                            </MediaFilter>

                    </listMediaRequestKey>

                 </ListMedia>

            </SOAP-ENV:Body>

            </SOAP-ENV:Envelope>';


			$ListMediaRequest_curl = $this->curl->curl_send($ListMediaRequest_xml, $ListMediaRequest);
			$ListMediaRequest_curl_array = $this->curl->xmlToArray($ListMediaRequest_curl);
		
			
			$result = ( isset( $ListMediaRequest_curl_array['ListMediaResponse']['ListMediaResult']['ListOfMedia']['MediaListItem'] )  && $ListMediaRequest_curl_array['ListMediaResponse']['ListMediaResult']['ListOfMedia']['MediaListItem'] ? $ListMediaRequest_curl_array['ListMediaResponse']['ListMediaResult']['ListOfMedia']['MediaListItem'] : '' );
			
			
			if ($result) {
				
				if( !isset( $result[0]['SerialNumber'] ) ) {
					$resultTotal[] = $result ;
				} else {
					$resultTotal  =  $result ;
				} 
				
				if ( isset($resultTotal[0]['Data']) ) {
					
					if ( is_array($resultTotal[0]['Data']) ) {
						$resultTotal[0]['Data'] = '' ;
					} 
				}
				
				$message = "Media Found, " ;
				
				//echo json_encode([ 'status' => 200, 'message' => "Data found.", 'dataStatus' => 'true', 'data' => $resultTotal]) ;
				
			} else {
				$resultTotal = [] ;
				$message = "Media Not Found, " ;
				//echo json_encode([ 'status' => 200, 'message' => "No data found.", 'dataStatus' => 'false', 'data' => $resultTotal]) ;
			
			} 
			
			/***List Media API***/
			
			
			/***List Log Detail Items API***/
			
			$url_alarm = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/ListLogDetailItems";
			$xml_post_string_alarm = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
				<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
				 <soap:Header/>
				 <soap:Body>
					<cls:ListLogDetailItems>
					   <!--Optional:-->
					   <cls:listLogDetailItemsRequestKey>
						  <cls:ServiceVersion>Version_1_110_4</cls:ServiceVersion>
						  <!--Optional:-->
						  <cls:UserName>'.$username.'</cls:UserName>
						  <!--Optional:-->
						  <cls:Password>'.$password.'</cls:Password>
						  <!--Optional:-->
						  <cls:LogDetailFilter>
							 <!--Optional:-->

							 <cls:FilterList>
								<cls:LogDetailFilterListItem>
								   <cls:FilterAttribute  xsi:type="cls:SerialNumberLogDetailFilterAttribute"/>
								   <cls:FilterOperator  xsi:type="cls:EqualityLogDetailFilterOperator"/>
								   <cls:FilterValue  xsi:type="cls:LogDetailFilterComparisonInteger">
								   <cls:Value>'.$serialNumber.'</cls:Value>
								   </cls:FilterValue>
								</cls:LogDetailFilterListItem>
								<cls:LogDetailFilterListItem>
								   <cls:FilterAttribute  xsi:type="cls:LogHeaderIdentifierLogDetailFilterAttribute"/>
								   <cls:FilterOperator  xsi:type="cls:EqualityLogDetailFilterOperator"/>
								   <cls:FilterValue  xsi:type="cls:LogDetailFilterComparisonInteger">
								   <cls:Value>'.$logHeaderIdentifier.'</cls:Value>
								   </cls:FilterValue>
								</cls:LogDetailFilterListItem>

							 </cls:FilterList>
						  </cls:LogDetailFilter>
					   </cls:listLogDetailItemsRequestKey>
					</cls:ListLogDetailItems>
				 </soap:Body>
				</soap:Envelope>';

			//header('Content-type: application/xml');
			$curl_send_alarm = $this->curl->curl_send($xml_post_string_alarm, $url_alarm);
			$xmlToArray_alarm = $this->curl->xmlParse($curl_send_alarm);
		
			$listLogDetailItems = ( isset( $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] )  && $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] ? $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] : '' );
			
			if ($listLogDetailItems) {
			
				if( !isset( $listLogDetailItems[0]['SerialNumber'] ) ) {
					$listLogDetailItemsResult[] = $listLogDetailItems ;
				} else {
					$listLogDetailItemsResult  =  $listLogDetailItems ;
				} 
				
				$message .= "Details Found" ;
			
			} else {
				$listLogDetailItemsResult = [] ;
				$message .= "Details Not Found" ;
			} 
				
				
		    if ( !$resultTotal && !$listLogDetailItemsResult ) {
				$dataStatus = 'false' ; 
			} else {
				$dataStatus = 'true' ;
			}
			
			/***List Log Detail Items API***/
			
			
			echo json_encode([ 'status' => 200, 'message' => $message, 'dataStatus' => $dataStatus, 'mediaDetails' => $listLogDetailItemsResult, 'data' => $resultTotal]) ;
			
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Serial number/Log header identifier is required."]) ;
		}
	}
	
	
	public function putItemOnTest() {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		$serialNumber = $this->input->post('serial_number') ;
	
		/***remove later***
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		/***remove later***/
		
		if ($serialNumber) {
			   /***remove later***
			   $serialNumber = "160463" ;	
			   /***remove later***/
			
			   $todayDate	  = date('Y-m-d');
			   $current_time  = date('H:i:s',strtotime('+2hours'));
		
			   $onTestUntil   = $todayDate.'T'.$current_time.'Z' ;
			   
			   $url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/PutItemOnTest";
			   $xml_post_string = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
					<soap:Header />
					<soap:Body>
						<cls:PutItemOnTest>
							<cls:putItemOnTestRequestKey>
								<cls:ServiceVersion>Version_1_119_4</cls:ServiceVersion>
								<cls:UserName>'.$username.'</cls:UserName>
								<cls:Password>'.$password.'</cls:Password>
								<cls:SerialNumber>'.$serialNumber.'</cls:SerialNumber>
								<cls:OnTestType xsi:type="cls:OnTestSite"></cls:OnTestType>
								<cls:OnTestUntil>'.$onTestUntil.'</cls:OnTestUntil>
								<cls:Description>Site taken out of service by the Monitoring app. '.$username.'</cls:Description>
							</cls:putItemOnTestRequestKey>
						</cls:PutItemOnTest>
					</soap:Body>
				</soap:Envelope>';
				
				$curl_send = $this->curl->curl_send($xml_post_string, $url);
				$xmlToArray = $this->curl->xmlToArray($curl_send);
				
				if ( isset( $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult']['Errors']['Message']['MessageID'] ) && $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult']['Errors']['Message']['MessageID'] == "SXSWS_12" ) {
					
					$messageText = ( isset( $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult']['Errors']['Message']['MessageText'] ) ? $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult']['Errors']['Message']['MessageText'] : "Site is currently been modified, please try again later"   )  ;
					
					echo json_encode([ 'status' => 200, 'message' => $messageText, 'dataStatus' => 'locked']) ;
					
				} elseif ( isset( $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult']['Errors'] ) ){
					
					echo json_encode([ 'status' => 200, 'message' => "Internal server error", 'dataStatus' => 'false']) ;
					
				} elseif ( isset( $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult'] ) ) {
					
					echo json_encode([ 'status' => 200, 'message' => "Site disarmed successfully", 'dataStatus' => 'true']) ;
					
				} else {
					
					echo json_encode([ 'status' => 200, 'message' => "Internal server error", 'dataStatus' => 'false']) ;
				
				}
				
				
				
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Serial number is required."]) ;
		}
	
	
	
	}
	
	
	public function takeItemOffTest() {
		
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		$serialNumber = $this->input->post('serial_number') ;
	
		/***remove later***
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		/***remove later***/
		
		
		
		
		
		if ($serialNumber) {
			   /***remove later***
			   $serialNumber = "160463" ;
			   /***remove later***/
			   
			   $url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/TakeItemOffTest";
			   $xml_post_string = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
					<soap:Header />
					<soap:Body>
						<cls:TakeItemOffTest>
							<cls:takeItemOffTestRequestKey>
								<cls:ServiceVersion>Version_1_119_4</cls:ServiceVersion>
								<cls:UserName>'.$username.'</cls:UserName>
								<cls:Password>'.$password.'</cls:Password>
								<cls:SerialNumber>'.$serialNumber.'</cls:SerialNumber>
								<cls:OnTestType xsi:type="cls:OnTestSite"></cls:OnTestType>
							</cls:takeItemOffTestRequestKey>
						</cls:TakeItemOffTest>
					</soap:Body>
				</soap:Envelope>';
				
				
				$curl_send = $this->curl->curl_send($xml_post_string, $url);
				$xmlToArray = $this->curl->xmlToArray($curl_send);
				
				
				 if ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageID'] ) && $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageID'] == "SXSWS_27" ) {
					
					echo json_encode([ 'status' => 200, 'message' => "Site already armed", 'dataStatus' => 'false']) ;
					
				}  elseif ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageID'] ) && $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageID'] == "SXSWS_12" ) {
					
					$messageText = ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageText'] ) ? $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageText'] : "Site is currently been modified, please try again later"   )  ;
					
					echo json_encode([ 'status' => 200, 'message' => $messageText, 'dataStatus' => 'locked']) ;
					
				} elseif ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors'] ) ){
					
					echo json_encode([ 'status' => 200, 'message' => "Internal server error", 'dataStatus' => 'false']) ;
					
				} elseif ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult'] ) ) {
					
					echo json_encode([ 'status' => 200, 'message' => "Site armed successfully", 'dataStatus' => 'true']) ;
					
				} else {
					
					echo json_encode([ 'status' => 200, 'message' => "Internal server error", 'dataStatus' => 'false']) ;
				
				}
				
				
				
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Serial number is required."]) ;
		}
	
	
	
	}
	
	public function getSiteStatus() {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		$serialNumber = $this->input->post('serial_number') ;
		
		/***remove later***
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		/***remove later***/
		

		if ($serialNumber) {
				
				/***remove later***
				$serialNumber = "160463" ;
				/***remove later***/
				
			    $url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/GetSite";
				$xml_post_string = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
				<SOAP-ENV:Envelope
				 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
				 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
				 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
				xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
				xmlns:xsd="http://www.w3.org/2001/XMLSchema">
				<SOAP-ENV:Body>
					<GetSite xmlns="http://www.monitorsoft.com/SentinelXS/clsSentinelXS">
						<getSiteRequestKey>
							<UserName>'.$username.'</UserName>
							<Password>'.$password .'</Password>
							<SerialNumber>'.(int)$serialNumber .'</SerialNumber>
						</getSiteRequestKey>
					</GetSite>
				</SOAP-ENV:Body>
				</SOAP-ENV:Envelope>';

				$curl_send = $this->curl->curl_send($xml_post_string, $url);
				$xmlToArray = $this->curl->xmlToArray($curl_send);
				
				
				$siteStatus = ( isset( $xmlToArray['GetSiteResponse']['GetSiteResult']['SiteInformation']['IsOnTest'] ) ? $xmlToArray['GetSiteResponse']['GetSiteResult']['SiteInformation']['IsOnTest']  : ''   )     ;
				
				if ( $siteStatus ) {
					
					echo json_encode([ 'status' => 200, 'message' => "Site status found", 'dataStatus' => 'true', 'isOnTest' => $siteStatus]) ;
					
				} else {
					
					echo json_encode([ 'status' => 200, 'message' => "Site status not found.", 'dataStatus' => 'false', 'isOnTest' => $siteStatus]) ;
				
				}

		} else {
			echo json_encode([ 'status' => 500, 'message' => "Serial number is required."]) ;
		}
	
	
	
	}
	
	public function putItemOnTestAutomatically() {
		
		//echo json_encode([ 'status' => 200, 'message' => "Auto arm/disarm is disabled", 'dataStatus' => 'false' ]) ;
		//exit ;
		
		
		$dataUser = $this->mainUserData ;
		
		if( isset($dataUser['auto_arm_disarm_status']) &&  $dataUser['auto_arm_disarm_status'] == 'false' ) {
			echo json_encode([ 'status' => 200, 'message' => "Auto arm/disarm is disabled", 'dataStatus' => 'false' ]) ;
			exit ;
		}
		
		
		if( isset($dataUser['disarm_range']) &&  $dataUser['disarm_range'] ) {
			$db_disarm_range =  $dataUser['disarm_range'] ;
		} else {
			$db_disarm_range = "100" ;
		}
		
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		
		$latitudeFrom  = $this->input->post('latitude') ;
		$longitudeFrom = $this->input->post('longitude') ;
		
		/***remove later***
		
		$insertLogHere  = $this->users->log_putItemOnTestAutomatically($latitudeFrom, $longitudeFrom, $dataUser['user_id']) ;
		
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		/***remove later***/
		
		if ($latitudeFrom && $longitudeFrom) {
			
			$validateLatLong   = $this->validateLatLong($latitudeFrom, $longitudeFrom) ;
			
			if (!$validateLatLong) {
				echo json_encode([ 'status' => 500, 'message' => "Invalid Latitude/Longitude."]) ;
			} else {
				
				try {
					$conexion = new PDO("informix:host=".$this->config->item('pdo_connect')['host'].";service=".$this->config->item('pdo_connect')['service'].";database=".$this->config->item('pdo_connect')['database'].";server=".$this->config->item('pdo_connect')['server'].";protocol=".$this->config->item('pdo_connect')['protocol'].";EnableScrollableCursors=".$this->config->item('pdo_connect')['EnableScrollableCursors'].";client_locale=".$this->config->item('pdo_connect')['client_locale'].";db_locale=".$this->config->item('pdo_connect')['db_locale'] ,$this->config->item('pdo_connect')['db_user'],$this->config->item('pdo_connect')['db_pass']);
				} catch( PDOException $Exception ) {
					echo json_encode([ 'status' => 500, 'message' => "Internal server error."]) ;
					exit ;
				}
		
				$sql    = 'select * from webusers where name = "'.$username.'" and agctype = 4';
				$prep   = $conexion->prepare($sql);
				$prep->execute();
				$result = $prep->fetchAll(PDO::FETCH_ASSOC);
				
				if ( isset($result[0]['AGCNO']) && $result[0]['AGCNO'] ) {
					
					$linkAccountId = $result[0]['AGCNO'] ;
					
					/* This is with comstate 1 only
					 * Uncomment this and remove below one
					 * 
					 * $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno inner join (select serialno,Min(commsno) as commsno2 from systrans group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND T02.commstate = 1 ORDER BY T01.serialno DESC" ;
					 */
					
					
					$sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno inner join (select serialno,Min(commsno) as commsno2 from systrans group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) ORDER BY T01.serialno DESC" ;
					
					
					$prepCon   = $conexion->prepare($sqlNew);
					$prepCon->execute();
					$resultTotal = $prepCon->fetchAll(PDO::FETCH_ASSOC);
					
					if ($resultTotal) {
						
						$disarmedSiteString = "" ;
						$count				= 0 ;
						$armedSiteString 	= "" ;
						$countArmed 		= 0 ;
						
						foreach($resultTotal as $value) {
							
							##### New Code Starts ###
							
							$calculateDistance = false ;

							if ( isset($value['NETADDR2']) && $value['NETADDR2']) {
								
								$explodeLocation  = explode(',', $value['NETADDR2']) ;
								
								if ( ( isset($explodeLocation[0]) && $explodeLocation[0] ) && ( isset($explodeLocation[1]) && $explodeLocation[1] )) {
									
									$latitudeTo  = trim($explodeLocation[0]);
									$longitudeTo = trim($explodeLocation[1]);
									
									if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
											$calculateDistance = true ;
									} else {
										
										$checkDbLatLong = $this->users->checkSiteAlreadyExists($value['SERIALNO']) ;  // check in database
										
										if ( $checkDbLatLong ) {
										
											$latitudeTo  = trim($checkDbLatLong['latitude']);
											$longitudeTo = trim($checkDbLatLong['longitude']);
											
											if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
													$calculateDistance = true ;
											}
										
										}
										
								  }
								} else {
								
									$checkDbLatLong = $this->users->checkSiteAlreadyExists($value['SERIALNO']) ;  // check in database
										
									if ( $checkDbLatLong ) {
									
										$latitudeTo  = trim($checkDbLatLong['latitude']);
										$longitudeTo = trim($checkDbLatLong['longitude']);
										
										if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
												$calculateDistance = true ;
										}
									
									}
								
								}
								
							} else {

								$checkDbLatLong = $this->users->checkSiteAlreadyExists($value['SERIALNO']) ;  // check in database
										
								if ( $checkDbLatLong ) {
								
									$latitudeTo  = trim($checkDbLatLong['latitude']);
									$longitudeTo = trim($checkDbLatLong['longitude']);
									
									if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
											$calculateDistance = true ;
									}
								
								}

							}
							
							##### New Code Starts ###
							
							if( $calculateDistance ) { // if we have lat/long from above cases
										
								  $earthRadius = 6371000;
								
								  $latFrom = deg2rad($latitudeFrom);
								  $lonFrom = deg2rad($longitudeFrom);
								  $latTo   = deg2rad($latitudeTo);
								  $lonTo   = deg2rad($longitudeTo);

								  $lonDelta = $lonTo - $lonFrom;
								  $a = pow(cos($latTo) * sin($lonDelta), 2) +
									pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
								  $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);

								  $angle 	= atan2(sqrt($a), $b);
								  $distance = round($angle * $earthRadius) ;
								
								  if ( $distance <= $db_disarm_range) { // distance compared here
									  
									/***remove later***
									if ( $value['SERIALNO'] ==  '160463' )  {
									/***remove later***/
										
										/***check here if the site is already is on test  then continue from here****/
						
										$isOntest = $this->calledFromFunctionGetSiteStatus($value) ;
										
										if($isOntest == "YES") {
											continue;
										}
										
										/***check here if the site is already is on test  then continue from here****/
										
										
										$putItemOnTest = $this->calledFromFunctionToPutItemOnTest($value) ;
										
										if($putItemOnTest == "YES") {
											
											if ( $count != 0 ) {
												$disarmedSiteString .= ", " ;
											}
											
											$disarmedSiteString .= $value['NAME']   ;
											$count++ ;
											
											/***Add data in data base***/
											
											$value['USER_ID'] 	 = $dataUser['user_id'] ;
											$insertDisarmedSites = $this->users->insertDisarmedSites($value) ;
											
											/***Add data in data base***/
										}
										
									/***remove later***
									}
									/***remove later***/
									
								  } else {
									  
									/***Site greater then 500 meters if site found in database disarm it and remove data from database***/
									
									$checkSiteDisarmed = $this->users->checkSiteDisarmed($value['SERIALNO'], $dataUser['user_id']) ;
									
									if ( $checkSiteDisarmed == "YES" ) {
										
										$takeItemOffTest = $this->calledFromFunctionToTakeItemOffTest($value) ;
										
										if ( $takeItemOffTest == "YES") {
											
											if ( $countArmed != 0 ) {
												$armedSiteString .= ", " ;
											}
											
											$armedSiteString .= $value['NAME']   ;
											$countArmed++ ;
											
											$deleteDisarmedSites = $this->users->deleteDisarmedSites($value['SERIALNO'], $dataUser['user_id']) ;
										}
										
									}
								  }
								}
						} // end of for each
						
						if ($armedSiteString) {
							
							$msgArmed = "Site automatically armed based on your location: " . $armedSiteString ;
							
							/*Send push notification if user have google firebase token */
							if ( isset($dataUser['google_firebase_token']) && $dataUser['google_firebase_token']) {
							
								$sendPushNotification = $this->sendPushNotification($dataUser['google_firebase_token'], $msgArmed) ;
							} 
							
						} else {
								$msgArmed = "No sites armed" ;
						}
						
						
						if ($disarmedSiteString) {
							
							$msgDisarmed 		  = "Site automatically disarmed based on your location: " . $disarmedSiteString ;
							
							/*Send push notification if user have google firebase token*/
							if ( isset($dataUser['google_firebase_token']) && $dataUser['google_firebase_token']) {
								
									$sendPushNotification = $this->sendPushNotification($dataUser['google_firebase_token'], $msgDisarmed) ;
							} 
							
						} else {
							$msgDisarmed =  "No sites disarmed." ;
						}
						
						
						echo json_encode([ 'status' => 200, 'message' => $msgDisarmed, 'sitesArmed' =>  $msgArmed, 'dataStatus' => 'true' ]) ;
						
						
					} else {
						echo json_encode([ 'status' => 200, 'message' => "No data found.", 'dataStatus' => 'false' ]) ;
					}
					
					
					
				} else {
					echo json_encode([ 'status' => 500, 'message' => "Internal server error."]) ;
				}
				
				
			}
			
			
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Latitude/Longitude is required."]) ;
		}
	
	}
	
	public function calledFromFunctionToPutItemOnTest($data) {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		$serialNumber = $data['SERIALNO'] ;
		
		
		/***remove later***
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		$serialNumber = "160463" ;
		/***remove later***/
		
		// 60 minutes additionally added to match with UK  time.
		
		if( isset($dataUser['disarm_range']) &&  $dataUser['disarm_range'] ) {
			$db_disarm_time =  ( 60 + $dataUser['disarm_time'] ) ;
		} else {
			$db_disarm_time = "120" ; // 60 + 60 // 60 minutes default time
		}
		
		
		
		$todayDate	  = date('Y-m-d');
		$current_time  = date('H:i:s',strtotime('+'.$db_disarm_time.'minutes'));

	    $onTestUntil   = $todayDate.'T'.$current_time.'Z' ;
	   
	    $url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/PutItemOnTest";
	    $xml_post_string = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
			<soap:Header />
			<soap:Body>
				<cls:PutItemOnTest>
					<cls:putItemOnTestRequestKey>
						<cls:ServiceVersion>Version_1_119_4</cls:ServiceVersion>
						<cls:UserName>'.$username.'</cls:UserName>
						<cls:Password>'.$password.'</cls:Password>
						<cls:SerialNumber>'.$serialNumber.'</cls:SerialNumber>
						<cls:OnTestType xsi:type="cls:OnTestSite"></cls:OnTestType>
						<cls:OnTestUntil>'.$onTestUntil.'</cls:OnTestUntil>
						<cls:Description>Site taken out of service by the Monitoring app. '.$username.'</cls:Description>
					</cls:putItemOnTestRequestKey>
				</cls:PutItemOnTest>
			</soap:Body>
		</soap:Envelope>';
		
		$curl_send = $this->curl->curl_send($xml_post_string, $url);
		$xmlToArray = $this->curl->xmlToArray($curl_send);
		
		if ( isset( $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult']['Errors'] ) ){
					
			return "NO" ;
			
		} elseif ( isset( $xmlToArray['PutItemOnTestResponse']['PutItemOnTestResult'] ) ) {
			
			return "YES";
			
		} else {
			
			return "NO" ;
		
		}
		
	}
	
	public function calledFromFunctionGetSiteStatus($data) {
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		$serialNumber = $data['SERIALNO'] ;
		
		/***remove later***
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		/***remove later***/
			
		$url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/GetSite";
		$xml_post_string = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
		<SOAP-ENV:Envelope
		 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
		 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
		 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:xsd="http://www.w3.org/2001/XMLSchema">
		<SOAP-ENV:Body>
			<GetSite xmlns="http://www.monitorsoft.com/SentinelXS/clsSentinelXS">
				<getSiteRequestKey>
					<UserName>'.$username.'</UserName>
					<Password>'.$password .'</Password>
					<SerialNumber>'.(int)$serialNumber .'</SerialNumber>
				</getSiteRequestKey>
			</GetSite>
		</SOAP-ENV:Body>
		</SOAP-ENV:Envelope>';

		$curl_send = $this->curl->curl_send($xml_post_string, $url);
		$xmlToArray = $this->curl->xmlToArray($curl_send);
		
		//debug($xmlToArray, 1) ;
		
		$siteStatus = ( isset( $xmlToArray['GetSiteResponse']['GetSiteResult']['SiteInformation']['IsOnTest'] ) ? $xmlToArray['GetSiteResponse']['GetSiteResult']['SiteInformation']['IsOnTest']  : ''   )     ;
		
		if ( $siteStatus ) {
			
			if ($siteStatus == "true") {
				return "YES";
			} else {
				return "NO" ;
			}
			
		} else {
			return "NO" ;
		}

	}
	
	public function sendPushNotification($fcmDeviceToken, $msg) {
		
		$dataUser = $this->mainUserData ;
		
		$url		= 'https://fcm.googleapis.com/fcm/send' ;
		$serverKey  = self::$API_ACCESS_KEY ;
							
		$message = array(
			'message' => $msg,
			'disarmTime' => $dataUser['disarm_time'],
			'title' => 'armDisarmAuto'
		);

		$headers = array(
			'Authorization: key=' . $serverKey,
			'Content-Type: application/json'
		);

		$fields = array(
			'registration_ids' => [$fcmDeviceToken],
			'data' => $message,
			'priority' 		=> 'high'
		);

							
		$ch = curl_init();
		// Set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		// Disabling SSL Certificate support temporarly
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		if ($fields) {
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
		}

		// Execute post
		$result = curl_exec($ch);
		
		if ($result === FALSE) {
		  // curl failed 
		} else {
			// curl not failed
		}

		// Close connection
		curl_close($ch);


	}	

	public function calledFromFunctionToTakeItemOffTest($data) {
		
		
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		$serialNumber = $data['SERIALNO'] ;
	
		/***remove later***
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		$serialNumber = "160463" ;
		/***remove later***/
		
	
		   $url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/TakeItemOffTest";
		   $xml_post_string = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
				<soap:Header />
				<soap:Body>
					<cls:TakeItemOffTest>
						<cls:takeItemOffTestRequestKey>
							<cls:ServiceVersion>Version_1_119_4</cls:ServiceVersion>
							<cls:UserName>'.$username.'</cls:UserName>
							<cls:Password>'.$password.'</cls:Password>
							<cls:SerialNumber>'.$serialNumber.'</cls:SerialNumber>
							<cls:OnTestType xsi:type="cls:OnTestSite"></cls:OnTestType>
						</cls:takeItemOffTestRequestKey>
					</cls:TakeItemOffTest>
				</soap:Body>
			</soap:Envelope>';
			
			
			$curl_send = $this->curl->curl_send($xml_post_string, $url);
			$xmlToArray = $this->curl->xmlToArray($curl_send);
			
			
			 if ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageID'] ) && $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors']['Message']['MessageID'] = "SXSWS_27" ) {
				
				return "YES" ;
				
			} elseif ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult']['Errors'] ) ){
				
				return "NO" ;
				
			} elseif ( isset( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult'] ) ) {
				
				return "YES" ;
				
			} else {
				
				return "NO" ;
			
			}
	}


	public function configureAutoArmDisarm() {
		
		
		$dataUser = $this->mainUserData ;
		
		$armDisarmStatus = $this->input->post('armDisarmStatus') ;
		$range 	 		 = $this->input->post('disarmRange') ;
		$time 	 		 = $this->input->post('disarmTime') ;
	
		
		if ($armDisarmStatus && $range  && $time) {
			
			$arrayArmDisarmStatus = ['true', 'false'] ;
			
			if(!in_array($armDisarmStatus, $arrayArmDisarmStatus)) {
				echo json_encode([ 'status' => 500, 'message' => "Status is not valid format"]) ;
				exit;
			}
			
			
			$data['auto_arm_disarm_status'] =    $armDisarmStatus;
			$data['disarm_range'] 			=    $range;
			$data['disarm_time'] 			=    $time;
			
			$userId = $dataUser['user_id'] ;
			
			$updateAutoArmDisarm = $this->users->updateAutoArmDisarm($data, $userId) ;
			
			if ( $updateAutoArmDisarm ) {
			
				echo json_encode([ 'status' => 200, 'message' => "Updated successfully", 'armDisarmStatus' => $armDisarmStatus, 'disarmRange' => $range, 'disarmTime' => $time, 'dataStatus' => 'true']) ;
			
			} else {
				echo json_encode([ 'status' => 200, 'message' => "Internal server error", 'dataStatus' => 'false']) ;
			}
			
			
		} else {
			
			if (!$armDisarmStatus && !$range && !$time) {
				$message  		 = "Status, Range, Time is required.";
			} elseif (!$armDisarmStatus) {
				$message  		 = "Status is required.";
			} elseif(!$range) {
				$message  		 = "Range is required.";
			} else {
				$message  		 = "Time is required.";
			}
			
			
			echo json_encode([ 'status' => 500, 'message' => $message]) ;
		}
	}
	
	
	public function getNearestSiteEvents() {
	
		$dataUser  = $this->mainUserData ;
		
		$siteRange = "250" ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		
		$latitudeFrom  = $this->input->post('latitude') ;
		$longitudeFrom = $this->input->post('longitude') ;
		
		if ($latitudeFrom && $longitudeFrom) {
			
			$validateLatLong   = $this->validateLatLong($latitudeFrom, $longitudeFrom) ;
			
			if (!$validateLatLong) {
				echo json_encode([ 'status' => 500, 'message' => "Invalid Latitude/Longitude"]) ;
			} else {
				
				try {
					$conexion = new PDO("informix:host=".$this->config->item('pdo_connect')['host'].";service=".$this->config->item('pdo_connect')['service'].";database=".$this->config->item('pdo_connect')['database'].";server=".$this->config->item('pdo_connect')['server'].";protocol=".$this->config->item('pdo_connect')['protocol'].";EnableScrollableCursors=".$this->config->item('pdo_connect')['EnableScrollableCursors'].";client_locale=".$this->config->item('pdo_connect')['client_locale'].";db_locale=".$this->config->item('pdo_connect')['db_locale'] ,$this->config->item('pdo_connect')['db_user'],$this->config->item('pdo_connect')['db_pass']);
				} catch( PDOException $Exception ) {
					echo json_encode([ 'status' => 500, 'message' => "Internal server error"]) ;
					exit ;
				}
		
				$sql    = 'select * from webusers where name = "'.$username.'" and agctype = 4';
				$prep   = $conexion->prepare($sql);
				$prep->execute();
				$result = $prep->fetchAll(PDO::FETCH_ASSOC);
				
				if ( isset($result[0]['AGCNO']) && $result[0]['AGCNO'] ) {
					
					$linkAccountId = $result[0]['AGCNO'] ;
					
					/* This is with comstate 1 only
					 * Uncomment this and remove below one
					 * 
					 * $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno inner join (select serialno,Min(commsno) as commsno2 from systrans group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND T02.commstate = 1 ORDER BY T01.serialno DESC" ;
					 
					
					
					 $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno inner join (select serialno,Min(commsno) as commsno2 from systrans group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.recid = T05.recid WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND T02.commstate = 1 ORDER BY T01.serialno DESC" ;*/
					 
					 
					  $sqlNew = "select T01.name, T01.serialno, T01.address_postcode, T04.netaddr2, T04.panelid, T05.name as transtype ,T03.commsno2 FROM customer as T01 inner join monitoring as T02 on T01.serialno = T02.serialno and T02.commstate = 1
inner join (select serialno,Min(commsno) as commsno2 from systrans where LEN(netaddr)> 0 group by serialno) as T03 on T01.serialno = T03.serialno inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno INNER JOIN receiver AS T05 ON T04.transtype = T05.type AND T05.recid not IN(37,38,39,44) WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) ORDER BY T01.serialno desc";
					
					
					$prepCon   = $conexion->prepare($sqlNew);
					$prepCon->execute();
					$resultTotal = $prepCon->fetchAll(PDO::FETCH_ASSOC);
					
					if ($resultTotal) {
						
						$count				= 0 ;
						$siteInRange  		= "" ;
						
						foreach($resultTotal as $value) {
							
							##### New Code Starts ###
							
							$calculateDistance = false ;

							if ( isset($value['NETADDR2']) && $value['NETADDR2']) {
								
								$explodeLocation  = explode(',', $value['NETADDR2']) ;
								
								if ( ( isset($explodeLocation[0]) && $explodeLocation[0] ) && ( isset($explodeLocation[1]) && $explodeLocation[1] )) {
									
									$latitudeTo  = trim($explodeLocation[0]);
									$longitudeTo = trim($explodeLocation[1]);
									
									if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
											$calculateDistance = true ;
									} else {
										
										$checkDbLatLong = $this->users->checkSiteAlreadyExists($value['SERIALNO']) ;  // check in database
										
										if ( $checkDbLatLong ) {
										
											$latitudeTo  = trim($checkDbLatLong['latitude']);
											$longitudeTo = trim($checkDbLatLong['longitude']);
											
											if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
													$calculateDistance = true ;
											}
										
										}
										
								  }
								} else {
								
									$checkDbLatLong = $this->users->checkSiteAlreadyExists($value['SERIALNO']) ;  // check in database
										
									if ( $checkDbLatLong ) {
									
										$latitudeTo  = trim($checkDbLatLong['latitude']);
										$longitudeTo = trim($checkDbLatLong['longitude']);
										
										if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
												$calculateDistance = true ;
										}
									
									}
								
								}
								
							} else {

								$checkDbLatLong = $this->users->checkSiteAlreadyExists($value['SERIALNO']) ;  // check in database
										
								if ( $checkDbLatLong ) {
								
									$latitudeTo  = trim($checkDbLatLong['latitude']);
									$longitudeTo = trim($checkDbLatLong['longitude']);
									
									if ( $this->validateLatLong($latitudeTo, $longitudeTo) ) {
											$calculateDistance = true ;
									}
								
								}

							}
							
							##### New Code Starts ###
							
							if( $calculateDistance ) { // if we have lat/long from above cases
								
								
								 $earthRadius = 6371000;
										
								  $latFrom = deg2rad($latitudeFrom);
								  $lonFrom = deg2rad($longitudeFrom);
								  $latTo   = deg2rad($latitudeTo);
								  $lonTo   = deg2rad($longitudeTo);

								  $lonDelta = $lonTo - $lonFrom;
								  $a = pow(cos($latTo) * sin($lonDelta), 2) +
									pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
								  $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);

								  $angle 	= atan2(sqrt($a), $b);
								  $distance = round($angle * $earthRadius) ;
								  
								  if ( $distance <= $siteRange) { // distance compared here
										
									$siteInRange = $value ;
									break ;
									
								  } 
								
							}
							
						} // end of for each
						
						if ($siteInRange) {
							
							if ( isset($siteInRange['SERIALNO']) && $siteInRange['SERIALNO']   ) {
								$getEvents = $this->calledFromFunctionToGetEvents($siteInRange['SERIALNO'], 'today') ;
							} else {
								$getEvents = [] ;
							}
							
							echo json_encode([ 'status' => 200, 'message' => "site found", 'siteDetails' => $siteInRange, 'eventDetails' => $getEvents, 'dataStatus' => 'true' ]) ;
							
							
						} else {
								echo json_encode([ 'status' => 200, 'message' => "No site found", 'dataStatus' => 'false' ]) ;
						}
						
					} else {
						echo json_encode([ 'status' => 200, 'message' => "No sites found", 'dataStatus' => 'false' ]) ;
					}
					
					
					
				} else {
					echo json_encode([ 'status' => 500, 'message' => "Link account number not found", 'dataStatus' => 'false']) ;
				}
				
				
			}
			
			
		} else {
			echo json_encode([ 'status' => 500, 'message' => "Latitude/Longitude is required.", 'dataStatus' => 'false']) ;
		}
	
	}
	
	
	public function calledFromFunctionToGetEvents($serialNumber, $eventFor) {
	
		$dataUser = $this->mainUserData ;
		
		$username = encrypt_string($dataUser['user_name'],'d') ;
		$password = encrypt_string($dataUser['user_password'],'d') ;
		
		if ($eventFor == "today") {
			
			$startDate = date('Y-m-d') . "T00:00:00";
			$endDate   = date('Y-m-d')."T".date('H:i:s') ;
			
		} elseif($eventFor == "last24Hours") {
			
			$startDate =  date('Y-m-d', strtotime("-1 day")) ."T".   date('H:i:s', strtotime("-1 day")) ;
			$endDate   =  date('Y-m-d')."T".date('H:i:s') ;
			
		} elseif($eventFor == "last7Days") {
						
			$startDate =  date('Y-m-d', strtotime("-6 days")) . "T00:00:00";
			$endDate   =  date('Y-m-d')."T".date('H:i:s') ;
			
		} elseif($eventFor == "calendar") {
						
			$startDate =  $this->input->post('start_date')."T00:00:00" ;
			$endDate   =  $this->input->post('end_date')."T23:59:59" ;
			
			if (!$startDate && !$endDate ) {
				echo json_encode([ 'status' => 500, 'message' => "Start/End date is required."]) ;
				exit;
			}
			
		} else {
			$startDate = date('Y-m-d') . "T00:00:00";
			$endDate   = date('Y-m-d')."T".date('H:i:s') ;
		}
		
		$url_alarm = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/ListLogDetailItems";
		
		$xml_post_string_alarm = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
						<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
						   <soap:Header/>
						   <soap:Body>
							  <cls:ListLogDetailItems>
								 <!--Optional:-->
								 <cls:listLogDetailItemsRequestKey>
									<cls:ServiceVersion>Version_1_110_4</cls:ServiceVersion>
									<!--Optional:-->
									<cls:UserName>'.$username.'</cls:UserName>
									<!--Optional:-->
									<cls:Password>'.$password.'</cls:Password>
									<!--Optional:-->
									<cls:LogDetailFilter>
									   <!--Optional:-->

									   <cls:FilterList>
										  <cls:LogDetailFilterListItem>
											 <cls:FilterAttribute  xsi:type="cls:SerialNumberLogDetailFilterAttribute"/>
											 <cls:FilterOperator  xsi:type="cls:EqualityLogDetailFilterOperator"/>
											 <cls:FilterValue  xsi:type="cls:LogDetailFilterComparisonInteger">
											 <cls:Value>'.$serialNumber.'</cls:Value>
											 </cls:FilterValue>
										  </cls:LogDetailFilterListItem>


										   <cls:LogDetailFilterListItem>

															<cls:FilterAttribute xsi:type="cls:DateRangeLogDetailFilterAttribute" />

												 <cls:FilterOperator xsi:type="cls:EqualityLogDetailFilterOperator" />

												 <cls:FilterValue xsi:type="cls:LogDetailFilterComparisonDateRange">

													  <cls:FromValue>'.$startDate.'</cls:FromValue>

													  <cls:ToValue>'.$endDate.'</cls:ToValue>

												 </cls:FilterValue>

										   </cls:LogDetailFilterListItem>
															 <cls:LogDetailFilterListItem>
														<cls:FilterAttribute xsi:type="cls:LogCategoryLogDetailFilterAttribute" />
														<cls:FilterOperator xsi:type="cls:InLogDetailFilterOperator" />
														<cls:FilterValue xsi:type="cls:LogDetailFilterComparisonLogCategoryList">
																	<cls:Value>
																		<cls:BaseLogCategoryListItem xsi:type="cls:SignalLogCategoryListItem" />

																		<cls:BaseLogCategoryListItem xsi:type="cls:AlarmLogCategoryListItem" />

																		<cls:BaseLogCategoryListItem xsi:type="cls:TrackingLogCategoryListItem" />

																		<cls:BaseLogCategoryListItem xsi:type="cls:AudioLogCategoryListItem" />

																		<cls:BaseLogCategoryListItem xsi:type="cls:CctvLogCategoryListItem" />
																 </cls:Value>
														</cls:FilterValue>
											</cls:LogDetailFilterListItem>
									   </cls:FilterList>
									</cls:LogDetailFilter>
								 </cls:listLogDetailItemsRequestKey>
							  </cls:ListLogDetailItems>
						   </soap:Body>
						</soap:Envelope>';


		$curl_send_alarm = $this->curl->curl_send($xml_post_string_alarm, $url_alarm);
		$data = array();
		$xmlToArray_alarm = $this->curl->xmlParse($curl_send_alarm);

		$list_log_header_xml = ( isset( $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] )  && $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] ? $xmlToArray_alarm['soap:Body']['ListLogDetailItemsResponse']['ListLogDetailItemsResult']['ListOfLogDetailItems']['LogDetailListItem'] : '' );
		
		
		if ($list_log_header_xml) {
			
			if( !isset( $list_log_header_xml[0]['SerialNumber'] ) ) {
				$result[] = $list_log_header_xml ;
			} else {
				$result  =  $list_log_header_xml ;
			} 
		} else {
			$result = [] ;
		}
				
		return $result ;
  }
	
	
  public function getSignals() {
	  
	$panelId 			 = $this->input->post('panelId') ;
	$logHeaderIdentifier = $this->input->post('logHeaderIdentifier') ;
	
	
	if( $panelId && $logHeaderIdentifier ) {
		$host	 				 = '34.218.89.169';
		$service 				 = '1526';
		$database 				 = 'isent98';
		$server 				 = 'ol_omsdb3';
		$protocol 				 = 'onsoctcp';
		$EnableScrollableCursors = '1';
		$client_locale			 = 'en_us.8859-1';
		$db_locale 				 = 'en_us.8859-1';
		$db_user				 = 'ReadOnly';
		$db_pass 				 = 'nowriting';
		$error					 = '' ;
				
		
		try {
			$conexion = new PDO("informix:host=".$host.";service=".$service.";database=".$database.";server=".$server.";protocol=".$protocol.";EnableScrollableCursors=".$EnableScrollableCursors.";client_locale=".$client_locale.";db_locale=".$db_locale ,$db_user ,$db_pass);
		} catch( PDOException $Exception ) {
			
			echo json_encode([ 'status' => 500, 'message' => "There is some error in database connection", 'dataStatus' => 'false', 'data' => '']) ;
			
			exit;
		}
		
		
		$sql = 'select T01.srcid, T01.evtime, T01.rawinfo, T03.evstring
from rawdata as T01 inner join systrans as T02 on T01.serialno = T02.serialno left join detlog as T03 on T01.serialno = T03.serialno and T01.seqno = T03.rseqno
WHERE T02.panelid = "'.(int)$panelId.'"
AND T03.lseqno = "'.(int)$logHeaderIdentifier.'"
AND T02.recid in (29, 11, 6)';
			$prep   = $conexion->prepare($sql);
			$prep->execute();
			$resultTotal = $prep->fetchAll(PDO::FETCH_ASSOC);
			if (!$resultTotal ) {
				$data = [] ;
				$message = "No data found" ;
			} else {
				$data = $resultTotal ;
				$message = "Data found" ;
			}
			//debug($resultTotal, 1) ;
			echo json_encode([ 'status' => 200, 'message' => $message, 'dataStatus' => 'true', 'data' => $data]) ;
	} else {
	
		echo json_encode([ 'status' => 204, 'message' => "Panel Id and Log Header Identifier are required", 'dataStatus' => 'false', 'data' => '']) ;
	
	}	
	
  }	
	
	
  public function getAllSitesGeocode() {
  
	
		$host	 				 = '34.218.89.169';
		$service 				 = '1526';
		$database 				 = 'isent98';
		$server 				 = 'ol_omsdb3';
		$protocol 				 = 'onsoctcp';
		$EnableScrollableCursors = '1';
		$client_locale			 = 'en_us.8859-1';
		$db_locale 				 = 'en_us.8859-1';
		$db_user				 = 'ReadOnly';
		$db_pass 				 = 'nowriting';
		$error					 = '' ;
				
		
		try {
			$conexion = new PDO("informix:host=".$host.";service=".$service.";database=".$database.";server=".$server.";protocol=".$protocol.";EnableScrollableCursors=".$EnableScrollableCursors.";client_locale=".$client_locale.";db_locale=".$db_locale ,$db_user ,$db_pass);
		} catch( PDOException $Exception ) {
			
			echo json_encode([ 'status' => 500, 'message' => "There is some error in database connection", 'dataStatus' => 'false', 'data' => '']) ;
			
			exit;
		}
  
		$sql = "select name, serialno, address_postcode FROM customer Where instno IN (1000,1002,1003,1006) AND name NOT LIKE '%STOCK/%'";
		$prep   = $conexion->prepare($sql);
		$prep->execute();
		$resultTotal = $prep->fetchAll(PDO::FETCH_ASSOC);
		
		
		if ( $resultTotal ) {
			
			$counter 			= 0 ; // For newly inserted
			$noPostalCodes 		= 0 ;
			$alreadyInserted 	= 0 ;
			$geoCodeNotFound 	= 0 ; // geo code error / or lat-long not found
			
			
			foreach( $resultTotal as $arrayData ) {
			
				if ( isset( $arrayData['ADDRESS_POSTCODE'] ) && $arrayData['ADDRESS_POSTCODE'] ) {
					
					$checkSiteAlreadyExists = $this->users->checkSiteAlreadyExists($arrayData['SERIALNO']) ; 
					
					if ( !$checkSiteAlreadyExists ) { // Perform the google geocode API
						
						/***Google Geocode Starts***/
						
						$zip  = $arrayData['ADDRESS_POSTCODE'] ;
						
						$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&components=" . urlencode('country:GB') . "&key=AIzaSyAnLSfp3Pr0-SsgG1U8T61Wy-gSttmDyYY";
						
						$result_string = file_get_contents($url);
						
						$result = json_decode($result_string, true);
						
						
						if ( $result ) {
 
							if ( ( isset( $result['results'][0]['geometry']['location']['lat'] ) && $result['results'][0]['geometry']['location']['lat'] ) &&  ( isset( $result['results'][0]['geometry']['location']['lng']  ) && $result['results'][0]['geometry']['location']['lng'] ) ) {
		
								$formattedAddress = ( isset( $result['results'][0]['formatted_address'] ) && $result['results'][0]['formatted_address'] ? $result['results'][0]['formatted_address'] : '' ) ;
								
								$insertData = $arrayData ;
								$insertData['latitude']			 = $result['results'][0]['geometry']['location']['lat']  ;
								$insertData['longitude'] 		 = $result['results'][0]['geometry']['location']['lng'] ;
								$insertData['formatted_address'] = $formattedAddress ;
								
								$insert  =  $this->users->insertSiteGeocodes($insertData) ;
						
								$counter++ ;
								
							} else {
								$geoCodeNotFound++ ;
							}
 
 
						} else {
							$geoCodeNotFound++ ; 
						}
						
						
						
						/***Google Geocode Ends***/

					} else {
						$alreadyInserted++ ;
					}
					
				} else {
					$noPostalCodes++ ;
				}
			
			} 
			
			echo "Total Sites 	= " . count($resultTotal)."<br />" ;
			echo "New Inserted Sites = " . $counter."<br />" ;
			echo "Already Inserted  Sites = " . $alreadyInserted."<br />" ;
			echo "Sites With No Postal Codes 	= " . $noPostalCodes."<br />" ;
			echo "Google Geocode Failure 	= " . $geoCodeNotFound."<br />" ;
			
			
		} else {
		
			echo "No data returned from sentinal." ;
		}
		
		
		// debug($resultTotal, 1) ;
  }	
	
	
	public function sendNotificationsWakeSleepModeDevices() {
	
		$getGoogleFCMToken = $this->users->getTokenLoggedInUsers() ; // Users logged in with having token
		
		// debug($getGoogleFCMToken, 1) ;
		
		
		if ( $getGoogleFCMToken ) {
			
			$url 			= 'https://fcm.googleapis.com/fcm/send' ;
			$serverKey      = self::$API_ACCESS_KEY ;
			$message = array(
				'title' => 'wakeSleepModeDevices',
			);

			$headers = array(
				'Authorization: key=' . $serverKey,
				'Content-Type: application/json'
			);

			$fields = array(
				'registration_ids'  => $getGoogleFCMToken,
				'data'				=> $message,
				'priority' 			=> 'high'
			);

			$ch = curl_init();
			
			// Set the url, number of POST vars, POST data
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			// Disabling SSL Certificate support temporarly
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			if ($fields) {
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
			}

			// Execute post
			$result = curl_exec($ch);
			if ($result === FALSE) {
				
			   $message  = 'Curl failed: ' . curl_error($ch) ;
			   
			   
			} else {
				
				$resultArray = json_decode($result, true);
				
				//debug($resultArray) ;
				
				$message = "Curl successful, Notifications sent to valid FCM tokens" ;
				
			}

			// Close connection
			curl_close($ch);
				
		} else {
		
			$message = "No Users Found" ;
		
		}
		
		echo $message ;
			
	}
	
	/***Below are testing API functions***/
	public function listSites() {
	
		$username 				= 'servicesentryengineer1' ;
		$password  				= 'Js013579!' ;
		
		
		//$username 				= 'demo@orbisprotect.com' ;
		//$password  				= 'Pass2121!' ;
		
		$url = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/ListSites";
			/*** To search a particular name*
			$xml_post_string = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
																									xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS"
																									xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		 <soap:Header/>
		 <soap:Body>
				<cls:ListSites>
					 <!--Optional:-->
					 <cls:listSitesRequestKey>
							<cls:ServiceVersion>Version_1_104_1</cls:ServiceVersion>
							<!--Optional:-->
							<cls:UserName>'.$username.'</cls:UserName>
							<!--Optional:-->
							<cls:Password>'.$password .'</cls:Password>
							<!--Optional:-->
							<cls:SiteFilter>
								 <cls:FilterList>
										<!-- Exlude Templates:-->
										<!-- Include Commissioned Only :-->
										<cls:SiteFilterListItem>
											 <cls:FilterAttribute xsi:type="cls:NameSiteFilterAttribute"/>
											 <cls:FilterOperator xsi:type="cls:EqualitySiteFilterOperator"/>
											 <cls:FilterValue xsi:type="cls:SiteFilterComparisonString">
																<cls:Value>NWP HQ External UPS and Airwaves</cls:Value>
											 </cls:FilterValue>
										</cls:SiteFilterListItem>
								 </cls:FilterList>
							</cls:SiteFilter>

					 </cls:listSitesRequestKey>
				</cls:ListSites>
		 </soap:Body>
	</soap:Envelope>';
*/
					$xml_post_string = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
																									xmlns:cls="http://www.monitorsoft.com/SentinelXS/clsSentinelXS"
																									xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		 <soap:Header/>
		 <soap:Body>
				<cls:ListSites>
					 <!--Optional:-->
					 <cls:listSitesRequestKey>
							<cls:ServiceVersion>Version_1_104_1</cls:ServiceVersion>
							<!--Optional:-->
							<cls:UserName>'.$username.'</cls:UserName>
							<!--Optional:-->
							<cls:Password>'.$password .'</cls:Password>
							<cls:SiteFilter>
								 <cls:FilterList>
							 <!-- Include Commissioned Only :-->
							  <cls:SiteFilterListItem>
								 <cls:FilterAttribute xsi:type="cls:CommissionedStateSiteFilterAttribute"/>
								 <cls:FilterOperator xsi:type="cls:EqualitySiteFilterOperator"/>
								 <cls:FilterValue xsi:type="cls:SiteFilterComparisonCommissionState">
										  <cls:Value xsi:type="cls:Commissioned"/>
								 </cls:FilterValue>
							  </cls:SiteFilterListItem>
						   </cls:FilterList>
						    </cls:SiteFilter>
					 </cls:listSitesRequestKey>
				</cls:ListSites>
		 </soap:Body>
	</soap:Envelope>';
				
				
				
				// get curl response
				$curl_send = $this->curl->curl_send($xml_post_string, $url);
				$xmlToArray = $this->curl->xmlToArray($curl_send);
				//~ echo "<pre>";
					//~ print_r(htmlentities($curl_send));
				//~ echo "</pre>";
				debug($xmlToArray, 1) ; 
	
	
	
	}
	
	public function get_user_sentinel() {
		
		$username 				= 'servicesentryengineer1' ;
		
		//$username 				= 'demo@orbisprotect.com' ;

		
		
		try {
			$conexion = new PDO("informix:host=".$this->config->item('pdo_connect')['host'].";service=".$this->config->item('pdo_connect')['service'].";database=".$this->config->item('pdo_connect')['database'].";server=".$this->config->item('pdo_connect')['server'].";protocol=".$this->config->item('pdo_connect')['protocol'].";EnableScrollableCursors=".$this->config->item('pdo_connect')['EnableScrollableCursors'].";client_locale=".$this->config->item('pdo_connect')['client_locale'].";db_locale=".$this->config->item('pdo_connect')['db_locale'] ,$this->config->item('pdo_connect')['db_user'],$this->config->item('pdo_connect')['db_pass']);
		} catch( PDOException $Exception ) {
			header( 'Location: '.base_url().'user/dbError' );
			exit;
		}
		
		$linkAccountId = "50917" ;
		$sql    = 'select * from webusers where name = "'.$username.'" and agctype = 4';
		$sql = "SELECT customer.name, customer.serialno,customer.address_postcode FROM customer, monitoring WHERE customer.linkno IN ( SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND customer.serialno = monitoring.serialno AND monitoring.commstate = 1
				 ORDER BY customer.serialno DESC" ;
		//die($sql);
		$prep   = $conexion->prepare($sql);
		$prep->execute();
		$result = $prep->fetchAll(PDO::FETCH_ASSOC);
	//	$linkaccID = $result[0]['AGCNO'];
	//	$groupSql    = "SELECT  level,* FROM   linkacc  START   WITH linkacc.linkno IN (".$linkaccID.")  CONNECT BY PRIOR linkacc.linkno = linkacc.parent";
			//die($groupSql) ;
		debug($result, 1) ;
		if( !empty($result) ){

			//get first group id under that linkaccount
			$groupSql    = "SELECT  level,* FROM   linkacc  START   WITH linkacc.linkno IN (".$linkaccID.")  CONNECT BY PRIOR linkacc.linkno = linkacc.parent";
			die($groupSql) ;
			$groupPrep   = $conexion->prepare($groupSql);
			$groupPrep->execute();
			$groupResult = $groupPrep->fetchAll(PDO::FETCH_ASSOC);
			debug($groupResult, 1) ;
			$groupID = $groupResult[0]['LINKNO'];
		}
		else{
			$linkaccID= '0';
			$groupID = '0';
		}

		
		
		
	}
	
	public function test() {
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		$serialnumber = "160463" ;
		
		
		$getsitedetail = "http://www.monitorsoft.com/SentinelXS/clsSentinelXS/GetSite";
			$xml_getsitedetail = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
				<SOAP-ENV:Envelope
				 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
				 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
				 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
				xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
				xmlns:xsd="http://www.w3.org/2001/XMLSchema">
				<SOAP-ENV:Body>
					<GetSite xmlns="http://www.monitorsoft.com/SentinelXS/clsSentinelXS">
						<getSiteRequestKey>
							<UserName>'.$username.'</UserName>
							<Password>'.$password .'</Password>
							<SerialNumber>'.$serialnumber.'</SerialNumber>
						</getSiteRequestKey>
					</GetSite>
				</SOAP-ENV:Body>
				</SOAP-ENV:Envelope>';

				$curl_getsitedetail = $this->curl->curl_send($xml_getsitedetail, $getsitedetail);
				$xmlToArray_get_sites = $this->curl->xmlParse($curl_getsitedetail);
				echo $xmlToArray_get_sites['soap:Body']['GetSiteResponse']['GetSiteResult']['SiteInformation']['IsOnTest'];
				debug($xmlToArray_get_sites, 1) ;
		try {
			$conexion = new PDO("informix:host=".$this->config->item('pdo_connect')['host'].";service=".$this->config->item('pdo_connect')['service'].";database=".$this->config->item('pdo_connect')['database'].";server=".$this->config->item('pdo_connect')['server'].";protocol=".$this->config->item('pdo_connect')['protocol'].";EnableScrollableCursors=".$this->config->item('pdo_connect')['EnableScrollableCursors'].";client_locale=".$this->config->item('pdo_connect')['client_locale'].";db_locale=".$this->config->item('pdo_connect')['db_locale'] ,$this->config->item('pdo_connect')['db_user'],$this->config->item('pdo_connect')['db_pass']);
		} catch( PDOException $Exception ) {
			header( 'Location: '.base_url().'user/dbError' );
			exit;
		}

		/* ,(SELECT * 
	 	FROM outsrv
	 	WHERE customer.serialno = outsrv.serialno) */

		$sql    = "select * from outsrv where SERIALNO = '160463' order by LSEQNO DESC";
		
		
		/*$sql = "SELECT customer.name, customer.serialno,customer.address_postcode,outsrv.back_in_service  FROM customer INNER JOIN monitoring ON
customer.serialno = monitoring.serialno  Left JOIN outsrv ON customer.serialno = outsrv.serialno WHERE customer.linkno IN (
SELECT linkno FROM linkacc START WITH linkacc.linkno IN (48613) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) 
ORDER BY customer.serialno DESC" ;*/

$sql = "select
T01.name, 
T01.serialno,
T01.address_postcode, 
T04.netaddr2,
T05.back_in_service,
T05.LSEQNO,
T02.commstate
FROM customer as T01
inner join monitoring as T02 on T01.serialno = T02.serialno
inner join (select serialno,Min(commsno) as commsno2 from systrans group by serialno) as T03 on T01.serialno = T03.serialno
inner join systrans as T04 on T03.serialno = T04.serialno And T03.commsno2 = T04.commsno
left join (select serialno,back_in_service, MAX(Lseqno) as Lseqno from outsrv group by serialno,back_in_service) as T05 on T01.serialno = T05.serialno
WHERE T01.linkno IN (SELECT linkno FROM linkacc START WITH linkacc.linkno IN (48613) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) 
--AND T02.commstate = 1 
--and T04.panelid = 469
ORDER BY T01.serialno DESC" ;


				 
		$prep   = $conexion->prepare($sql);
		$prep->execute();
		$result = $prep->fetchAll(PDO::FETCH_ASSOC);
	
		debug($result, 1) ;
	
	
	}
	
	function haversineGreatCircleDistance()
	{
		
		
	  $latitudeFrom  = "54.6052191" ;
	  $longitudeFrom = "-1.1050448" ;	
	  $latitudeTo    = "54.609024" ;
	  $longitudeTo   = "-1.108499" ;
	  $earthRadius = 6371000;
		
	  // convert from degrees to radians
	  $latFrom = deg2rad($latitudeFrom);
	  $lonFrom = deg2rad($longitudeFrom);
	  $latTo = deg2rad($latitudeTo);
	  $lonTo = deg2rad($longitudeTo);

	  $latDelta = $latTo - $latFrom;
	  $lonDelta = $lonTo - $lonFrom;

	  $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
		cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
	  echo  $angle * $earthRadius;
	}
	
	
	public static function vincentyGreatCircleDistance()
	{
	 	
	  $latitudeFrom  = "30.6587716" ;
	  $longitudeFrom = "76.8352513" ;
	  $latitudeTo    = "54.609024" ;
	  $longitudeTo   = "-1.108499" ;
	  $earthRadius = 6371000;
	 
	  // convert from degrees to radians
	  $latFrom = deg2rad($latitudeFrom);
	  $lonFrom = deg2rad($longitudeFrom);
	  $latTo = deg2rad($latitudeTo);
	  $lonTo = deg2rad($longitudeTo);

	  $lonDelta = $lonTo - $lonFrom;
	  $a = pow(cos($latTo) * sin($lonDelta), 2) +
		pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
	  $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);

	  $angle = atan2(sqrt($a), $b);
	  echo  $angle * $earthRadius;
	}
	
	
	function validateLatLong($lat, $long) {
		return preg_match('/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?),[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/', $lat.','.$long);
	}
	
	
}
