<?php
App::uses('AppController', 'Controller');
/**
 * Controller name
 *
 * @var string
 */
class DevicelogController extends AppController
{
	public $result;
	var $user;
	
	public $paginate = array(
		'paramType' => 'querystring'
	);
	
	 function beforeFilter(){
		$this->Auth->allow(array('addlogs','mapkmllayer', 'secuirity_alert'));
		$this->result = array();
		$this->result['error'] = 1;
		$this->result['success'] = "false";
		
		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 );			
		} 
		$this->user = $this->Auth->user();
	} 
	
	function addlogs(){
		$this->loadModel('DeviceLog');
		if (is_array($this->request->data)){
			if (!empty($this->request->data['device_id'])){
				//$this->DeviceLog->deleteAll(array('device_id'=>$this->request->data['device_id']));
			}
			if (isset($this->request->data['logData'])){
				$data = array();
				$user_id = 0;
				//pr($this->request->data);
				if (isset($this->request->data['deviceId']) || isset($this->request->data['token'])){
					$this->loadModel('User');
					//$user = $this->User->findByImei($this->request->data['deviceId']);
					$user = $this->User->find('first', array('conditions'=>array('OR'=>array('User.session_token'=>$this->request->data['token'], 'User.imei'=>$this->request->data['deviceId']))));
					if($user){
						$user_id = $user['User']['id'];
					}
				}
				//pr($this->request->data['logData']);
				$deviceLogsIds = array();
				$dlStr = null;
				foreach($this->request->data['logData'] as $logData){
					
					if (empty($logData['user_id']) ){
						$logData['user_id'] = $user_id;
					}
					
					if (!empty($logData['user_id'])){
						$data[] = $logData;				 
					}	
					if (!empty($logData['_id']) ){
						$deviceLogsIds[] = $logData['_id'];
					}
					if (!empty($deviceLogsIds)){
						$dlStr = implode(",",$deviceLogsIds);
					}
				}
				
				if($data){
					$saved = $this->DeviceLog->saveAll($data);
				}
				
				$this->result['message'] = __('Log data was saved successfully');
				$this->result['error'] = 0;
				$this->result['deviceLogsIds'] = $dlStr;
				$this->result['success'] = "true";
				
			}
		}else{
			$this->result['message'] = __('There are internal error , please try again');
		}
		$this->result['timestamp'] = time();
		echo json_encode($this->result, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	
	function index(){
		$this->loadModel('DeviceLog');
		
		$actConditions = array('activity IS NOT NULL');
		$conditions = array();
		if (!empty($this->request->query['q']) ){
			$conditions['CONCAT_WS(" ", LOWER(User.first_name),LOWER(User.last_name)) LIKE'] =  '%'.strtolower($this->request->query['q']).'%';
			
		}
		if ( !empty($this->request->query['dt'])){
			$date = $this->request->query['dt'];
		}else{
			$date = date('Y-m-d');
		}
		$query = $this->request->query;
		if(empty($query['dr'])){
			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[] = "DeviceLog.start_time between '$date1' AND '$date2'";
		}else{
			if(!empty($query['to'])){
				$date2 = date('Y-m-d', strtotime("+1 day", strtotime($query['to'])) );
			}
			if (!empty($query['from']) && !empty($query['to'])){
				$date1 = $query['from'];
				$conditions[] = "DeviceLog.start_time between '".$query['from']."' AND '$date2'";				
			}elseif(!empty($query['from']) ){
				$conditions[] = "DeviceLog.start_time >= '".$query['from']."'";
			}elseif(!empty($query['to'])){
				$conditions[] = "DeviceLog.start_time <= '".$date2."'";
			}
		}
		if (!empty($this->request->query['ac']) ){
			$conditions['DeviceLog.activity'] = $this->request->query['ac'];
		}
		if (!empty($this->request->query['uid']) ){
			$conditions['DeviceLog.user_id'] = $this->request->query['uid'];
			$actConditions['DeviceLog.user_id'] = $this->request->query['uid'];
		}
		
		$this->DeviceLog->belongsTo = array(
					'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'));
					
		$order = $this->paginate['order'] = array('DeviceLog.start_time'=>'desc');
		
		if(isset($this->request->query['export'])){  
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}	
              $logs = $this->DeviceLog->find('all',array('conditions' => $conditions,'order'=>$order, 'limit'=>10000, 'offset'=>$offset));
		}else{
		     $logs = $this->paginate('DeviceLog', $conditions);
		}
		
		$activityApp = $this->DeviceLog->find('list', array('fields'=>array('activity','activity'), 'group'=>array('activity'), 'conditions'=>$actConditions ));
		$this->loadModel('User');
		//pr($this->user);
		$users = $this->User->usersListByRole($this->user);
		$this->set(compact('logs', 'activityApp','users', 'date' , 'query','offset'));
		
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'DeviceLog');
			   $this->render('export_device_log','export_xls');
		}
	}
	
	function userlogs($uid = 0){
		$this->loadModel('User');
		$this->loadModel('DeviceLog');
		$userData = $this->User->findById($uid);
		if ( !empty($this->request->query['dt'])){
			$date = $this->request->query['dt'];
		}else{
			$date = date('Y-m-d');
		}
		$query = $this->request->query;
		$conditions = array('user_id'=>$uid);
		if(empty($query['dr'])){
			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[] = "start_time between '$date1' AND '$date2'";
		}else{
			if(!empty($query['to'])){
				$date2 = date('Y-m-d', strtotime("+1 day", strtotime($query['to'])) );
			}
			if (!empty($query['from']) && !empty($query['to'])){
				$date1 = $query['from'];
				$conditions[] = "start_time between '".$query['from']."' AND '$date2'";				
			}elseif(!empty($query['from']) ){
				$conditions[] = "start_time >= '".$query['from']."'";
			}elseif(!empty($query['to'])){
				$conditions[] = "start_time <= '".$date2."'";
			}
		}
		
		
		$logs = $this->DeviceLog->find('all', array('conditions'=>$conditions ));
		$logData = array();
		$totalTime = 0;
		if($logs){
			foreach($logs as $log){
				$activity = $log['DeviceLog']['activity'];
				$totalTime += (int)$log['DeviceLog']['duration'];
				
				if (!isset($logData[$activity])){
					$logData[$activity] = (int)$log['DeviceLog']['duration'];
				}else{
				
					$logData[$activity] += (int)$log['DeviceLog']['duration'];
				}
			}
		}
		arsort($logData);
		$this->set(compact('userData', 'logData', 'totalTime', 'date'));
	}
	function userlogstabular($uid = 0){
		$this->loadModel('User');
		$this->loadModel('DeviceLog');
		
		if ( !empty($this->request->query['dt'])){
			$date = $this->request->query['dt'];
		}else{
			$date = date('Y-m-d');
		}
		$query = $this->request->query;
		$conditions = array('user_id'=>$uid);
		if(empty($query['dr'])){
			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[] = "start_time between '$date1' AND '$date2'";
		}else{
			if(!empty($query['to'])){
				$date2 = date('Y-m-d', strtotime("+1 day", strtotime($query['to'])) );
			}
			if (!empty($query['from']) && !empty($query['to'])){
				$date1 = $query['from'];
				$conditions[] = "start_time between '".$query['from']."' AND '$date2'";				
			}elseif(!empty($query['from']) ){
				$conditions[] = "start_time >= '".$query['from']."'";
			}elseif(!empty($query['to'])){
				$conditions[] = "start_time <= '".$date2."'";
			}
		}
		
		
		$logs = $this->DeviceLog->find('all', array('conditions'=>$conditions, 'order'=>array('start_time'=>'asc') ));
		$logData = $logLatLongData = array();
		$totalTime = 0;
		if($logs){
			foreach($logs as $log){
				$activity = $log['DeviceLog']['activity'];
				$totalTime += (int)$log['DeviceLog']['duration'];
				
				if (!isset($logData[$activity])){
					$logData[$activity] = (int)$log['DeviceLog']['duration'];
				}else{
				
					$logData[$activity] += (int)$log['DeviceLog']['duration'];
				}
				
				$logLatLongData[$activity][] = $log['DeviceLog'];
			}
		}
		//arsort($logData);
		$this->set(compact('logData', 'logLatLongData'));
	}
	
	public function viewonmap(){
	
	}
	function locateonmap($uid = 0){
		$this->loadModel('User');
		$userData = $this->User->findById($uid);	
		
		$this->set(compact('userData'));
	}
	function mapkmllayer($uid = 0){
		$this->layout = 'kml';
		$this->loadModel('DeviceLog');
		
		if ( !empty($this->request->query['dt'])){
			$date = $this->request->query['dt'];
		}else{
			$date = date('Y-m-d');
		}
		if($this->request->query){
			foreach($this->request->query as $k=>$val){
				$k = str_replace('amp;', '', $k);
				$this->request->query[$k] = $val;
			}
		}
		$query = $this->request->query;
		$conditions = array('user_id'=>$uid);
		if(empty($query['dr'])){
			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[] = "start_time between '$date1' AND '$date2'";
			
		}else{
			if(!empty($query['to'])){
				$date2 = date('Y-m-d', strtotime("+1 day", strtotime($query['to'])) );
			}
			if (!empty($query['from']) && !empty($query['to'])){
				$date1 = $query['from'];
				$conditions[] = "start_time between '".$query['from']."' AND '$date2'";				
			}elseif(!empty($query['from']) ){
				$conditions[] = "start_time >= '".$query['from']."'";
			}elseif(!empty($query['to'])){
				$conditions[] = "start_time <= '".$date2."'";
			}
		}
		//print_r($conditions);
		$this->DeviceLog->belongsTo = array('User' => array('className' => 'User', 'foreignKey' => 'user_id', 'type'=>'left', 'fields'=>array('id', 'first_name', 'last_name')));
		
		$trackData = $this->DeviceLog->find('all', array('conditions'=>$conditions, 'order'=>array('DeviceLog.start_time'=>'asc') ));
		
		
		$this->set('trackData', $trackData);
		$this->set('uid', $uid);
		
	}
	
/**
 * Make an alert on inactivate the device security
 * 
 */
	public function secuirity_alert(){
		$this->result = $data = array();
		$data = $this->request->data;
		$this->result['error'] = 0;
		$this->loadModel('DeviceAdminLog');
		$this->loadModel('User');
		$userId = 0;
		if( !empty($data['userId']) ){
			$userId = $data['userId'];
		}else{
			if(!empty($data['deviceId'])){
				$userId = $this->User->field("id", array("imei"=>$data['deviceId']) );
			}
		}
		$toSaveData = array('user_id'=>$userId, 'status'=>$data['status'], 'device_id'=>$data['deviceId']);
		$dataSave = $this->DeviceAdminLog->save($toSaveData);
		if($dataSave){
			$this->result['message'] = __('Log was added');
		}
		
		echo json_encode($this->result);
		exit;
	}
	
	public function pushnotifiation($uid = 0){
		$this->loadModel('User');
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL, PUSH_URL);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_HEADER, true); 
		curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Header : \"project_id\": <".APP_PROJECT_ID.">", "Header: \"Authorization\", \"key=".PUSHAPI_KEY."\"" ));
		$fields = array("dsd"=>'dsfsdf', 'test'=>'test vale');
		curl_setopt($ch, CURLOPT_POST, 1); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
		$response = curl_exec($ch); 
		pr($response);
		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
		print_r($status);
		curl_close($ch); 
		exit;
	}
}	
