<?php

class vehicle_movement {

	private static $vrmpath = 'http://touchpark.azurewebsites.net/api/vehiclemovementid/';

	public static function get($id=false) {
		$result=false;
		if(false !== $id){
			$sql	="SELECT * FROM `vehicle_movement` WHERE `VehicleMovementID`='".(int)$id."' LIMIT 1";
			$issues	=mysql_query($sql);
			if (mysql_num_rows($issues) > 0) {
				while ($row=mysql_fetch_array($issues)) {
					$result=$row;
				}
			}
		}
		return $result;
	}

	/**
	 * Get Most recent ID added
	 * @return integer The maximum ID stored
	 */
	public static function getMostRecentId() {
		$result=false;
		$sql	="SELECT `VehicleMovementID` FROM `vehicle_movement` ORDER BY `VehicleMovementID` DESC LIMIT 1";
		$issues	=mysql_query($sql);
		if (mysql_num_rows($issues) > 0) {
			while ($row=mysql_fetch_array($issues)) {
				$result=$row['VehicleMovementID'];
			}
		}
		return $result;
	}

	public static function addRecent($id, $movements=array()){
		$response = false;
		if(0 < count($movements)){
			$sql = "INSERT INTO `vehicle_movement` (";
			$sql .= "`VehicleMovementID`, ";
			$sql .= "`SiteCode`, ";
			$sql .= "`VRM`, ";
			$sql .= "`EventDate`, ";
			$sql .= "`Direction`, ";
			$sql .= "`Lane`, ";
			$sql .= "`Confidence`, ";
			$sql .= "`MachineName`, ";
			$sql .= "`PlateImage`, ";
			$sql .= "`OverviewImage`, ";
			$sql .= "`InfraredImage` ";
			$sql .= ") ";
			$sql .= "VALUES ";
			$sql .= "(";
			$sql .= "'".(int)$id."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['SiteCode']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['VRM']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['EventDate']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['Direction']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['Lane']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['Confidence']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['MachineName']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['PlateImage']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['OverviewImage']))."', ";
			$sql .= "'".mysql_real_escape_string(trim($movements['InfraredImage']))."' ";
			$sql .= ")";

			mysql_query($sql) or die(mysql_error());

			$response = $id;
		}
		return $response;
	}

	public static function getMovements(){
		$movements=false;
		// Get Last Movement ID
		$movement_id = self::getMostRecentId();

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, self::$vrmpath . (int)$movement_id);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$json = curl_exec($ch);

		if($json){
			$data = json_decode($json);
			$movements = array();
			foreach($data as $index=>$movement){
				$movements[(int)$movement->VehicleMovementID] = array(
					'SiteCode'		=> (int)$movement->SiteCode,
					'VRM'			=> $movement->VRM,
					'EventDate'		=> str_replace('T',' ',$movement->EventDate),
					'Direction'		=> (int)$movement->Direction,
					'Lane'			=> $movement->Lane,
					'Confidence'	=> (int)$movement->Confidence,
					'MachineName'	=> $movement->MachineName,
					'PlateImage'	=> $movement->PlateImage,
					'OverviewImage'	=> $movement->OverviewImage,
					'InfraredImage'	=> $movement->InfraredImage
				);
			}
		}
		return $movements;
	}

	public static function getBySearch($search='', $last=false, $limit=10){
	    $result=false;
		if('' !== $search){
			$arrSearch = explode(",", $search);
			$sql ="SELECT `vehicle_movement`.*, `stores`.`car_park`, `stores`.`post_town` FROM `vehicle_movement`, `stores` ";
			$sql .="WHERE ";
			$sql .="`vehicle_movement`.`SiteCode` = `stores`.`site_code`";
			$i=0;
			foreach($arrSearch as $val){
				$val = trim($val);
				if("" !== $val){
					$sql .= "AND (";
					$sql .="`vehicle_movement`.`VRM` LIKE '%".mysql_real_escape_string($val)."%' ";
					$sql .="OR `vehicle_movement`.`EventDate` LIKE '%".mysql_real_escape_string($val)."%' ";
					$sql .="OR `vehicle_movement`.`SiteCode` LIKE '%".mysql_real_escape_string($val)."%' ";
					$sql .="OR IF(`vehicle_movement`.`Direction` = 1, 'left', 'arrived') LIKE '%".mysql_real_escape_string($val)."%' ";
					$sql .="OR `stores`.`car_park` LIKE '%".mysql_real_escape_string($val)."%' ";
					$sql .="OR `stores`.`post_town` LIKE '%".mysql_real_escape_string($val)."%') ";
				}
				$i++;
			}
			if($last > 0){
				$sql .="AND `vehicle_movement`.`VehicleMovementID` < '".(int)$last."' ";
			}
			$sql .="ORDER BY `vehicle_movement`.`EventDate` DESC LIMIT ".$limit;

			$issues	=mysql_query($sql) or die(mysql_error());
			if (mysql_num_rows($issues) > 0) {
				while ($row=mysql_fetch_assoc($issues)) {
					$result[$row['VehicleMovementID']]=$row;
				}
			}
		}
		return $result;
	}

	public static function getLatest($limit=10) {
		$result=false;
		if(false !== $id){
			$sql="SELECT `vehicle_movement`.*, `stores`.`car_park`, `stores`.`post_town` FROM `vehicle_movement`, `stores` WHERE `vehicle_movement`.`SiteCode` = `stores`.`site_code` ORDER BY `vehicle_movement`.`EventDate` DESC LIMIT ".$limit;
			$issues	=mysql_query($sql);
			if (mysql_num_rows($issues) > 0) {
				while ($row=mysql_fetch_assoc($issues)) {
					$result[$row['VehicleMovementID']]=$row;
				}
			}
		}
		return $result;
	}

	public static function getBeforeIDs($id=false, $limit=0) {
		$result=false;
		if(false !== $id){
			$sql="SELECT `vehicle_movement`.*, `stores`.`car_park`, `stores`.`post_town` FROM `vehicle_movement`, `stores` WHERE `vehicle_movement`.`SiteCode` = `stores`.`site_code` AND `vehicle_movement`.`VehicleMovementID` > '".(int)$id."' ORDER BY `vehicle_movement`.`EventDate` DESC ";
			if($limit > 0){
				$sql .= "LIMIT ".$limit;
			}
			$issues	=mysql_query($sql);
			if (mysql_num_rows($issues) > 0) {
				while ($row=mysql_fetch_assoc($issues)) {
					$result[$row['VehicleMovementID']]=$row;
				}
			}

		}
		return $result;
	}

	public static function getAfterIDs($id=false, $limit=10) {
		$result=false;
		if(false !== $id){
			$sql="SELECT `vehicle_movement`.*, `stores`.`car_park`, `stores`.`post_town` FROM `vehicle_movement`, `stores` WHERE `vehicle_movement`.`SiteCode` = `stores`.`site_code` AND `vehicle_movement`.`VehicleMovementID` < '".(int)$id."' ORDER BY `vehicle_movement`.`EventDate` DESC LIMIT ".$limit;
			$issues	=mysql_query($sql);
			if (mysql_num_rows($issues) > 0) {
				while ($row=mysql_fetch_assoc($issues)) {
					$result[$row['VehicleMovementID']]=$row;
				}
			}
		}
		return $result;
	}

	public static function makeList($arrVehicle=array(), $skipNewbtton=false, $skipTimeline=false) {
		$result='';
		if(count($arrVehicle) > 0){
			$now = date("Y-m-d");
			$arrData = array();
			$today = false;
			foreach($arrVehicle as $id => $vehile){
				$date = date("Y-m-d", strtotime($vehile['EventDate']));

				$arrData[$date][$id] = $vehile;
				if($date == $now){
					$today = true;
				}
			}
			
			foreach($arrData as $date => $data){

				$result .= '<div class="vrmsearch-timeline">';
					if($now == $date){
						$result .= '<a href="#" class="vrmsearch-timeline-header">TODAY</a>';
						if(!$skipNewbtton){
							$result .= '<div class="vrmsearch-timeline-items-new">';
								$result .= '<a href="#" class="vrmsearch-timeline-items-new-button"><span class="u-NewVRM-Numbers">0</span> NEW <span class="vrmsearch-timeline-items-new-button-span">SHOW</span></a>';
							$result .= '</div>';
						}
					}else{
						$result .= '<a href="#" class="vrmsearch-timeline-header">'.date("l jS F Y", strtotime($date)).'</a>';
					}
					
				$result .= '<div class="vrmsearch-timeline-items-block">';
				foreach($data as $id => $vehicle){	
					$result .= self::getItem($vehicle);	
				}
			$result .= '</div></div>';
			}
		}
		return $result;
	}


	public function getItem($vehicle= array()){
		$result = '';
		if($vehicle['Direction'] == 1){
			$diraction_class = "item-juftleft";
			$diraction_icon  = "icon-park-out";
			$summary_title   = "DEPARTED";
		} else {
			$diraction_class = "item-juftarrived";
			$diraction_icon  = "icon-park-in";
			$summary_title   = "ARRIVED";
		}

		$result .= '<div class="vrmsearch-timeline-items '.$diraction_class.'" data-id="'.$vehicle['VehicleMovementID'].'">
						<div class="vrmsearch-timeline-item">
							<div class="vrmsearch-timeline-img">
								<!--span class="vrmsearch-timeline-img-icon '.$diraction_icon.'"></span-->
								<span class="vrmsearch-timeline-img-circle">
									<img src="'.$vehicle['OverviewImage'].'" />
								</span>
							</div>
							<div class="vrmsearch-timeline-summary">
								<div class="vrmsearch-timeline-summary-block">
									<p class="vrmsearch-timeline-summary-title"><span>'.$summary_title.'</span> <span class="vrmsearch-timeline-summary-numberplate">'.$vehicle['VRM'].'</span> <span class="vrmsearch-timeline-summary-locationplate">'.$vehicle['post_town'].'</span></p>
								</div>
							</div>
							<div class="vrmsearch-timeline-result">
								<span class="vrmsearch-timeline-result-time">'.date("H:i", strtotime($vehicle['EventDate'])).'</span>
							</div>
							<span title="Open action block" class="icon-dropdown vrmsearch-timeline-item-open"></span>
						</div>
						<div class="vrmsearch-timeline-action">
							<div class="vrmsearch-timeline-action-block">
								<a href="#" class="vrmsearch-timeline-action-button u-Action-Add">ADD VOI</a>
								<a href="#" class="vrmsearch-timeline-action-button u-Action-Flag">FLAG</a>
								<a href="#" class="vrmsearch-timeline-action-button u-Action-Keep">KEEP</a>
							</div>
						</div>
					</div>';

		return $result;			
	}
}

?>