<?php
App::uses('AppController', 'Controller');
/**
 * Spy controller to manage spy activities
 */
class CrmspyController extends AppController
{
	public $result;
	var $user;
	var $uses = array();
	public $paginate = array(
		'paramType' => 'querystring'
	);
	
	public function activities($uid = 0){
		$userData = $this->_getmd5User($uid);
		$this->set('userData', $userData );
	}
	
	public function notification($uid = 0, $opr = "notification"){
		$userData = $this->_getmd5User($uid);
		/* if(!empty($userData['User']['gcm_regid'])){ */
		if(!empty($userData['User']['firebase_token'])){
			$message = array("msgData"=>"", "opr"=>$opr);
			$notification_mess = "";
			if($opr == "changepwd"){				
				$message['msgData'] = isset($this->data['txtPass'])?$this->data['txtPass']:"";
			}elseif($opr == "notification"){
				$notification_mess = $message['msgData'] = isset($this->data['pushMess'])?$this->data['pushMess']:"";
				 $message['notify_time'] = date('Y-m-d H:i:s');
			}
			/* $registatoin_ids = array($userData['User']['gcm_regid']); */
			 $registration_ids = array($userData['User']['firebase_token']);
			$message = array("message" => $message);    
			$result = $this->send_notification($registration_ids, $message  );	//pr($result);		
			if ($result === FALSE) {
				echo __("Failed to connect mobile device");
			}else{
				$resultArr = json_decode($result, true);
				if(isset($resultArr['success']) && $resultArr['success'] == 1){
					echo $this->getMessage($opr);
					if($opr == "notification"){
						//Save notification into database
						$this->loadModel('PushNotification');
						$datatoadd = array('user_id'=>$userData['User']['id'], 'send_by'=>$this->Auth->user('id'), 'message'=>$notification_mess, 'response'=>$result);
						$this->PushNotification->save($datatoadd);
					}
				}else{
					echo __('Request was not getting success, Error: %s', isset($resultArr['results']['0']['error'])?$resultArr['results']['0']['error']:"notRegsitered");
				//pr($resultArr);
				}
				
			}
		}
		exit;
	}
	
	public function getlocation($uid){
		$this->layout = null;
		$this->loadModel('UserTracking');
		$trackData = $this->UserTracking->find('first', array('conditions'=>array('md5(UserTracking.user_id)'=>$uid), 'order'=>array('UserTracking.id'=>'desc') ));
		$this->set('trackData', $trackData);
	}

	
	
	private function _getmd5User($uid){
		$this->loadModel('User');
		$this->User->unbindModelAll();
		$userData = $this->User->find('first', array('conditions'=>array('md5(id)'=>$uid), 'fields'=>array('id', 'first_name', 'last_name', 'gcm_regid','firebase_token') ));
		return $userData;
	}
	
 /**
 * Sending Push Notification
 */
    /* public function send_notification($registatoin_ids, $message) {
       
        // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';

        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message
        );

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Disabling SSL Certificate support temporary
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);
        return $result;
    } */
	
	
	public function send_notification($registration_ids, $message) { //pr($message); die();
	
		define('API_ACCESS_KEY',FIREBASE_API_KEY);
       
        // Set POST variables
        $fcmUrl = 'https://fcm.googleapis.com/fcm/send';
		
		switch($message['message']['opr']){
			case 'changepwd':
				$body = 'Your phone password has been changed';
				break;
				
			default:
				$body = 'You have recieved new message';
				break;
			
		} 
		
        
        $notification = [
            'body' => $body,
            'icon' =>'default', 
            'sound' => 'default'
        ];
        
        
        $fcmNotification = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
            'notification' => $notification,
        );
		
		
		$headers = [
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        ];
		
		//pr($fcmNotification);
		
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $fcmUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Disabling SSL Certificate support temporary
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);
        return $result;
    }
	
	function getMessage($opr){
		$returnMessage = array(
		'changepwd' => __('Change password request was send to user\'s device'), 
		'notification'=>__('Notification was send to the user\'s device'), 
		'getlocation'=>__('Getting the location..'), 
		'dataclean'=>__('Mobile device data clean request was send to the user\'s mobile, All data will removed'), 'ring'=>__('Mobile ring request was send to the user\'s device'), 
		'blockphone'=>__('User\'s phone blocking request was send'));
		
		return isset($returnMessage[$opr])?$returnMessage[$opr]:"Request was send";
	}
	
	function admin_history(){
		if (!empty($this->request->query['usr'])){
			$uid = $this->request->query['usr'];
			$this->loadModel('User');
			$this->loadModel('DeviceAdminLog');
			$userData = $this->User->find('first', array('conditions'=>array('User.id'=>$uid) ));
			//$this->paginate['joins'] = array(array('table'=>'users', 'type'=>'INNER', 'alias'=>'User', 'conditions'=> array('DeviceAdminLog.user_id = User.id') ));
			//$this->paginate['fields'] = array('User.*', 'DeviceAdminLog.*');
			$this->paginate['order'] = array('DeviceAdminLog.created' => 'desc');
			$conditions = array('DeviceAdminLog.user_id'=>$uid);
			$history = $this->paginate('DeviceAdminLog', $conditions);
			
			$this->set(compact('userData', 'history'));
		}
	}
	
	function notifications(){
		$this->loadModel('PushNotification');
		$conditions = array();
		$querystring = $this->request->query;
		if (!empty($querystring['q']) ){
			$keyword = strtolower(trim($this->request->query['q']));
			$conditions['OR']['CONCAT_WS(" ", User.first_name,User.first_name) LIKE'] =  '%'.$keyword.'%';
			$conditions['OR']['CONCAT_WS(" ", SendBy.first_name,SendBy.first_name) LIKE'] =  '%'.$keyword.'%';
			$conditions['OR']['PushNotification.message LIKE'] = '%'.$keyword.'%';
		}
		
		if(!empty($querystring['dv'])){
            $conditions['User.division_id'] =  $querystring['dv'];
        }
		if(!empty($querystring['rg'])){
			$conditions['User.region_id'] =  $querystring['rg'];
		}
		if(!empty($querystring['dp'])){
			$conditions['User.depot_id'] =  $querystring['dp'];
		}
		$this->PushNotification->belongsTo = array(
					'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'), 'SendBy' => array('className' => 'User', 'foreignKey' => 'send_by', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'));
		
		$this->paginate['order'] = array('PushNotification.id'=>'desc');
		$notifications = $this->paginate('PushNotification', $conditions);
		$this->_selectOptions();
		
		$this->set(compact('notifications', 'querystring'));
		if(isset($this->request->query['export'])){
			$this->set('filename', 'Notification');
			$this->render('notifications_xls','export_xls');
		}
	}
	
	function _selectOptions(){
		$this->loadModel('Division');
		$this->loadModel('Depot');
		$this->loadModel('Region');
		$this->loadModel('User');	
		
		$stateConditions = array();
		if (!empty($this->user['Role']['grade']) && $this->user['Role']['grade'] > 2 && !empty($this->user['state_id'])){
			$stateConditions = array('id'=>$this->user['state_id']);
		}		
		
		$divisions = $regions = $depots = $lgAreas = array();
		if(empty($this->user['division_id'])){
            $divisions = $this->Division->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
        }
		if(empty($this->user['region_id']) || $this->user['Role']['grade'] < 3 ){
			$regions = $this->Region->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		}
		if(empty($this->user['depot_id'])){
			$depots = $this->Depot->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		}
		
		$users = $this->User->usersListByRole($this->user);
		
		$this->set(compact('divisions','regions','depots', 'users'));
	}
	
	function deletemessage($id){
		
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('PushNotification');
        $this->PushNotification->id = $id;		
        if ($this->PushNotification->delete()) {
			
            $this->Session->setFlash(__('Notification was deleted successfully'));
            $this->redirect(array('controller'=>'spy', 'action' => 'notifications'));
        }else{
			$this->Session->setFlash(__('Notification was not deleted'));
			$this->redirect(array('controller'=>'spy','action' => 'notifications'));
		}
	}
	
	 public function deleteAllNotification(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('PushNotification');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->PushNotification->deleteAll(array('PushNotification.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Notification was deleted successfully') );
			$this->redirect(array('controller'=>'spy','action' => 'notifications'));
		}
		exit;
	}
}