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

class Api extends CI_Controller {

	public $mainUserData ;

	function __construct()
	{
		parent::__construct();
		
		$this->load->library('curl');
		$this->load->helper(['jwt', 'authorization']); 
		$this->load->model('users') ;
		
		$currentMethod  =  $this->router->fetch_method();
		
		if($currentMethod != "login") {
			
			$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') ;

		//$username 				= 'ServiceSentryEngineer' ;
		//$password  				= 'Star@1!' ;
		// list log header identifier 152112
		
		//New credentials for testing
		//~ $username 				= 'servicesentryengineer1' ;
		//~ $password  				= 'Js013579!' ;
		
		$linkAccountNumber		= '12345' ;
		
		
		$user_id 		= "" ;
		$user_jwt_token =  "" ;
		$name			= "" ;
		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) ; 
					
					if ( $insertData && $token) {
						$message  		 = "Valid credentials.";
						$loginStatus	 = "true"	;
						$user_id 		 =  $insertData;
						$user_jwt_token  =  $token;
						$name			 =  "Need to make name dynamic." ;
					} else {
						$message  		 = "Network error.";
						$loginStatus	 = "false"	;
					}
					
				} else {
					$status  		 = "200";
					$message  		 = "No matched record from the XML response.";
					$loginStatus	 = "false"	;	
				}
				
				
			} else {
				echo "No response from the API" ;
				$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]) ;
	}
	
	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') ;
			
			/*
			 *
			 *  search_by:    siteName      sitePostcode      siteTransmitterId     allSites
			 * 
			 */
			 
			 if ($eventType == "allSites") {
				 
				 $sqlNew = "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" ;
				 
				 
			 } elseif($eventType == "siteName" && $eventValue) {
				 
				 $eventValue = trim($eventValue) ;
				 $eventValue = str_replace(' ', '%', $eventValue) ;
				 
				 $sqlNew = "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.name LIKE '%".$eventValue."%' AND customer.serialno = monitoring.serialno AND monitoring.commstate = 1 ORDER BY customer.serialno DESC";
				 
			 } elseif($eventType == "sitePostcode" && $eventValue) {
				 
				 $eventValue = trim($eventValue) ;
				 $eventValue = str_replace(' ', '%', $eventValue) ;
				 
				  $sqlNew = "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.address_postcode LIKE '%".$eventValue."%' AND customer.serialno = monitoring.serialno AND monitoring.commstate = 1 ORDER BY customer.serialno DESC";
				  
				 
			 } elseif($eventType == "siteTransmitterId" && $eventValue) {
				 
				  $eventValue = (int)$eventValue ;
				 
				  $sqlNew = "SELECT customer.name, customer.serialno,customer.address_postcode FROM customer, monitoring, systrans WHERE customer.linkno IN ( SELECT linkno FROM linkacc START WITH linkacc.linkno IN ($linkAccountId) CONNECT BY PRIOR linkacc.linkno = linkacc.parent) AND systrans.panelid = '".$eventValue."' AND customer.serialno = systrans.serialno AND customer.serialno = monitoring.serialno AND monitoring.commstate = 1 ORDER BY customer.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') ;
				
			} 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 {
				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) {
			
			$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 ;
				} 
				
				echo json_encode([ 'status' => 200, 'message' => "Data found.", 'dataStatus' => 'true', 'data' => $resultTotal]) ;
				
			} else {
				$resultTotal = [] ;
				echo json_encode([ 'status' => 200, 'message' => "No data found.", 'dataStatus' => 'false', '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') ;
	
	
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		
		
		if ($serialNumber) {
		
			   $serialNumber = "160463" ;	
			
			   $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>Out of service because of a routine check</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'] ) && empty( $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') ;
	
	
		$username     = "jack.singh@orbisprotect.com" ;
		$password 	  = "Js246800!" ;
		
		
		
		
		
		
		if ($serialNumber) {
			   
			   $serialNumber = "160463" ;
			   
			   $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'] ) && empty( $xmlToArray['TakeItemOffTestResponse']['TakeItemOffTestResult'] ) ) {
					
					echo json_encode([ 'status' => 200, 'message' => "Site armed successfully", 'dataStatus' => 'true']) ;
					
				} elseif ( 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']) ;
					
				} 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') ;
		
		//~ $username     = "jack.singh@orbisprotect.com" ;
		//~ $password 	  = "Js246800!" ;
		
		$serialNumber = $this->input->post('serial_number') ;

		if ($serialNumber) {
			
			    $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."]) ;
		}
	
	
	
	}
	
	
	/***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) ;
	
	
	}
}
