<?php
App::uses('AppController', 'Controller');
class TrackingController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
	//var $helpers = array('Html', 'Form', 'Xml'); 
	function beforeFilter(){
		$this->Auth->allow(array('addlatlong','trackusers'));
	}
	/*public function addlatlong(){
		$this->loadModel('UserTracking');
		$this->loadModel('User');
		
		$response = $data = array();
		
		$response['error'] = 1;
		if (!empty($this->request->data['jsonString'])){
			$string = preg_replace("/[\r\n\t]+/", " ", $this->request->data['jsonString']);
			$jsonString = utf8_encode($string);
			$this->request->data = json_decode($jsonString, true );	
			$token = $this->request->data['token'];			
		}else{
			$token = $this->data['token'];
		}
		//pr($this->data);
		//
		$user = $this->User->findBySessionToken($token);
		//pr($user);
		//die();
		if( $user && ($this->data['user_id'] == $user['User']['id']) ){
			if( isset($this->data['multiple']) && $this->data['multiple'] == 1 ){
				if(!empty($this->data['trackdata'])){
					$user_id = $user['User']['id'];
					$insertData = array();
					$sqliteId = array();
					foreach($this->data['trackdata'] as $trackdata){
						//check is added
						$is_added = $this->UserTracking->find('count', array('conditions'=>array('user_id'=>$user_id, 'lat'=>$trackdata['lat'], 'long'=>$trackdata['long'],'tracking_time'=>$trackdata['tracking_time']) ));
						if($is_added == 0){
							$insertData[] = array('user_id' => $user_id, 'lat'=>$trackdata['lat'], 'long'=>$trackdata['long'], 'tracking_time'=>$trackdata['tracking_time']);		
						}
						$sqliteId[] = $trackdata['dbid'];
					}
					if(count($insertData) > 0){						
						$this->UserTracking->saveAll($insertData);						
					}
					$response['error'] = 0;
					$response['ids'] = implode(",", $sqliteId);
					$response['message'] = 'Tracking was saved successfully';
				}
			}elseif (!empty($this->data['lat']) && !empty($this->data['long'])){
				$data = array('user_id' => $this->data['user_id'], 'lat'=>$this->data['lat'], 'long'=>$this->data['long'], 'tracking_time'=>$this->data['tracking_time']);
				
				$this->UserTracking->saveAll($data);
			
				$response['error'] = 0;
				$response['message'] = 'Tracking was saved successfully';
			}else{
				$response['message'] = 'coordinate was empty, please try again';
			}
		}else{
			$response['message'] = 'Invalid session token';
		}
		echo json_encode($response);
		exit;
		
	}*/
	
	public function addlatlong(){
		$this->loadModel('UserTracking');
		$this->loadModel('User');
		
		$response = $data = array();
		
		$response['error'] = 1;
		if (!empty($this->request->data['jsonString'])){
			$string = preg_replace("/[\r\n\t]+/", " ", $this->request->data['jsonString']);
			$jsonString = utf8_encode($string);
			$this->request->data = json_decode($jsonString, true );	
			$token = $this->request->data['token'];			
		}else{
			$token = $this->data['token'];
		}
		//pr($this->data);
		//
		$user = $this->User->findBySessionToken($token);
		//pr($user);
		//die();
		if( $user && ($this->data['user_id'] == $user['User']['id']) ){
			if( isset($this->data['multiple']) && $this->data['multiple'] == 1 ){
				if(!empty($this->data['trackdata'])){
					$user_id = $user['User']['id'];
					$insertData = array();
					$sqliteId = array();
					foreach($this->data['trackdata'] as $trackdata){
						//check is added
						$is_added = $this->UserTracking->find('count', array('conditions'=>array('user_id'=>$user_id, 'lat'=>$trackdata['lat'], 'long'=>$trackdata['long'],'tracking_time'=>$trackdata['tracking_time']) ));
						if($is_added == 0){
							$insertData[] = array('user_id' => $user_id, 'lat'=>$trackdata['lat'], 'long'=>$trackdata['long'], 'tracking_time'=>$trackdata['tracking_time']);		
						}
						$sqliteId[] = $trackdata['dbid'];
					}
					if(count($insertData) > 0){						
						$this->UserTracking->saveAll($insertData);						
					}
					$response['error'] = 0;
					$response['ids'] = implode(",", $sqliteId);
					$response['message'] = 'Tracking was saved successfully';
				}
			}elseif (!empty($this->data['lat']) && !empty($this->data['long'])){
				$data = array('user_id' => $this->data['user_id'], 'lat'=>$this->data['lat'], 'long'=>$this->data['long'], 'tracking_time'=>$this->data['tracking_time']);
				
				$this->UserTracking->saveAll($data);
			
				$response['error'] = 0;
				$response['message'] = 'Tracking was saved successfully';
			}else{
				$response['message'] = 'coordinate was empty, please try again';
			}
		}else{
			$response['message'] = 'Invalid session token';
		}
		echo json_encode($response);
		exit;
		
	}
	
	
	public function trackusers($date = ''){
		$this->layout = 'kml';
		$this->loadModel('UserTracking');
		$conditions = array();
		if($this->request->query){
			foreach($this->request->query as $k=>$val){
				$k = str_replace('amp;', '', $k);
				$this->request->query[$k] = $val;
			}
		}
		
		if(!empty($this->request->query['dt']) ){
			$date = $this->request->query['dt'];
		}else{
			$date = date('Y-m-d');
		}
		$query = $this->request->query;
		if(!empty($query['stime'])){
			$date1 = date('Y-m-d H:i:s', strtotime($date.' '.$query['stime']) );
		}else{
			$date1 = $date.' 06:00:00';
		}
		
		if(!empty($query['etime'])){
			$date2 = date('Y-m-d H:i:s', strtotime($date.' '.$query['etime']) );
		}else{
			$date2 = $date.' 23:59:59';
		}
		$conditions[] = 'UserTracking.created BETWEEN "'.$date1.'" AND "'.$date2.'"';
		if(!empty($this->request->query['dp']) ){
			$conditions['User.depot_id'] = $this->request->query['dp'];
		}
		if(!empty($this->request->query['rg']) ){
			$conditions['User.region_id'] = $this->request->query['rg'];
		}
		if(!empty($this->request->query['usr']) ){
			$conditions['UserTracking.user_id'] = $this->request->query['usr'];
		}
		
		
		
		$conditions['UserTracking.lat !='] = 0;
		$conditions['UserTracking.long !='] = 0;
		$this->UserTracking->belongsTo = array('User' => array('className' => 'User', 'foreignKey' => 'user_id', 'type'=>'left', 'fields'=>array('id', 'first_name', 'last_name')));
		$trackingData = $this->UserTracking->find('all', array('conditions'=>$conditions, 'order'=>array('UserTracking.user_id' => 'desc','UserTracking.created' => 'desc')));
		//pr($trackingData);
		$trackData = array();
		foreach($trackingData as $track){
			
			$trackData[$track['User']['id']][] = $track;
		}
		//pr($trackData);
		$this->set('trackData', $trackData);
		
	}
	
	public function result(){
	//	$this->gradPermission(3);
		
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$this->loadModel('User');
		
		$this->user = $this->Auth->user();
		$users = $this->User->usersListByRole($this->user);
		if(!empty($this->request->query['rg'])){
			$region_id = $this->request->query['rg'];
		}else{
			$region_id = !empty($this->user['region_id'])?$this->user['region_id']:0;
		}
		$regions = $this->Region->getList();
		$depots = $this->Depot->getList($region_id);
		
		$this->set(compact('users', 'regions', 'depots'));
		
	}
	
	public function history(){
	//	$this->gradPermission(3);
		$this->loadModel('UserTracking');
		$this->loadModel('User');
		$historyData = $conditions = array();
		$conditions['UserTracking.lat !='] = 0;
		$conditions['UserTracking.long !='] = 0;
		if(!empty($this->request->query['dt']) ){
			$date = $this->request->query['dt'];
		}else{
			$date = date('Y-m-d');
		}
		
		$query = $this->request->query;
		if(!empty($query['stime'])){
			$date1 = date('Y-m-d H:i:s', strtotime($date.' '.$query['stime']) );
		}else{
			$date1 = $date.' 06:00:00';
		}
		
		if(!empty($query['etime'])){
			$date2 = date('Y-m-d H:i:s', strtotime($date.' '.$query['etime']) );
		}else{
			$date2 = $date.' 23:59:59';
		}
		$conditions[] = 'UserTracking.created BETWEEN "'.$date1.'" AND "'.$date2.'"';
		if(!empty($this->request->query['usr']) ){
			$conditions['UserTracking.user_id'] = $this->request->query['usr'];
			$this->User->unbindModel(array('belongsTo'=>array('Region', 'Depot', 'State','File', 'Role')));
			$userData = $this->User->find('first', array('fields'=>array('first_name','last_name'), 'conditions'=>array('id'=>$this->request->query['usr'] )));
			
			
			 
			//$conditions['UserTracking.created LIKE'] = $date.'%';
		
			//$this->paginate['conditions'] = $conditions;
			
			$historyResults = $this->UserTracking->find('all', array('conditions'=>$conditions, 'order'=>array('created'=>'asc')));
			
			if( $historyResults ){
				$startTime = strtotime($historyResults['0']['UserTracking']['created']);
				$startLatLong = array('datetime'=>$startTime, 'lat'=>$historyResults['0']['UserTracking']['lat'], 'long'=>$historyResults['0']['UserTracking']['long']);
				foreach($historyResults as $history){
					$endTime = strtotime($history['UserTracking']['created']);
					$endLatLong = array('datetime'=>$endTime, 'lat'=>$history['UserTracking']['lat'], 'long'=>$history['UserTracking']['long']);
					if (($endTime - $startTime) >= 1800){
						$historyData[] = array('start'=>$startLatLong, 'end'=>$endLatLong,  'data'=>$history);
						$startTime = $endTime;
						$startLatLong = $endLatLong;
					}
				}
			}
		}
		
		
		
		$this->user = $this->Auth->user();
		$users = $this->User->usersListByRole($this->user);
		
		$this->set(compact('historyData', 'users', 'userData', 'date') );
	}
	
}