<?php

session_start();
include ("/home/ronnie/ranger/v2/functions.php");

/**
 * API Wrapper for the Ranger Service
 */
class RangerApi {

	/**
	 * $host The API Service URL
	 * @var string
	 */
	#private $host='http://ranger1webapi.azurewebsites.net/api/'; // test
	private $host='http://api.parkshopreg.co.uk/api/'; // live

	/**
	 * $username Account Username
	 * @var string
	 */
	#private $username='Tester'; // test
	private $username='MobileApp'; // live

	/**
	 * $password Account Password
	 * @var string
	 */
	#private $password='T35t3r!.6251N01'; // test
	private $password='M0B1L34PP!.MOBILEAPP'; // live

	/**
	 * $mode LIVE or TEST
	 * @var string
	 */
	#private $mode='TEST';
	private $mode='LIVE';

	/**
	 * $protocol HTTP or HTTPS
	 * @var string
	 */
	private $protocol='HTTP';

	/**
	 * $includeHeaders 0 || 1
	 * @var boolean
	 */
	private $includeHeaders=1;

	/**
	 * Initialise the RangerApi with overriding values.
	 * @param  Object $settings Object containing connection settings
	 * @return $this            Return an instance of this object for chaining purposes
	 */
	public function initialise($settings=null) {
		if (is_object($settings)) {
			if (isset($settings->username)) {
				$this->username=trim($settings->username);
			}
			if (isset($settings->password)) {
				$this->password=trim($settings->password);
			}
			if (isset($settings->mode)) {
				$this->mode=(in_array(trim($settings->mode), array('TEST', 'LIVE')) ? trim($settings->mode) : 'TEST');
			}
			if (isset($settings->protocol)) {
				$this->protocol=(in_array(strtoupper($settings->protocol), array('HTTPS', 'HTTP')) ? strtoupper($settings->protocol) : 'HTTP');
			}
			if (isset($settings->includeHeaders)) {
				$this->includeHeaders=(1 === $this->includeHeaders ? 1 : 0);
			}
		}
		return $this;
	}

	/**
	 * Verify if a concession token is valid.
	 * @param  string $token Concession Token, often a long number
	 * @return object        XML Response, converted into an object.
	 *
	 * <concessioncode>
	 * <sitecode>434</sitecode>
	 * <site>Tesco Bideford</site>
	 * <storeid>9292</storeid>
	 * <transactionnumber>8422</transactionnumber>
	 * <tillnumber>973</tillnumber>
	 * </concessioncode>
	 *
	 */
	public function concessionVerify($token='') {

		$response=new stdClass;

		$response->token	=$token;
		$response->status	=false;
		$response->error	='';
		$response->raw		='';
		$resposne->readable	='';

		$response->sitecode			='';
		$response->site				='';
		$response->storeid			='';
		$response->transactionnumber='';
		$response->tillnumber		='';

		$path								=$this->host.'concession/'.$token;
		$xmlString							=$this->connect($path);
		$_SESSION['data']['concessioncode']	=$token;

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"validatetoken", "function"=>"concessionVerify", "concessioncode"=>$token, "endpoint"=>$path)),
			'response'	=>false
		));

		$response->raw		=$xmlString;
		$response->readable	=htmlentities($xmlString);

		// Formatting Corrections
		$xmlObject=$this->formatXML($xmlString);

		if ($xmlObject && isset($xmlObject->SiteCode)) {
			$response->status				=true;
			$response->sitecode				=(string) $xmlObject->SiteCode;
			$_SESSION['data']['concession']	=$token;
			if (isset($xmlObject->Site)) {
				$response->site=(string) $xmlObject->Site;
			}
			if (isset($xmlObject->StoreID)) {
				$response->storeid=(string) $xmlObject->StoreID;
			}
			if (isset($xmlObject->TransactionNumber)) {
				$response->transactionnumber=(string) $xmlObject->TransactionNumber;
			}
			if (isset($xmlObject->TillNumber)) {
				$response->tillnumber=(string) $xmlObject->TillNumber;
			}
		} else {
			$response->error='could not read response';
		}

		logger::updateLog($logger_uid, json_encode($response));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function saveToken($token='') {
		$_SESSION['data']['concessioncode']=$token;

		$response			=new stdClass;
		$response->status	=true;

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"saveToken", "function"=>"saveToken", "concessioncode"=>$token)),
			'response'	=>false
		));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function setParked($parked=0) {
		$_SESSION['data']['parked']=(int) $parked;

		$response			=new stdClass;
		$response->status	=true;

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"setParked", "function"=>"setParked", "parked"=>(int) $parked)),
			'response'	=>false
		));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function clearVehicle() {
		if (isset($_SESSION['data']['selectedVehicle'])) {
			unset($_SESSION['data']['selectedVehicle']);
		}
		$response			=new stdClass;
		$response->status	=true;

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"clearVehicle", "function"=>"clearVehicle")),
			'response'	=>false
		));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function setVRM($vrm=false, $full_vrm=false) {
		$response			=new stdClass;
		$response->status	=false;
		if (false !== trim($vrm)) {
			$_SESSION['data']['vrm']		=strtoupper($vrm);
			$_SESSION['data']['full_vrm']	=(int) ($full_vrm);
			$response->status				=true;

			$logger_uid=logger::saveLog(array(
				'user_uid'	=>(int) $_SESSION['user_loggedin'],
				'session'	=>json_encode($_SESSION),
				'request'	=>json_encode(array("action"=>"setVRM", "function"=>"setVRM", "vrm"=>strtoupper($vrm))),
				'response'	=>false
			));
			logger::updateSessionData($logger_uid, json_encode($_SESSION));
		}
		return $response;
	}

	public function concessionLuhnVerify($token='') {

		$response=new stdClass;

		$response->token	=$token;
		$response->status	=false;
		$response->error	='';
		$response->raw		='';
		$resposne->readable	='';

		$path		=$this->host.'concession/'.$token;
		$xmlString	=$this->connect($path);

		#$_SESSION['data']['concessioncode']	=$token;

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"validatetoken", "function"=>"concessionLuhnVerify", "concessioncode"=>$token, "endpoint"=>$path)),
			'response'	=>false
		));

		$response->raw		=$xmlString;
		$response->readable	=htmlentities($xmlString);

		// Formatting Corrections
		$xmlObject=$this->formatXML($xmlString);

		if ($xmlObject && isset($xmlObject->SiteCode)) {
			$response->status				=true;
			$response->sitecode				=(string) $xmlObject->SiteCode;
			$_SESSION['data']['concession']	=$token;
			if (isset($xmlObject->Site)) {
				$response->site=(string) $xmlObject->Site;
			}
			if (isset($xmlObject->StoreID)) {
				$response->storeid=(string) $xmlObject->StoreID;
			}
			if (isset($xmlObject->TransactionNumber)) {
				$response->transactionnumber=(string) $xmlObject->TransactionNumber;
			}
			if (isset($xmlObject->TillNumber)) {
				$response->tillnumber=(string) $xmlObject->TillNumber;
			}
		} else {
			$response->error='could not read response';
		}

		logger::updateLog($logger_uid, json_encode($response));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	/**
	 * Verify if a vehicle registration number is valid.
	 * @param  string $token VRM Token, 3 chars or more
	 * @return object        XML Response, converted into an object.
	 *
	 * <concessioncode>
	 * <sitecode>434</sitecode>
	 * <site>Tesco Bideford</site>
	 * <storeid>9292</storeid>
	 * <transactionnumber>8422</transactionnumber>
	 * <tillnumber>973</tillnumber>
	 * </concessioncode>
	 *
	 */
	public function vrmVerify($vrm='', $site_code=false) {
		$response			=new stdClass;
		$vrm				=strtoupper(trim($vrm));
		$response->vrm		=$vrm;
		$response->status	=false;
		$response->error	='';

		if ('' !== $site_code) {
			$arrStore	=stores::getBySiteCode($site_code);
			$path		=$this->host.'capture/'.$vrm.'/'.$arrStore['tesco_site_code'];
		} else {
			$path=$this->host.'capture/'.$vrm;
		}
		$xmlString=$this->connect($path);

		if (strlen($vrm) == 3) {
			$_SESSION['data']['vrm_3']=$vrm;
		} else {
			$_SESSION['data']['vrm']=$vrm;
		}

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"reg", "function"=>"vrmVerify", "vrm"=>$vrm, "site_code"=>$site_code, "endpoint"=>$path)),
			'response'	=>false
		));

		$response->raw			=$xmlString;
		$response->readable		=htmlentities($xmlString);
		$response->matchesArray	=array();
		$response->matchesCount	=false;

		// Formatting Corrections
		$xmlObject=(array) $this->formatXML($xmlString);
		#echo "<pre>";print_r($xmlObject);exit;
		if ($xmlObject && isset($xmlObject['VehicleCapture'])) {
			$response->status=true;
			if (isset($xmlObject['VehicleCapture']->SiteCode)) {
				$matches[]=$xmlObject['VehicleCapture'];
			} else {
				$matches=$xmlObject['VehicleCapture'];
			}
			/*
			 * get previous validated vehicle from cookie
			 * if that vehicle in this list (comparing by image) remove
			 */
			$arrValidaedVehicles		=false;
			$arrValidaedVehiclesVRM[]	=array();
			$arrValidaedVehiclesImage	=array();

			$ip			=$_SERVER['REMOTE_ADDR'];
			/* $arrUsers	=user_log::getByIPandCockie($ip, $_COOKIE['logged']);
			  if (count($arrUsers) > 0 && false !== $arrUsers) {
			  $uids=array();
			  foreach ($arrUsers as $user) {
			  $uids[]=$user['uid'];
			  } */
			$arrLogger	=logger::getallCompletedData();
			if (false !== $arrLogger) {
				foreach ($arrLogger as $logger) {
					$arrSession	=json_decode($logger['session'], true);
					$arrRequest	=json_decode($logger['request'], true);
					$arrResponse=json_decode(($logger['response']), true);
					if ($arrResponse['status'] == true && isset($arrSession['data']['selectedVehicle'])) {
						$arrValidaedVehicles		=$arrSession['data']['selectedVehicle'];
						$arrValidaedVehiclesImage[]	=trim($arrValidaedVehicles['imageuri']);
					}
				}
			}
			//}

			/*
			 * check if we have storecode
			 * if yes than get all cars having storecode
			 * else return all
			 */
			$i=0;
			if ('' !== $site_code) {
				if (isset($_SESSION['data']['store'])) {
					if ($site_code !== trim($_SESSION['data']['store']['site_code'])) {
						$this->chooseStore($site_code);
					}
				} else {
					$this->chooseStore($site_code);
				}

				foreach ($matches as $index=> $match) {
					$sitecode	=(string) $match->SiteCode[0];
					$imageuri	=(string) $match->ImageURI[0];
					#echo "<pre>";print_r($arrValidaedVehiclesImage);exit;
					if (!in_array($imageuri, $arrValidaedVehiclesImage)) {
						if ($site_code == $sitecode) {
							if (isset($match->SiteCode)) {
								$response->matchesArray[$i]['sitecode']=(string) $match->SiteCode[0];
							}
							if (isset($match->Site)) {
								$response->matchesArray[$i]['site']=(string) $match->Site[0];
							}
							if (isset($match->Direction)) {
								$response->matchesArray[$i]['direction']=(string) $match->Direction[0];
							}
							if (isset($match->Lane)) {
								$response->matchesArray[$i]['lane']=(string) $match->Lane[0];
							}
							if (isset($match->Confidence)) {
								$response->matchesArray[$i]['confidence']=(string) $match->Confidence[0];
							}
							if (isset($match->VehicleRegMark)) {
								$response->matchesArray[$i]['vehicleregmark']=(string) $match->VehicleRegMark[0];
							}
							if (isset($match->CaptureDateTime)) {
								$response->matchesArray[$i]['capturedatetime']=(string) $match->CaptureDateTime[0];
							}
							if (isset($match->ImageURI)) {
								$response->matchesArray[$i]['imageuri']=(string) $match->ImageURI[0];
							}
							$i++;
						}
					}
					$response->matchesCount=(int) count($response->matchesArray);
				}
			} else {
				if (isset($_SESSION['data']['store'])) {
					unset($_SESSION['data']['store']['site_code']);
				}
				foreach ($matches as $index=> $match) {
					$imageuri=(string) $match->ImageURI[0];
					if (!in_array($imageuri, $arrValidaedVehiclesImage)) {
						if (isset($match->SiteCode)) {
							$response->matchesArray[$i]['sitecode']=(string) $match->SiteCode[0];
						}
						if (isset($match->Site)) {
							$response->matchesArray[$i]['site']=(string) $match->Site[0];
						}
						if (isset($match->Direction)) {
							$response->matchesArray[$i]['direction']=(string) $match->Direction[0];
						}
						if (isset($match->Lane)) {
							$response->matchesArray[$i]['lane']=(string) $match->Lane[0];
						}
						if (isset($match->Confidence)) {
							$response->matchesArray[$i]['confidence']=(string) $match->Confidence[0];
						}
						if (isset($match->VehicleRegMark)) {
							$response->matchesArray[$i]['vehicleregmark']=(string) $match->VehicleRegMark[0];
						}
						if (isset($match->CaptureDateTime)) {
							$response->matchesArray[$i]['capturedatetime']=(string) $match->CaptureDateTime[0];
						}
						if (isset($match->ImageURI)) {
							$response->matchesArray[$i]['imageuri']=(string) $match->ImageURI[0];
						}
						$i++;
					}
				}
				$response->matchesCount=(int) count($response->matchesArray);
			}

			$_SESSION['data']['vehicles']['matchesCount']	=$response->matchesCount;
			$_SESSION['data']['vehicles']['matchesArray']	=$response->matchesArray;
		} else {
			$response->error='could not read response';
		}

		logger::updateLog($logger_uid, json_encode($response));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function storeVerify() {

		$response=new stdClass;

		$response->status	=false;
		$response->error	='';

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"store", "function"=>"storeVerify")),
			'response'	=>false
		));

		$arrStores=stores::getAll();
		if (false !== $arrStores) {
			$response->status		=true;
			$response->matchesCount	=(string) count($arrStores);
			$response->matchesArray	=(object) $arrStores;
		} else {
			$response->error='There is no stores found!';
		}

		logger::updateLog($logger_uid, json_encode($arrStores));
		return $response;
	}

	public function chooseCar($regNumber='') {

		$response=new stdClass;

		$response->status	=false;
		$response->error	='';

		$_SESSION['data']['vrm']=strtoupper($regNumber);

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"chooseCar", "function"=>"chooseCar", 'vrm'=>strtoupper($regNumber))),
			'response'	=>false
		));

		if (isset($_SESSION['data']['vehicles'])) {
			/*
			 * check vehicle contain storecode
			 */
			$arrVehicle	=false;
			$arrStore	=false;
			foreach ($_SESSION['data']['vehicles']['matchesArray'] as $vehicle) {
				$vehicle_storcode=$vehicle['sitecode'];
				if (isset($_SESSION['data']['store']['site_code'])) {
					$storcode=$_SESSION['data']['store']['site_code'];
					if (($storcode == $vehicle_storcode) && ($regNumber == $vehicle['vehicleregmark'])) {
						$arrVehicle=$vehicle;
					}
				} else if (($regNumber == $vehicle['vehicleregmark'])) {
					$arrVehicle=$vehicle;
				}
			}

			if ($arrVehicle) {
				if (!isset($_SESSION['data']['store']['site_code'])) {
					$arrStore=stores::getBySiteCode($arrVehicle['sitecode']);

					$_SESSION['data']['store']=$arrStore;
				} else {
					$arrStore=$_SESSION['data']['store'];
				}
			} else {
				$response->error='Invalid vehicle found!';
			}
		} else {
			$response->error='Invalid vehicle found!';
		}

		if ('' == $response->error) {
			$now						=date("Y-m-d H:i:s");
			$vehicle_arrived			=$arrVehicle['capturedatetime'];
			$strtotime_vehicle_arrived	=strtotime(date("H:i:s", strtotime($vehicle_arrived)));
			$vehicle_left				=$now;
			$strtotime_vehicle_left		=strtotime(date("H:i:s", strtotime($vehicle_left)));
			$day_of_week				=date('l', strtotime($now));

			/* echo "<pre>";
			  print_r($vehicle);
			  echo "<br/>vehicle_parking_start => $strtotime_vehicle_arrived =>  ".date("h:i:s A", ($strtotime_vehicle_arrived));
			  echo "<br/>vehicle_parking_end =>  $strtotime_vehicle_left =>  ".date("h:i:s A", ($strtotime_vehicle_left)); */

			$arrValidTime=false;
			foreach ($arrStore['timing'] as $timing) {
				if ($day_of_week == $timing['day_of_week']) {
					$arrValidTime=$timing;
				}
			}
			if (false !== $arrValidTime) {
				$response->status		=true;
				$response->vehicle		=$arrVehicle;
				$response->overstay		=false;
				$response->offence		=false;
				$response->entry_time	=(date("H:i", strtotime($vehicle_arrived)));
				$response->entry_date	=(date("j.n.y", strtotime($vehicle_arrived)));
				$response->left_time	=(date("H:i", strtotime($vehicle_left)));
				$response->left_date	=(date("j.n.y", strtotime($vehicle_left)));

				$_SESSION['data']['selectedVehicle']				=$arrVehicle;
				$_SESSION['data']['selectedVehicle']['overstay']	=false;
				$_SESSION['data']['selectedVehicle']['offence']		=false;
				$_SESSION['data']['selectedVehicle']['entry_date']	=$response->entry_time;
				$_SESSION['data']['selectedVehicle']['entry_time']	=$response->entry_date;
				$_SESSION['data']['selectedVehicle']['left_time']	=$response->left_time;
				$_SESSION['data']['selectedVehicle']['left_date']	=$response->left_date;

				/* echo "<pre>";print_r($arrValidTime); */

				$offence_start_time		=$arrValidTime['offence_start_time'];
				$offence_end_time		=$arrValidTime['offence_end_time'];
				$period_allowed			=$arrValidTime['period_allowed'];
				$period_grace			=$arrValidTime['period_grace'];
				$out_of_hours_offence	=$arrValidTime['out_of_hours_offence'];

				$_SESSION['data']['validTime']=$arrValidTime;

				$strtotime_offence_start_time	=strtotime(date("H:i:s", strtotime($offence_start_time)));
				$strtotime_offence_end_time		=strtotime(date("H:i:s", strtotime($offence_end_time)));
				$strtotime_period_allowed		=strtotime(date("H:i:s", strtotime($period_allowed)));
				$strtotime_period_grace			=strtotime(date("H:i:s", strtotime($period_grace)));

				/*
				 * Rule 1- offence=true and if they park before the start and after the end of the allowed period - then it is an offence
				 */
				if ($out_of_hours_offence == 'True' && (($strtotime_vehicle_arrived < $strtotime_offence_start_time) || ($strtotime_vehicle_arrived > $strtotime_offence_end_time))) {
					$response->offence	=true;
					$response->overstay	=true;

					$_SESSION['data']['selectedVehicle']['overstay']=true;
					$_SESSION['data']['selectedVehicle']['offence']	=true;
				} else {
					$balance_time_sec										=$strtotime_offence_end_time - $strtotime_vehicle_arrived;
					$_SESSION['data']['selectedVehicle']['balance_time_sec']=$balance_time_sec;

					$balance_time			=$this->getTimefromSeconds($balance_time_sec);
					$response->balance_time	=trim((($balance_time[0] > 0) ? $balance_time[0]." Hours " : false).(($balance_time[1] > 0) ? $balance_time[1]." Min " : false).(($balance_time[2] > 0) ? $balance_time[2]." Sec " : false));

					$_SESSION['data']['selectedVehicle']['balance_time']=$response->balance_time;
				}

				$seconds_stayed		=$strtotime_vehicle_left - $strtotime_vehicle_arrived;
				$permitted_seconds	=self::convertToSeconds($period_allowed, $period_grace);

				$_SESSION['data']['selectedVehicle']['seconds_stayed']		=$seconds_stayed;
				$_SESSION['data']['selectedVehicle']['permitted_seconds']	=$permitted_seconds;

				$_SESSION['data']['validTime']['permitted_seconds']=$permitted_seconds;

				$validated_stay				=$this->getTimefromSeconds($seconds_stayed);
				$response->validated_stay	=trim((($validated_stay[0] > 0) ? $validated_stay[0]." Hours " : false).(($validated_stay[1] > 0) ? $validated_stay[1]." Min " : false).(($validated_stay[2] > 0) ? $validated_stay[2]." Sec " : false));

				if (!$response->overstay) {

					/*
					 * Rule 2- check if vehicle overstay by given time
					 */
					#echo $seconds_stayed." > ".$permitted_seconds;	exit;
					if ($seconds_stayed > $permitted_seconds) {
						$response->overstay								=true;
						$_SESSION['data']['selectedVehicle']['overstay']=true;
					} else {
						$balance_time_sec										=$permitted_seconds - $seconds_stayed;
						$_SESSION['data']['selectedVehicle']['balance_time_sec']=$balance_time_sec;

						$balance_time										=$this->getTimefromSeconds($balance_time_sec);
						$response->balance_time								=trim((($balance_time[0] > 0) ? $balance_time[0]." Hours " : false).(($balance_time[1] > 0) ? $balance_time[1]." Min " : false).(($balance_time[2] > 0) ? $balance_time[2]." Sec " : false));
						$_SESSION['data']['selectedVehicle']['balance_time']=$response->balance_time;
					}
				}
			} else {
				$response->error='Invalid Timeslote for today!';
			}
		}
		logger::updateLog($logger_uid, json_encode($response));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function acceptCar() {
		$response=new stdClass;

		$response->status	=false;
		$response->error	='';

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"accepted", "function"=>"acceptCar")),
			'response'	=>false
		));

		if (!isset($_SESSION['data']['concession']) || !isset($_SESSION['data']['vrm'])) {
			$response->error='Invalid concessioncode or vrm found!';
		} else {
			$concessioncode	=$_SESSION['data']['concession'];
			$vrm			=$_SESSION['data']['vrm'];

			$path=$this->host.'concession/'.$concessioncode.'/vrm/'.$vrm.'';
			#echo $path;
			logger::updateRequest($logger_uid, json_encode(array("action"=>"accepted", "function"=>"acceptCar", "endpoint"=>$path)));

			$xmlString				=$this->connect($path, 'post');
			$response->concession	=$concessioncode;
			$response->vrm			=$vrm;
			$response->raw			=$xmlString;
			$response->readable		=htmlentities($xmlString);

			// Formatting Corrections
			$xmlObject=$this->formatXML($xmlString);

			if ($xmlObject) {
				$response->status=true;
			}
		}
		logger::updateLog($logger_uid, json_encode($response));
		return $response;
	}

	public function chooseStore($sitecode='') {

		$response=new stdClass;

		$response->status	=false;
		$response->error	='';

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"chooseStore", "function"=>"chooseStore", "sitecode"=>$sitecode)),
			'response'	=>false
		));

		$arrStore=stores::getBySiteCode($sitecode);
		if (false !== $arrStore) {
			$response->status=true;


			/*
			 * check reg token remembering
			 */
			/*
			 * check user having old session/cockies that having that contain registration number but not completed staps
			 * get request having action reg and with response true
			 * also check requst accepted not completed */

			$response->remembered		=false;
			$response->remembered_status=false;

			#$arrRemembered=$this->rememberedUser($_SESSION['user_loggedin'], $arrStore['site_code']);
			$arrRemembered['remembered']=false;
			if (false !== $arrRemembered['remembered']) {
				$vrm=((isset($_SESSION['data']['vrm'])) ? $_SESSION['data']['vrm'] : $_SESSION['data']['vrm_3']);

				$response->remembered		=$arrRemembered['remembered'];
				$response->validated		=$arrRemembered['validated'];
				$response->remembered_status=$arrRemembered['status'];
				$response->vrm				=$vrm;
				$response->vehicle			=$arrRemembered['arrVehicle'];
			}
			$_SESSION['data']['store']=$arrStore;
		} else {
			$response->error='There is no store found!';
		}
		logger::updateLog($logger_uid, json_encode($response));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function validateLuhnToken($sitecode='') {

		$response=new stdClass;

		$response->status	=false;
		$response->error	='';

		$arrStore=stores::getBySiteCode($sitecode);
		#echo "<pre>";print_r($arrStore);exit;
		if (!isset($_SESSION['data']['concessioncode'])) {
			$response->error='concession code missing!';
		} else if (false !== $arrStore) {
			$response->status			=true;
			$_SESSION['data']['store']	=$arrStore;

			$tesco_site_code=$arrStore['tesco_site_code'];
			#echo "tesco_site_code => ".$tesco_site_code."<br/>";
			$concession		=$_SESSION['data']['concessioncode'];
			#echo "concession => ".$concession."<br/>";
			$luhmstring		=$tesco_site_code.$concession;
			#echo "luhmstring => ".$luhmstring."<br/>";
			$luhn			=$this->Luhn($luhmstring);
			#echo "Luhn($sitecode$concession) => $luhn <br/>";

			$newConcessioCode=$tesco_site_code.$concession.$luhn;
			#echo "newConcessioCode => $newConcessioCode <br/>";

			$logger_uid=logger::saveLog(array(
				'user_uid'	=>(int) $_SESSION['user_loggedin'],
				'session'	=>json_encode($_SESSION),
				'request'	=>json_encode(array("action"=>"chooseStore", "function"=>"validateLuhnToken", "sitecode"=>$sitecode, "tesco_site_code"=>$tesco_site_code, "concessioncode", "new_concessiocode"=>$newConcessioCode)),
				'response'	=>false
			));

			$response=$this->concessionLuhnVerify($newConcessioCode);

			$_SESSION['data']['old_concessioncode']	=$concession;
			$response->new_concessiocode			=$newConcessioCode;


			$_SESSION['data']['store']=$arrStore;

			$day_of_week	=date('l', strtotime($now));
			$arrValidTime	=false;
			foreach ($arrStore['timing'] as $timing) {
				if ($day_of_week == $timing['day_of_week']) {
					$arrValidTime=$timing;
				}
			}
			$_SESSION['data']['validTime']	=$arrValidTime;
			$response->valid_time			=$arrValidTime;

			$offence_start_time		=$arrValidTime['offence_start_time'];
			$offence_end_time		=$arrValidTime['offence_end_time'];
			$period_allowed			=$arrValidTime['period_allowed'];
			$period_grace			=$arrValidTime['period_grace'];
			$out_of_hours_offence	=$arrValidTime['out_of_hours_offence'];

			$permitted_seconds=self::convertToSeconds($period_allowed, $period_grace);

			$_SESSION['data']['validTime']['permitted_seconds']=$permitted_seconds;

			$max_stay_sec=$this->getTimefromSeconds($permitted_seconds);

			$max_stay=trim((($max_stay_sec[0] > 0) ? $max_stay_sec[0]." Hours " : false).(($max_stay_sec[1] > 0) ? $max_stay_sec[1]." Min " : false).(($max_stay_sec[2] > 0) ? $max_stay_sec[2]." Sec " : ''));

			$_SESSION['data']['validTime']['max_stay']	=$max_stay;
			$response->max_stay							=$max_stay;
		} else {
			$response->error='There is no store found!';
		}
		logger::updateLog($logger_uid, json_encode($response));
		logger::updateSessionData($logger_uid, json_encode($_SESSION));
		return $response;
	}

	public function getRemembered() {

		$response=new stdClass;

		$response->remembered	=false;
		$response->status		=false;
		$response->error		='';

		$logger_uid=logger::saveLog(array(
			'user_uid'	=>(int) $_SESSION['user_loggedin'],
			'session'	=>json_encode($_SESSION),
			'request'	=>json_encode(array("action"=>"getRemembered", "function"=>"getRemembered")),
			'response'	=>false
		));

		/*
		 * check user having old session/cockies that having that contain registration number but not completed staps
		 * get request having action reg and with response true
		 * also check requst accepted not completed
		 */
		$arrRemembered=$this->rememberedUser($_SESSION['user_loggedin']);
		if (false !== $arrRemembered['remembered']) {
			$vrm=((isset($_SESSION['data']['vrm'])) ? $_SESSION['data']['vrm'] : $_SESSION['data']['vrm_3']);

			$response->remembered	=$arrRemembered['remembered'];
			$response->validated	=$arrRemembered['validated'];
			$response->status		=$arrRemembered['status'];
			$response->vrm			=$vrm;
			$response->vehicle		=$arrRemembered['arrVehicle'];
		}

		logger::updateLog($logger_uid, json_encode($response));
		return $response;
	}

	public function concessionVerifyTest($token='') {
		return $this->concessionVerify($token);
	}

	public function vrmVerifyTest($vrm, $site_code=false) {
		return $this->vrmVerify($vrm, $site_code);
	}

	public function storeVerifyTest() {
		return $this->storeVerify('EJ1');
	}

	public function chooseCarTest($regNumber=false) {
		return $this->chooseCar($regNumber);
	}

	public function chooseStoreTest($sitecode='') {
		return $this->chooseStore($sitecode);
	}

	public function connect($endpoint='', $method='') {
		$response=false;

		if (0 < strlen($endpoint)) {

			$req=curl_init($endpoint);
			curl_setopt($req, CURLOPT_TIMEOUT, 30);
			curl_setopt($req, CURLOPT_RETURNTRANSFER, TRUE);
			if ($method == 'post') {
				$header=array(
					'Content-Type:application/xml',
					'Authorization: Basic '.base64_encode($this->username.":".$this->password),
					'Content-Length: 0'
				);
				curl_setopt($req, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)");
				curl_setopt($req, CURLOPT_POST, 1);
			} else {
				$header=array(
					'Content-Type:application/xml',
					'Authorization: Basic '.base64_encode($this->username.":".$this->password)
				);
				curl_setopt($req, CURLOPT_HTTPGET, 1);
			}
			curl_setopt($req, CURLOPT_HTTPHEADER, $header);
			curl_setopt($req, CURLOPT_HEADER, $this->includeHeaders);

			$response	=curl_exec($req);
			/* remove header from curl response */
			#if ($_SERVER['REMOTE_ADDR'] == "43.250.166.206") {
			$header_size=curl_getinfo($req, CURLINFO_HEADER_SIZE);
			$header		=substr($response, 0, $header_size);
			$response	=trim(substr($response, $header_size));
			#}
			curl_close($req);
		}
		return $response;
	}

	public function convertToSeconds($time1=false, $time2=false) {
		#echo $time1."<br/>";echo $time2."<br/>";
		list($hours1, $minutes1, $seconds1)=explode(':', $time1);
		list($hours2, $minutes2, $seconds2)=explode(':', $time2);

		$permitted_seconds=(3600 * ((int) $hours1 + (int) $hours2) + 60 * ((int) $minutes1 + (int) $minutes2) + $seconds1 + $seconds2);
		return $permitted_seconds;
	}

	public function getTimefromSeconds($seconds=false) {
		$hrs=false;
		$min=false;
		$sec=false;
		if (false !== $seconds) {
			$hrs=floor($seconds / 3600);
			$min=floor(($seconds / 60) % 60);
			$sec=$seconds % 60;
		}
		return array($hrs, $min, $sec);
	}

	public function rememberUserByRegNumber($user_uid=false) {
		$response=array("activetab"=>"ValidateParking", "arrVehicle"=>array());
		if (false !== $user_uid) {
			$ip			=$_SERVER['REMOTE_ADDR'];
			$arrUsers	=user_log::getByIPandCockie($ip, $_COOKIE['logged']);

			if (count($arrUsers) > 0 && false !== $arrUsers) {
				$uids=array();
				foreach ($arrUsers as $user) {
					$uids[]=$user['uid'];
				}
				$arrLogger=logger::getLastActiveUser($uids);
				if (false !== $arrLogger) {
					$arrSession	=json_decode($arrLogger['session'], true);
					$arrRequest	=json_decode($arrLogger['request'], true);
					$arrResponse=json_decode(($arrLogger['response']), true);
					/* echo "<pre>";
					  print_r($arrLogger);
					  echo "<pre>";
					  print_r($arrResponse);
					  exit; */
					if ($arrResponse['status'] == true && $arrResponse['matchesCount'] > 0) {
						$_SESSION['data']=$arrSession['data'];

						$response['activetab']	="Vehicle";
						$arrVehicles			=$arrResponse['matchesArray'];
						if (count($arrVehicles) > 0) {
							$index=array_rand($arrVehicles);

							$response['arrVehicle']			=$arrVehicles[$index];
							$response['arrVehicle']['index']=$index;
						}
					}
				}
			}
		}
		return $response;
	}

	public function rememberedUser($user_uid=false, $site_code=false) {
		$response=array("status"=>false, "remembered"=>false, "validated"=>false, "arrVehicle"=>array());
		if (false !== $user_uid) {
			$ip			=$_SERVER['REMOTE_ADDR'];
			$arrUsers	=user_log::getByIPandCockie($ip, $_COOKIE['logged']);

			if (count($arrUsers) > 0 && false !== $arrUsers) {
				$uids=array();
				foreach ($arrUsers as $user) {
					$uids[]=$user['uid'];
				}
				$arrLogger=logger::getLastCompletedUser($uids);
				#echo "<pre>";print_r($arrLogger);exit;
				if (false !== $arrLogger) {
					$arrSession		=json_decode($arrLogger['session'], true);
					$arrRequest		=json_decode($arrLogger['request'], true);
					$arrResponse	=json_decode(($arrLogger['response']), true);
					/* echo "<pre>";
					  print_r($arrSession);
					  exit;
					  echo "<pre>";
					  print_r($arrResponse);
					  exit; */
					//$_SESSION['data']['selectedVehicle']
					$tmpOldSession	=$_SESSION;
					if ($arrResponse['status'] == true && isset($arrSession['data']['selectedVehicle'])) {
						$response['remembered']				=true;
						$_SESSION['data']					=$arrSession['data'];
						$_SESSION['token']					=$tmpOldSession['token'];
						$_SESSION['data']['concessioncode']	=$tmpOldSession['data']['concessioncode'];
						$_SESSION['data']['concession']		=$tmpOldSession['data']['concession'];

						$arrVehicles=$arrSession['data']['selectedVehicle'];
						if (count($arrVehicles) > 0) {
							$vehicleRegNumber	=trim($arrVehicles['vehicleregmark']);
							$vehicleimage		=trim($arrVehicles['imageuri']);
							if ('' !== $vehicleRegNumber) {
								$path		=$this->host.'capture/'.$vehicleRegNumber;
								$xmlString	=$this->connect($path);

								$logger_uid=logger::saveLog(array(
									'user_uid'	=>(int) $_SESSION['user_loggedin'],
									'session'	=>json_encode($_SESSION),
									'request'	=>json_encode(array("action"=>"captureVehicle", "function"=>"rememberedUser", "endpoint"=>$path)),
									'response'	=>false
								));

								$xmResponse				=new stdClass();
								$xmResponse->status		=false;
								$xmResponse->error		='';
								$xmResponse->vrm		=$vehicleRegNumber;
								$xmResponse->raw		=$xmlString;
								$xmResponse->readable	=htmlentities($xmlString);

								// Formatting Corrections
								$xmlObject=$this->formatXML($xmlString);


								if ($xmlObject && isset($xmlObject->SearchResultCount)) {
									if ((int) $xmlObject->SearchResultCount > 0) {

										$match		=$xmlObject->VehicleCapture;
										$sitecode	=false;
										$imageuri	=false;
										if (isset($match->SiteCode)) {
											$sitecode=(string) $match->SiteCode[0];
										}
										if (isset($match->ImageURI)) {
											$imageuri=(string) $match->ImageURI[0];
										}

										$valid=true;
										/* check is vehicle updated with new captured image? if no then failed as already validated this car today */
										if ($vehicleimage == $imageuri) {
											$valid					=false;
											$xmResponse->error		='Vehicle have been already validated previously and not updated new capture image since validated!';
											$response['validated']	=$vehicleRegNumber;
										}
										/* check store is same as selected now? */
										if (false !== $site_code) {
											if ($site_code !== $sitecode) {
												$valid				=false;
												$xmResponse->error	='Site code not match with validated vehicle';
											}
										}


										if ($valid) {
											$_SESSION['data']['vrm']=$vehicleRegNumber;
											$response['status']		=true;

											$response['arrVehicle']['sitecode']=$sitecode;
											if (isset($match->Site)) {
												$response['arrVehicle']['site']=(string) $match->Site[0];
											}
											if (isset($match->Direction)) {
												$response['arrVehicle']['direction']=(string) $match->Direction[0];
											}
											if (isset($match->Lane)) {
												$response['arrVehicle']['lane']=(string) $match->Lane[0];
											}
											if (isset($match->Confidence)) {
												$response['arrVehicle']['confidence']=(string) $match->Confidence[0];
											}
											if (isset($match->VehicleRegMark)) {
												$response['arrVehicle']['vehicleregmark']=(string) $match->VehicleRegMark[0];
											}
											if (isset($match->CaptureDateTime)) {
												$response['arrVehicle']['capturedatetime']=(string) $match->CaptureDateTime[0];
											}
											if (isset($match->ImageURI)) {
												$response['arrVehicle']['imageuri']=$imageuri;
											}
											$xmResponse['arrVehicle']=$response['arrVehicle'];
										}
									}
								}
							}
						}
						logger::updateLog($logger_uid, json_encode($xmResponse));
					}
				}
			}
		}

		return $response;
	}

	/*
	 * Generating Luhn Checksums
	 */

	public function Luhn($number=0) {

		$stack	=0;
		$number	=str_split(strrev($number));


		foreach ($number as $key=> $value) {
			if ($key % 2 == 0) {
				$value=array_sum(str_split($value * 2));
			}
			$stack += $value;
		}
		$stack %= 10;

		if ($stack != 0) {
			$stack -= 10;
			$stack=abs($stack);
		}


		#$number	=implode('', array_reverse($number));
		#$number	=$number.strval($stack);

		return $stack;
	}

	public static function createPaginationUrl($page=1, $total_pages=false, $url=false) {
		$mainUrl=rtrim($url, "/")."/?page_number=";

		$page		=($total_pages > 0) ? $page : 0;
		$prevpage	=$pre		=($page > 1) ? $page - 1 : $page;
		//$prevpage = $page;
		$nextpage	=$next		=$page + 1;
		$prevclass	="c-Btn-Prev";
		$nextclass	="c-Btn-Next";

		$prevpage=$mainUrl."".$prevpage;

		if ($page == 1) {
			$prevpage	="#";
			$prevclass	="disabled";
		}

		if ($next > $total_pages) {
			$nextpage	="#";
			$nextclass	="disabled";
		} else {
			$nextpage=$mainUrl."".$nextpage;
		}

		$pagination="";
		if (false === $total_pages) {
			$total_pages=0;
		}
		$page_index=0;

		$i	=0;
		$j	=5;
		while (1) {
			if ($page_index == $total_pages) {
				break;
			}

			if (($page_index >= $page - 1 && $i < 5) || ($page_index >= $page - $j && $j > 0)) {
				/* if ($params) { */
				$pageurl	=$mainUrl.(1 + $page_index);
				/* } else {
				  $pageurl = "#";
				  } */
				$page_number=(1 + $page_index);

				$pagination .= '<li><a href="'.$pageurl.'" data-page="'.$page_number.'" class="'.((($page - 1) == $page_index) ? "active" : "").'">'.$page_number.'</a></li>';
				if ($page_index >= $page - 1) {
					$i++;
				}
				$j--;
			}

			++$page_index;
		}

		$tplPagination='<li class="prev '.$prevclass.'"><a href="'.$prevpage.'" class="" data-page="'.$pre.'">&laquo;</a></li>';
		$tplPagination .= $pagination;
		$tplPagination .= '<li class="next '.$nextclass.'"><a href="'.$nextpage.'" class="" data-page="'.$next.'">&raquo;</a></li>';
		$tplPagination .= '<li class="c-Pagination-LastStats">Showing '.$page.' of '.$page_index.' PAGES</b></li>';

		return $tplPagination;
	}

	public function formatXML($xmlString='') {
		$xmlString	=str_replace('<!--?xml version="1.0" encoding="utf-16"?-->', '', $xmlString);
		$xmlString	=str_replace('<?xml version="1.0" encoding="utf-16"?>', '', $xmlString);

		// There may be other issues with the response, so let's handle warnings
		set_error_handler(function($errno=false, $errstr='') {
			$response->error=array($errno, $errstr);
		}, E_WARNING);
		// Try to parse response as xml
		$xmlObject=simplexml_load_string($xmlString);

		// Restore error handler
		restore_error_handler();
		return $xmlObject;
	}

}

$ranger		=new RangerApi();
$xmlString	=$ranger->connect('http://ranger1webapi.azurewebsites.net/api/sites/');
$raw		=$xmlString;
$readable	=htmlentities($xmlString);

// Formatting Corrections
$xmlString	=str_replace('<!--?xml version="1.0" encoding="utf-16"?-->', '', $xmlString);
$xmlString	=str_replace('<?xml version="1.0" encoding="utf-16"?>', '', $xmlString);

// There may be other issues with the response, so let's handle warnings
set_error_handler(function($errno=false, $errstr='') {
	$response->error=array($errno, $errstr);
}, E_WARNING);

// Try to parse response as xml
$xmlObject=simplexml_load_string($xmlString);

// Restore error handler
restore_error_handler();

$json		=json_encode($xmlObject);
$arrStores	=json_decode($json, true);
if (isset($arrStores['CarPark'])) {
	echo "<pre>";
	print_r($arrStores['CarPark']);exit;
	#stores::delete();
	#store_timing::deleteAll();
	#$response=stores::saveStores($arrStores['CarPark']);
	$response = true;
	/*
	 * Insert timeing of that stores
	 */
	if ($response) {
		$arrStores=stores::getAll();

		if (count($arrStores) > 0) {
			foreach ($arrStores as $store) {
				echo "<hr/>";
				echo "<pre>";print_r($store);
				if ('' !== $store['site_code'] && (int) $store['tesco_site_code'] > 0) {
					$xmlString	=$ranger->connect('http://ranger1webapi.azurewebsites.net/api/sites/'.$store['site_code']);
					$raw		=$xmlString;
					$readable	=htmlentities($xmlString);

					// Formatting Corrections
					$xmlString	=str_replace('<!--?xml version="1.0" encoding="utf-16"?-->', '', $xmlString);
					$xmlString	=str_replace('<?xml version="1.0" encoding="utf-16"?>', '', $xmlString);

					// There may be other issues with the response, so let's handle warnings
					set_error_handler(function($errno=false, $errstr='') {
						$response->error=array($errno, $errstr);
					}, E_WARNING);

					// Try to parse response as xml
					$xmlObject=simplexml_load_string($xmlString);

					// Restore error handler
					restore_error_handler();

					$json			=json_encode($xmlObject);
					$arrStoreTiming	=json_decode($json, true);
					if (isset($arrStoreTiming['Timing'])) {
						echo "<pre>";
						print_r($arrStoreTiming['Timing']);
						#$response=store_timing::saveTimings($store['uid'], $arrStoreTiming['Timing']);
					}
				}
			}
		}
	}
}
?>