<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
	
	public $name = 'Users';
	
	function beforeFilter(){
		$this->Auth->authenticate = array(
            'Form' => array(
                'fields' => array('username' => 'username'),
				'scope' => array('User.status' => 1)
            )
        );
		$this->Auth->allow(array('service_login', 'auto_login','autologin'));
	}
	var $components = array('FileUpload' => array(
					'allow_non_image_files' => false),'Option');
	 
	
	
	/**
     * dashboard method
     *
     * @return void
     */
	public function dashboard() {
		
		$this->user = $user = $this->Auth->user();
		//pr($this->Auth->user());
		switch($user['Role']['grade']){
			case 1:
			case 2:
			case 3:
			case 4:
				$this->getFrontData();
				$this->render('admin_dashboard');
			break;
			/*
				$this->set('udata', $user);
				$this->render('depot_dashboard');
			break;
			*/
			
			default:
				$this->set('udata', $user);
				$this->render('dashboard');
			break;
		}
	} 
	
    public function getFrontData(){
		//Get active compaign
		$this->loadModel('Compaign');
		//$this->loadModel('User');
		$this->Compaign->unbindModel(array('hasAndBelongsToMany'=>array('Region','Depot')));
		$compaigns = $this->Compaign->find('all', array('conditions'=>array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date")));
		$this->set('compaigns', $compaigns);
		
		$visits = $this->User->currentmonthVisit($this->user);
		//pr($visits);
		$this->set('visits',$visits);
		//pr($sales);
	}
	function _userCondition(&$conditionsa){
		switch($this->user['Role']['grade']){
			case 6:
				$conditions['Customer.user_id'] = $this->user['id'];
			break;
			case 5:
			default:
			break;
		}
	}
	
/**
 * login method
 *
 * @return void
 */
	public function login(){
		
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				$this->loadModel('Rolepermission');
				$roleid = $this->Auth->user("role_id");
				$permData = $this->User->getrolepermission($roleid);
				foreach($permData as $permDatas){
					$data[] = $permDatas['p']['controller'].'/'.$permDatas['p']['action'];					
				}				
				$this->Session->write('Auth.User.permission', $data);
				$this->loadModel('SpecialPermission');
				$special_per = $this->SpecialPermission->find('all', array('conditions'=>array('user_id'=>$this->Auth->user("id")) ));
				if($special_per){
					$sp_arr = array();
					foreach($special_per as $sp){
						$sp_arr[] = $sp['SpecialPermission']['action'];
					}
					//pr($sp_arr);
					$this->Session->write('Auth.User.SpecialPermission', $sp_arr);
				}
				$this->redirect($this->Auth->redirectUrl('dashboard'));
			} else {
				$this->Session->setFlash(__('Please check your username or password'), 'default', array());
			}
		}
	}
	
	public function autologin(){
		if($this->Auth->loggedIn()){
			$this->redirect($this->Auth->redirectUrl());
		}
		if(!empty($this->request->query['usr'])){
			$user = $this->User->findByUsername($this->request->query['usr']);
			if($user && LOGINTOKEN == $this->request->query['token']){
				$user = array_merge($user['User'], $user);
				$this->Auth->login($user);
				$this->loadModel('Rolepermission');
				$roleid = $this->Auth->user("role_id");
				$permData = $this->User->getrolepermission($roleid);
				foreach($permData as $permDatas){
					$data[] = $permDatas['p']['controller'].'/'.$permDatas['p']['action'];					
				}				
				$this->Session->write('Auth.User.permission', $data);
				$this->redirect($this->Auth->redirectUrl());
			}else{
				$this->Session->setFlash(__('Please check your username or password'), 'default', array());
				$this->redirect(array('controller'=>'users', 'action'=>'login'));
			}
		}else{
			$this->Session->setFlash(__('Please check your username or password'), 'default', array());
			$this->redirect(array('controller'=>'users', 'action'=>'login'));
		}
	}
/**
 * logout method
 *
 * @return void
 */
	public function logout() {
		$this->redirect($this->Auth->logout());
	}
	
/**
 * logout method
 *
 * @return void
 */
	public function service_login() {
		//$this->redirect();
		$response = array();
		$response['error'] = 3;
		$response['timeSlice'] = TIMESLICE;
		$response['baseUrl'] = Router::url('/', true);
		if ($this->request->is('post')){
			$user = $this->User->find('first', array('conditions'=>array('User.username'=>$this->data['username'], 'User.status'=>ACTIVE)));
			
			if ($user && ($user['User']['password'] == $this->Auth->password($this->data['password'])) ){
			//if ($user && ($user['User']['password'] == $this->Auth->password($this->data['password'])) ){
				if (empty($this->data['imei']) || ($this->data['imei'] != $user['User']['imei']) ){
					$response['message'] = __('Please contact administrator to authorize your device');
				}else {
					$response['error'] = 0;
					unset($user['User']['password']);
					if($user['File']['name']){
						$user['User']['image_url'] =  Router::url('/files/photos/med/' . $user['File']['name'],true); 
					}else{
						$user['User']['image_url'] =  Router::url('/files/photos/med/default.jpg', true); 
					}
					
					$this->loadModel('AppLog');
					$logData = array('input'=>serialize($this->request->data), 'url'=>$this->request->url ) ;
					$this->AppLog->save($logData);
					
					$random_number =  uniqid (rand (),true);
					
					$updateData = array('id'=>$user['User']['id'], 'session_token' => $random_number, 'login_time' => date('Y-m-d H:i:s'));
					if(!empty($this->data['regId'])){
						$user['User']['gcm_regid'] = $updateData['gcm_regid'] = $this->data['regId'];
					}
					
					if(!empty($this->data['app_version'])) {
	                    $user['User']['app_version'] = $updateData['app_version'] = $this->data['app_version'];
                    }
					
					if(!empty($this->data['firebase_token'])){
						$user['User']['firebase_token'] = $updateData['firebase_token'] = $this->data['firebase_token'];
					}

					
					$this->User->save($updateData);
					$user['User']['session_token'] = $random_number;
					$response['data'] = $user;
					$response['token'] = $random_number;
				}
			}else{
				$response['message'] = __('You have enter wrong username or password');
			}
		} else {
			$response['message'] = __('Invalid request');
		}
		
		echo json_encode( $response );
		exit;
	}
	
	public function auto_login($token=''){
		if($token){
			$user = $this->User->find('first', array('conditions'=>array('User.session_token'=>$token)));
			$userData = $user['User'];
			unset($user['User']);
			$userInfo = $userData + $user;
			if ($userInfo){
				$this->Auth->login($userInfo);
				$this->redirect($this->Auth->redirectUrl());
			}else{
				$this->Session->setFlash(__('Invalid request'), 'default', array());
			}
		}else{
			$this->redirect(array('action'=>'login'));
		}
		
	}
	public function declined() {
		$this->render('/Errors/access_denied');
	}
	/**
     * index method
     *
     * @return void
     */
	public function index(){
		
		
		
		
		
	//	$this->gradPermission(4);
		$conditions = array('User.status' => ACTIVE);;
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['User.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['User.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if ( !empty($this->request->query['r'])){
			$conditions['User.role_id'] = $this->request->query['r'];
		}
		if ( !empty($this->request->query['st'])){
			$conditions['User.state_id'] = $this->request->query['st'];
		}
		if ( !empty($this->request->query['dv'])){
			$conditions['User.division_id'] = $this->request->query['dv'];
		}
		if ( !empty($this->request->query['rg'])){
			$conditions['User.region_id'] = $this->request->query['rg'];
		}
		if ( !empty($this->request->query['dp'])){
			$conditions['User.depot_id'] = $this->request->query['dp'];
		}
		$this->_userRoleConditions($conditions);
		$order=$this->paginate['order'] = array('User.first_name' => 'asc', 'User.last_name'=>'asc');
		$querystring = $this->request->query;
		
		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;
			}	
              $users = $this->User->find('all',array('conditions' => $conditions,'order'=>$order, 'limit'=>10000, 'offset'=>$offset));
		}else{
		      $users = $this->paginate('User', $conditions);
		}

		$this->set(compact('querystring','users','offset'));

		$this->_options();
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'Users');
			   $this->render('export_users','export_xls');
		}
		
	}
	/**
     * add method
     *
     * @return void
     */
	public function add(){
	//	$this->gradPermission(1);
		if($this->request->data){
			//Upload Image
			if ($this->_uniqueUser($this->request->data)){
				$image_ok = true;
				if (!empty($this->request->data['User']['image']['name'])){
					if ($this->FileUpload->upload($this->request->data['User'],'image')) {
						$this->request->data['User']['file_id'] = $this->FileUpload->fileId;
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					if (!empty($this->request->data['pass'])){
						$this->request->data['User']['password'] = $this->Auth->password($this->request->data['pass']);
					}
					$this->request->data['User']['create_by'] = $this->Auth->user('id');
					$this->User->save($this->request->data);
					$this->Session->setFlash(__('User was added successfully'));
					$this->redirect(array('controller'=>'users', 'action'=>'index'));
				}
			}else{
				$this->Session->setFlash(__('Username already taken, please choose another'));
			}
		}
		
		$this->_options();
	}
	/**
     * edit method
     *
     * @param string $id
     * @return void
     */
	public function edit($id = null){
		$roledata=array(SUPPORT);
		$this->loadModel('Audit');
		AppController::roleBasePermission($roledata);
	//	$this->gradPermission(1);
		$this->User->id = $id;
		$userData = $this->User->read(null, $id);
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
           if ($this->_uniqueUser($this->request->data)){
			$image_ok = true;
			if (!empty($this->request->data['User']['image']['name'])){
				if ($this->FileUpload->upload($this->request->data['User'],'image')) {
					$this->request->data['User']['file_id'] = $uploaded_file_id = $this->FileUpload->fileId;
					if (!empty($this->request->data['User']['oldFile_id'])){
						$this->FileUpload->removeFileId($this->request->data['User']['oldFile_id']);
					}
				} else {
					
					$image_ok = false;
				}
			}
			if ($image_ok){
				if (!empty($this->request->data['User']['oldFile_id']) && $this->request->data['User']['remove_img'] == "1"){
					$this->FileUpload->removeFileId($this->request->data['User']['oldFile_id']);
					if(!isset($uploaded_file_id)){							
						$this->request->data['User']['file_id'] = 0;
					}
				}
				if (!empty($this->request->data['pass'])){
					$this->request->data['User']['password'] = $this->Auth->password($this->request->data['pass']);
				}
				$this->request->data['User']['last_update_by'] = $this->Auth->user('id');
				
				if(!empty($this->request->data['User']['inactive_status']) && $this->request->data['User']['status'] == 0){
					$this->request->data['User']['status'] =$this->request->data['User']['inactive_status'];
				}
				if ($user = $this->User->save($this->request->data)) {
					$this->User->updateCustRegDepot($this->request->data['User'], $user['User']['id']);
					$this->Audit->saveDeletedData($userData['User']['id'], 'User', $this->Auth->user('id') , serialize($userData),'User Has been updated', STATUS_EDIT);
					$this->Session->setFlash(__('The user has been updated'));
					//$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
				}
				
			}
		  }else{
			$this->Session->setFlash(__('Username already taken, please choose another'));
		  }
        } 
		$this->request->data = $this->User->read(null, $id);
		
		unset($this->request->data['User']['Password']);
		$this->_options();
        
		
	}
	/**
     * view method
     *
     * @param int $id
     * @return void
     */
    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('udata', $this->User->read(null, $id));
		
		$this->loadModel('UserTracking');
		$tracking = $this->UserTracking->find('all', array('conditions'=>array('user_id'=>$id, 'tracking_time LIKE' => date('Y-m-d', time()-84600) . '%'), 'order'=>array('tracking_time'=>'desc'), 'limit'=>'8'));
		//pr($tracking);
		
		$endPoint = $startPoint = '';
		if ($tracking){
			$endElm = end($tracking);
			$startPoint = $endElm['UserTracking']['lat'].','.$endElm['UserTracking']['long'];
			$endPoint = $tracking['0']['UserTracking']['lat'].','.$tracking['0']['UserTracking']['long'];
			foreach ($tracking as $track){
				
			}
		}
		$this->set(compact('tracking','startPoint','endPoint'));
		
    }
	/**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
		$this->loadModel('Audit');
	//	$this->gradPermission(1);
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->User->id = $id;
		 $this->User->unbindModelAll();
		$userData = $this->User->read(null,$id);
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
		$data = array('last_update_by' => $this->Auth->user('id'), 'status'=>DELETED );
        if ($this->User->save($data)) {
			$this->Audit->saveDeletedData($id, 'User', $this->Auth->user('id') , serialize($userData),'User Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('User was deleted successfully'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

	function _options(){
		$this->loadModel('Role');
		$roles = $this->Role->getRolesList();
		$this->set(compact('roles'));
		$Opdata = isset($this->request->data['User'] ) ? $this->request->data['User']  : array();
		$this->Option->Options($Opdata, $this->user);
	/*	$this->loadModel('State');
		$this->loadModel('Region');
		$this->loadModel('Depot');
		
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$depots = $this->Depot->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		
		$this->set(compact('roles', 'states', 'regions', 'depots'));*/

	}
	
	/**
     * check unique username method
     * @params : $data (array)
     * @return boolean
     */
	function _uniqueUser($data){
		$conditions = array('User.username' => $data['User']['username']);
		if (!empty($data['User']['id'])){
			$conditions['User.id !='] = $data['User']['id'];
		}
		$is_exist = $this->User->find('count', array('conditions'=>$conditions));
		if($is_exist == 0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
     * roles method
     *
     * @return void
     */

	public function roles(){
		$this->gradPermission(2);
		$this->loadModel('Role');
		$roles = $this->Role->getRolesList( );
		$this->set('roles', $roles);
	}
	
	/**
     * addrole method
     *
     * @return void
     */
	public function addrole(){
	//	$this->gradPermission(1);
		$this->loadModel('Role');
		if ($this->request->data){
			if (!$this->request->data['Role']['parent_id']){
				$this->request->data['Role']['grade'] = 1;
			}elseif(!empty($this->request->data['Role']['parent_id'])){
				$role = $this->Role->find('first', array('conditions'=>array('id'=>$this->request->data['Role']['parent_id'])));
				$this->request->data['Role']['grade'] = $role['Role']['grade']+1;
			}
			$this->Role->save($this->request->data);
			$this->redirect(array('controller'=>'users', 'action'=>'roles'));
		}
		$roles = $this->Role->getrolesList( );
		
		$this->set('roles', $roles);
	}
	
	public function checkuser($id = null){
		$result = array();
		if ($this->request->data['User']['username']){
			if (!preg_match('/^[0-9a-zA-Z-_]+$/', $this->request->data['User']['username'])){
				$result['valid'] = false;
				$result['message'] = __('Username contain only alphanumeric characters and -_');
			}else{
				$conditions = array('User.username'=>$this->request->data['User']['username']);
				if ($id){
					$conditions['User.id !='] = $id;
				}
				
				$is_exist = $this->User->find('count', array('conditions'=>$conditions));
				if($is_exist == 0){
					$result['valid'] = true;
				}else{
					$result['valid'] = false;
					$result['message'] = __('Username already taken, please choose another');
				}
			}
		}
		$this->set('result', $result);
	}
	
	public function getDpUser($depot_id){
		
		$conditions = array('User.depot_id'=>$depot_id);
		$this->paginate['limit'] = 10;
		$this->paginate['order'] = array('User.role_id'=>'asc', 'User.first_name'=>'asc', 'User.last_name'=>'asc');
		$users = $this->paginate('User', $conditions);
		
		$this->set('users', $users);
	}
	
	public function relations(){
		$this->loadModel('UserRelation');
		$data  = array();
		if ($this->request->data){
			//pr($this->request->data);
			$this->UserRelation->deleteAll(array('user_id'=>$this->request->data['User']['user_id']), false);
			if (!empty($this->request->data['member'])){
				foreach ($this->request->data['member'] as $members){
					$data[] = array('user_id'=>$this->request->data['User']['user_id'],'uid2'=>$members);
				}
			}
			if($data){
				
				$this->UserRelation->saveAll($data);
			}
		}
		$users = array();
		$usersList = $this->User->find('all', array('fields'=>array('User.id', 'User.first_name', 'User.last_name', 'Role.name' ), 'conditions'=>array( 'Role.grade < ' => '6', 'User.status'=>ACTIVE), 'order'=>array('User.first_name'=>'asc', 'User.last_name'=>'asc')));
		foreach ($usersList as $ul){
			$users[$ul['User']['id']] = $ul['User']['first_name'].' '.$ul['User']['last_name']. ' ('.$ul['Role']['name'].')';
		}
		$this->set('users', $users);
	}
	
	public function getMembers(){
		if($this->request->data['uId']){
			$uid = $this->request->data['uId'];
			$user = $this->User->findById($this->request->data['uId']);
			//pr($user);
			$conditions = array('Role.grade >=' => $user['Role']['grade']+1,'User.status'=>ACTIVE);
			switch($user['Role']['grade']){
				case 1:
					//$conditions['Role.grade'] = 2; //Gerade 3 is Regianal manager
				break;
				case 2:
					//$conditions['Role.grade'] = 3; //Gerade 3 is Regianal manager
					
				break;
				case 3:
					//$conditions['Role.grade'] = 4; //Gerade 3 is Depot manager
					$conditions['User.region_id'] = $user['User']['region_id']; 
				break;
				case 4:
				default:
					$conditions['User.depot_id'] = $user['User']['depot_id']; 
				break;
			}
			
			$joins = array(array('table'=>'user_relations', 'alias'=>'UserRelation', 'type'=>'left', 'conditions'=>array('User.id = UserRelation.uid2 AND UserRelation.user_id = '.$uid) ));
			
			$members = $this->User->find('all', array('fields'=>array('User.id', 'User.first_name', 'User.last_name', 'Role.name', 'UserRelation.uid2'), 'conditions' => $conditions, 'order'=>array('User.first_name'=>'asc', 'User.last_name'=>'asc' ), 'joins'=> $joins));
			
			$this->set(compact('user', 'members'));
		}
	}
	
	function relationtree(){
	//	$this->gradPermission(1);
		$usersList = $this->User->find('all', array('fields'=>array('User.id', 'User.first_name', 'User.last_name', 'Role.name', 'Role.grade' ), 'conditions'=>array( 'Role.grade < ' => '3','User.status'=>ACTIVE)));
		foreach ($usersList as $ul){
			$users[$ul['Role']['grade']][] = $ul;
		}
		$this->set('users', $users);
	}
	
	function treeMembers(){
		$lavel = $this->request->data['lavel']+1;
		$uid = $this->request->data['uId'];
		
		$joins = array(array('table'=>'user_relations', 'alias'=>'UserRelation', 'type'=>'inner', 'conditions'=>array('User.id = UserRelation.uid2 AND UserRelation.user_id = '.$uid) ));
			
		$users = $this->User->find('all', array('fields'=>array('User.id', 'User.first_name', 'User.last_name', 'Role.name', 'Role.grade' ), 'conditions'=>array( 'Role.grade' => $lavel), 'joins' => $joins));
		
		$this->set('users', $users);
	}
	
	function roleUpdate(){
		$name=$this->request->data['name'];
		$rid=$this->request->data['rid'];		
		$this->loadModel('Role');
		$this->Role->id = $rid;
		$data = array('name'=>$name);
		$this->Role->save($data);
		exit;
		}
		
		//-----------------------------------
function userSalesReport($id=null){
	$this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('udata', $this->User->read(null, $id));
		$this->loadModel('Order');
		
		$conditions = array();
	
		$conditions['User.id'] =  $id;//condition for only selected user
		$this->paginate['order'] = array('Order.order_date' => 'desc');
		$orders = $this->paginate('Order', $conditions);
		$this->set('orders', $orders);
		}		
function userExpenses($id=null){
	$this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('udata', $this->User->read(null, $id));
		$this->loadModel('Expense');
		
		$conditions = array();
	
		$conditions['User.id'] =  $id;//condition for only selected user
		$this->paginate['expense'] = array('Expense.title' => 'desc');
		$expenses = $this->paginate('Expense', $conditions);
		$this->set('expenses', $expenses);
		}
		
	function userCustomer($id=null){
	$this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('udata', $this->User->read(null, $id));
		$this->loadModel('Customer');
		
		$conditions = array();
	
		$conditions['User.id'] =  $id;//condition for only selected user
		$this->paginate['customer'] = array('Customer.first_name' => 'desc');
		$customers = $this->paginate('Customer', $conditions);
		$this->set('customers', $customers);
		}
		//--------------------user track-------
 	 function trackByDepot($id=null, $date=''){
		$conditions = array();
	  	$this->loadModel('User');
		$this->loadModel('UserTracking');
		$this->loadModel('Depot');
		$this->set('udata', $this->Depot->read(null, $id));
		
		$users = $this->User->usersList($id);
		$this->set('users', $users);
		
	  	$this->UserTracking->belongsTo = array('User' => array('className' => 'User', 'foreignKey' => 'user_id', 'type'=>'left', 'fields'=>array('id', 'first_name', 'last_name')));
		if (!empty($this->request->query['us']) ){
			$conditions['UserTracking.user_id'] = $this->request->query['us'];
		}
		$conditions['User.depot_id'] = $id;
		if ($date){
			$conditions['UserTracking.created LIKE '] = $date.'%';
		}else{
			$conditions['UserTracking.created LIKE '] = date('Y-m-d').'%';
		}
		
		
		//$this->paginate = array('limit'=>100);
		
		$usertracking = $this->UserTracking->find('all', array('conditions'=>$conditions, 'order'=>array('UserTracking.id' => 'asc') ));
		//echo count($usertracking);
		$trackData = array();
		foreach($usertracking as $track){
			//pr($track);
			$trackData[$track['User']['id']][] = $track;
		}
		
		$this->set('user_tracking', $trackData);
	  }	
	  
	  function _userRoleConditions(&$conditions){
		$this->user = $this->Auth->user();
		
		switch($this->user['Role']['grade']){
			case 2:
				if($this->user['role_id'] == DIVISIONMANAGER){
					$conditions['User.division_id'] = $this->user['division_id'];
				}				
			break;
			case 3:
				$conditions['User.region_id'] = $this->user['region_id'];
			break;
			case 4:
				$conditions['User.depot_id'] = $this->user['depot_id'];
			break;
			case 5:
			case 6:
				$conditions['User.id'] = $this->user['id'];
			break;
		}
	  }
	  
	  
	/*   function saleActivity($opt=''){
	//	$this->gradPermission(4);
		$date = date('Y-m');
		
		$date = ($opt)?$opt:$date;
		$strtotime = strtotime($date);
		$prev = date('Y-m', strtotime('-1 month', $strtotime) );
		$next = date('Y-m', strtotime('+1 month', $strtotime) );
		$current = date('M, Y', $strtotime);
		
		$conditions = array('Sale.sale_date LIKE "'.$date.'%"', 'User.status'=>ACTIVE);
		//Role based conditions
		$this->_userRoleConditions($conditions);
		$params = array();
		//$params['date'] = $date; 
		//$joins = array(array('table'=>'sales', 'alias'=>'Sale', 'type'=>'left', 'conditions' => array('User.id = Sale.user_id')));
		// $joins = array(array('table'=>"(SELECT user_id, cal_qty, sale_date, amount FROM sales WHERE sale_date LIKE  '$date%' UNION  SELECT user_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE sale_date LIKE  '$date%' UNION SELECT user_id, cal_qty, sale_date, amount FROM consumer_sales WHERE sale_date LIKE  '$date%' UNION  SELECT user_id, cal_qty, sale_date, amount FROM consumer_redistribution_sales WHERE sale_date LIKE  '$date%')", 'alias'=>'Sale', 'type'=>'left', 'conditions' => array('User.id = Sale.user_id'))); //
		
		$joins = array(array('table'=>"(SELECT user_id, cal_qty, sale_date, amount FROM sales WHERE sale_date LIKE  '$date%' UNION ALL SELECT user_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE sale_date LIKE  '$date%' UNION ALL SELECT user_id, cal_qty, sale_date, amount FROM consumer_sales WHERE sale_date LIKE  '$date%' UNION ALL SELECT user_id, cal_qty, sale_date, amount FROM consumer_redistribution_sales WHERE sale_date LIKE  '$date%')", 'alias'=>'Sale', 'type'=>'left', 'conditions' => array('User.id = Sale.user_id')));
		
		//$fields = array('User.id', 'User.first_name', 'User.last_name', '(IFNULL(SUM(Sale.cal_qty),0) + IFNULL((SELECT SUM(cal_qty) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0)) AS total_sale', '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0)) AS total_amount');

		// $fields = array('User.id', 'User.first_name', 'User.last_name', 'SUM(Sale.cal_qty) AS total_sale', 'SUM(Sale.amount) AS total_amount'); //
		
		$fields = array('User.id', 'User.first_name', 'User.last_name', '(IFNULL(SUM(Sale.cal_qty),0) + IFNULL((SELECT SUM(cal_qty) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0) + IFNULL((SELECT SUM(cal_qty) FROM consumer_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0) + IFNULL((SELECT SUM(cal_qty) FROM consumer_redistribution_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0)) AS total_sale',  '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0) + IFNULL((SELECT SUM(amount) FROM consumer_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0) + IFNULL((SELECT SUM(amount) FROM consumer_redistribution_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0)) AS total_amount');
		
		
		$this->User->unbindModelAll();
		
		$this->User->virtualFields['total_amount'] = 'SUM(Sale.amount)';
		
		$this->paginate['fields'] = $fields;
		$this->paginate['group'] = array('User.id');
		$this->paginate['order'] = array('total_amount'=>'desc', 'total_sale'=>'desc');
		$this->paginate['joins'] = $joins;
		$users = $this->paginate('User', $conditions);
		//$users = $this->User->find('all', array('fields'=>$fields, 'conditions'=>$conditions, 'order'=>array('total_amount'=>'desc'), 'joins'=>$joins, 'group'=>array('Sale.user_id')));
		//Custom paging
		//$this->paginate['model'] = 'user';
		//$this->paginate['date'] = $date;
		//$this->paginate['user'] = $this->user; 
		//$this->loadModel('SaleActivity');
		///$users = $this->paginate('SaleActivity', $conditions);
		
		if ($users){
			$this->User->saleActivity($users, compact('date', 'prev', 'next', 'current'));
		} //pr($users);
		
		//$this->loadModel('Brand');
		$brands = $this->Brand->find('list',  array('fields'=>array('id', 'name'))); //
		$this->loadModel('BrandGroup');
		$brands = $this->BrandGroup->find('list',  array('fields'=>array('id', 'name')));
		
		$this->set(compact('users', 'brands', 'date', 'prev', 'next', 'current','strtotime'));
		if(!$this->request->is('ajax')){
			$this->render('sale_activity_report');
		}
		
	} */
	
	
	function _nav_params($type, $opt){
        switch($type){
            case 'daily':
                $date = ($opt)?$opt:date('Y-m-d');
                $strtotime = strtotime($date);
                $prev = date('Y-m-d', strtotime('-1 day', $strtotime) );
                $next = date('Y-m-d', strtotime('+1 day', $strtotime) );
                $current = date('M d, Y', $strtotime);
                break;
            case 'weekly':
                $date = ($opt)?$opt:date('Y-m-d');
                $strtotime = strtotime('monday this week', strtotime($date));
                $prev = date('Y-m-d', strtotime('-1 week', $strtotime) );
                $next = date('Y-m-d', strtotime('+1 week', $strtotime) );
                $current = __('From %s to %s', strftime('%b %d, %Y', $strtotime), strftime('%b %d, %Y', strtotime('+6 days', $strtotime)));
                break;

            case 'between':
                //$date = $this->request->query['from'];
                if (!empty($this->request->query['from'])){
                    $date = $this->request->query['from'];
                }else{
                    //$date = date('Y-m-d');
                    $date = date('Y-m-d', strtotime('-1 day', strtotime($this->request->query['to'])));
                }

                if (!empty($this->request->query['to'])){
                    $date2 = $this->request->query['to'];
                }else{
                    $date2 = date('Y-m-d');
                }
                $strtotime = strtotime($date);
                $prev = ''; //date('Y-m-d', strtotime('-1 week', $strtotime) );
                $next = ''; // date('Y-m-d', strtotime('+1 week', $strtotime) );
                $current = __('From %s to %s', strftime('%b %d, %Y', $strtotime), strftime('%b %d, %Y', strtotime($date2)));
                break;
            case 'monthly':
                $date = ($opt)?$opt:date('Y-m-01');
                $strtotime = strtotime($date);
                $prev = date('Y-m', strtotime('-1 month', $strtotime) );
                $next = date('Y-m', strtotime('+1 month', $strtotime) );
                $current = date('M, Y', $strtotime);
                break;
        }
        $this->set(compact('date', 'strtotime', 'prev', 'next', 'current'));
        return compact('date', 'strtotime', 'prev', 'next', 'current');
    }

	function saleActivity($type='monthly', $opt=''){
	//	$this->gradPermission(4);
        if($type=='daily' || $type=='weekly' ){
            $date = date('Y-m-d');
        }else{
		    $date = date('Y-m');
        }

		$date = ($opt)?$opt:$date;
//

        $conditions = array('User.status'=>ACTIVE);
        $saConditions[] = 'Sale.user_id=User.id';
        $total_amt_cond ='1 ';

        $query = $this->request->query;//pr($this->request);exit;
        if($type=='weekly' && (empty($query['from']) && empty($query['to']) )){
            $strtotime = strtotime('monday this week', strtotime($date));
            $d1 = date('Y-m-d', $strtotime);
            $d2 =  date('Y-m-d', strtotime('+6 days', $strtotime));
            $total_amt_cond .= " AND sale_date between '".$d1."' AND '".$d2."' ";
            $conditions[] = "Sale.sale_date between '".$d1."' AND '".$d2."' ";
        }elseif (($type=='daily' || $type=='monthly') && (empty($query['from']) && empty($query['to']) )){
            $total_amt_cond .= " AND sale_date LIKE  '$date%'";
            $conditions[] = 'Sale.sale_date LIKE "'.$date.'%"';
        }

        if(!empty($query['from']) || !empty($query['to']) ){
            if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
                $total_amt_cond .= ' AND sale_date BETWEEN "'.$this->request->query['from'].'" AND "'.$this->request->query['to'].'"';
                $conditions[] = 'Sale.sale_date between "'.$this->request->query['from'].'" AND "'.$this->request->query['to'].' "';
            } elseif (!empty($this->request->query['from'])){
                $total_amt_cond .= ' AND sale_date >= "'.$this->request->query['from'].'"';
                $conditions[] = 'Sale.sale_date >= "'.$this->request->query['from'].'"';
            } elseif (!empty($this->request->query['to'])){
                $d1 = date('Y-m-d', strtotime('-1 day', strtotime($this->request->query['to'])));
//                $total_amt_cond .= ' AND sale_date <= "'.$this->request->query['to'].'"';
//                $conditions[] = 'Sale.sale_date <= "'.$this->request->query['to'].'"';
                $total_amt_cond .= ' AND sale_date BETWEEN "'.$d1.'" AND "'.$this->request->query['to'].'"';
                $conditions[] = 'Sale.sale_date between "'.$d1.'" AND "'.$this->request->query['to'].' "';
            }
            $type = 'between';
        }else{
            $type = isset($type) ? $type : 'monthly';
        }

        $navParams = $this->_nav_params($type, $opt);
        $strtotime = $navParams['strtotime'];
        $prev = $navParams['prev'];
		$next = $navParams['next'];
		$current = $navParams['current'];

        $this->loadModel('Region');
        $this->loadModel('Depot');
        if (!empty($this->request->query['rg'])){
            $region_id = $this->request->query['rg'];
        }else{
            $region_id = 0;
            if(!empty($this->user['region_id']) && $this->user['Role']['grade'] >=3){
                $this->request->query['rg'] = $region_id = $this->user['region_id'];
            }
        }
        if(!empty($this->user['depot_id']) && $this->user['Role']['grade'] >=4){
            $this->request->query['dp'] = $this->user['depot_id'];
        }
        $regions = $this->Region->getList();
        $depots = $this->Depot->getList($region_id);


        if (!empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
            if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
//                $region_id = $this->request->query['rg'];
                $total_amt_cond .=' AND depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
            if (!empty($this->request->query['dp'])){
                $depot_id = $this->request->query['dp'];
                $total_amt_cond .=' AND depot_id='.$this->request->query['dp'];
            }
        }

        if (!empty($this->request->query['brand_group_id'])){
          $brand_group_id = $this->request->query['brand_group_id'];
            $conditions[] = 'Sale.brand_group_id='.$brand_group_id;
          //$saConditions[] = 'Sale.brand_group_id='.$brand_group_id;
          $total_amt_cond .= ' AND brand_group_id='.$brand_group_id;
          //pr($saConditions);exit;
        }
        if (!empty($this->request->query['user_id'])){
          $user_id = $this->request->query['user_id'];
            $conditions[] = 'Sale.user_id='.$user_id;
          //$saConditions[] = 'Sale.user_id='.$user_id;
          $total_amt_cond .= ' AND user_id='.$user_id;
          //pr($saConditions);exit;
        }



		//Role based conditions
		$this->_userRoleConditions($conditions);
		$params = array();
		//$params['date'] = $date;
		//$joins = array(array('table'=>'sales', 'alias'=>'Sale', 'type'=>'left', 'conditions' => array('User.id = Sale.user_id')));
		/* $joins = array(array('table'=>"(SELECT user_id, cal_qty, sale_date, amount FROM sales WHERE sale_date LIKE  '$date%' UNION  SELECT user_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE sale_date LIKE  '$date%' UNION SELECT user_id, cal_qty, sale_date, amount FROM consumer_sales WHERE sale_date LIKE  '$date%' UNION  SELECT user_id, cal_qty, sale_date, amount FROM consumer_redistribution_sales WHERE sale_date LIKE  '$date%')", 'alias'=>'Sale', 'type'=>'left', 'conditions' => array('User.id = Sale.user_id'))); */

        $joins = array(array('table'=>"(SELECT user_id,brand_group_id,  cal_qty, sale_date, amount FROM sales WHERE   $total_amt_cond  UNION ALL SELECT user_id,brand_group_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE   $total_amt_cond UNION ALL SELECT user_id,brand_group_id, cal_qty, sale_date, amount FROM consumer_sales WHERE   $total_amt_cond UNION ALL SELECT user_id,brand_group_id, cal_qty, sale_date, amount FROM consumer_redistribution_sales WHERE   $total_amt_cond)", 'alias'=>'Sale', 'type'=>'left', 'conditions' => $saConditions));

        //pr($joins);exit;
		//$fields = array('User.id', 'User.first_name', 'User.last_name', '(IFNULL(SUM(Sale.cal_qty),0) + IFNULL((SELECT SUM(cal_qty) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0)) AS total_sale', '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%"),0)) AS total_amount');

		/* $fields = array('User.id', 'User.first_name', 'User.last_name', 'SUM(Sale.cal_qty) AS total_sale', 'SUM(Sale.amount) AS total_amount'); */
		
//		$fields = array('User.id', 'User.first_name', 'User.last_name', '(IFNULL(SUM(Sale.cal_qty),0) + IFNULL((SELECT SUM(cal_qty) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%" '.$total_amt_cond.'),0) + IFNULL((SELECT SUM(cal_qty) FROM consumer_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%" '.$total_amt_cond.'),0) + IFNULL((SELECT SUM(cal_qty) FROM consumer_redistribution_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%" '.$total_amt_cond.'),0)) AS total_sale',  '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%" '.$total_amt_cond.'),0) + IFNULL((SELECT SUM(amount) FROM consumer_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%" '.$total_amt_cond.'),0) + IFNULL((SELECT SUM(amount) FROM consumer_redistribution_sales WHERE user_id = Sale.user_id AND sale_date LIKE "'.$date.'%" '.$total_amt_cond.'),0)) AS total_amount');
        $fields = array('User.id', 'User.first_name', 'User.last_name', '(IFNULL(SUM(Sale.cal_qty),0) ) AS total_sale',  '(IFNULL(SUM(Sale.amount),0) ) AS total_amount');
		
		$this->User->unbindModelAll();
		
		$this->User->virtualFields['total_amount'] = 'SUM(Sale.amount)';
		
		$this->paginate['fields'] = $fields;
		$group=$this->paginate['group'] = array('User.id');
		$order=$this->paginate['order'] = array('total_amount'=>'desc', 'total_sale'=>'desc');
		$this->paginate['joins'] = $joins;
		
		$querystring = $this->request->query;
		
		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;
			}	
             $users = $this->User->find('all',array('fields' => $fields,'conditions' => $conditions,'joins'=>$joins,'order'=>$order, 'limit'=>10000, 'offset'=>$offset,'group'=>$group));
		}else{
		      $users = $this->paginate('User', $conditions);
		}

		
		
		//$users = $this->User->find('all', array('fields'=>$fields, 'conditions'=>$conditions, 'order'=>array('total_amount'=>'desc'), 'joins'=>$joins, 'group'=>array('Sale.user_id')));
		//Custom paging
		//$this->paginate['model'] = 'user';
		//$this->paginate['date'] = $date;
		//$this->paginate['user'] = $this->user; 
		//$this->loadModel('SaleActivity');
		///$users = $this->paginate('SaleActivity', $conditions);
        $brand_group_id = isset($brand_group_id) ? $brand_group_id : false;
        $region_id = isset($region_id) ? $region_id : false;
        $depot_id = isset($depot_id) ? $depot_id : false;

        $params = array_merge($navParams, compact('query','type','region_id','depot_id','date', 'prev', 'next', 'current','brand_group_id'));

		if ($users){
			$this->User->saleActivity($users, $params);
		} //pr($users);
		
		/* $this->loadModel('Brand');
		$brands = $this->Brand->find('list',  array('fields'=>array('id', 'name'))); */
		$this->loadModel('BrandGroup');
		$brands = $this->BrandGroup->find('list',  array('fields'=>array('id', 'name')));

		//pr($brands);exit;

        $this->user = $this->Auth->user();
        $userAvail = $this->User->usersListByRole($this->user);
		
		$this->set(compact('regions', 'depots', 'users', 'type', 'offset', 'querystring','userAvail', 'brands', 'date', 'prev', 'next', 'current','strtotime'));
		if(!$this->request->is('ajax')){
			if(isset($this->request->query['export'])){ 
				$this->set('filename', 'saleActivity');
				$this->render('sale_activity_report_export','export_xls');
			}else{
				$this->render('sale_activity_report');
			}
		}
		
	}
	
	public function customerCount(){
		$this->user = $this->Auth->user();
		$this->User->unbindModel(array('belongsTo'=>array('State', 'Region', 'File')));
		$joins = array(
				array('table'=>'customers', 'alias'=>'Customer', 'type'=>'left', 'conditions'=>array('User.id = Customer.user_id'))
			);
		$fields = array('User.id', 'User.first_name', 'User.last_name', 'Depot.title', 'Role.name', 'COUNT(Customer.id) AS total_customer');
		$conditions = array('User.status'=>ACTIVE);
		
		if($this->user['Role']['grade'] > 1){
			$conditions['User.role_id >='] = $this->user['role_id'];
		}
		//$users = $this->User->find('all', array( 'fields'=>$fields, 'joins'=>$joins, 'group'=>array('User.id'), 'order'=>array('total_customer'=>'desc')));
		$this->User->virtualFields['total_customer'] = 'COUNT(Customer.id)';
		$this->paginate['joins'] = $joins;
		$this->paginate['order'] = array('total_customer'=>'desc');
		$this->paginate['fields'] = $fields;
		$this->paginate['group'] = array('User.id');
		$this->_userRoleConditions($conditions);
		$users = $this->paginate('User',$conditions);
		$this->set('users', $users);
		
		if(!$this->request->is('ajax')){
			$this->render('customer_count_report');
		}
	}
	
	public function visits(){
		//$this->gradPermission(4);
		$conditions = array('User.status =' => ACTIVE);
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['User.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['User.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		
		
		$oC = $vC = $rdC = '';
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$d1 = $this->request->query['from'];
			$d2 = $this->request->query['to'].' 23:59:59';
			$oC = " AND Order.order_date BETWEEN '$d1' AND '$d2'";
			$vC = " AND visiting_date BETWEEN '$d1' AND '$d2'";
			$rdC = " AND sale_date BETWEEN '$d1' AND '$d2'";
		}elseif (!empty($this->request->query['from'])){
			$d1 = $this->request->query['from'];
			
			$oC = " AND Order.order_date  >= '$d1'";
			$vC = " AND visiting_date  >= '$d1'";
			$rdC = " AND sale_date >= '$d1'";
			
		} elseif (!empty($this->request->query['to'])){
			
			$d1 = $this->request->query['to'].' 23:59:59';
			$oC = " AND Order.order_date  <= '$d1'";
			$vC = " AND visiting_date <= '$d1'";
			$rdC = " AND sale_date <= '$d1'";
		}
		$this->User->unbindModelAll();
		
		//$this->paginate['fields'] = array("User.id", "User.first_name", "User.last_name", "(COUNT(Order.id) + (SELECT COUNT(id) FROM customer_visits WHERE user_id = User.id $vC) + (SELECT COUNT(id) FROM redistributor_sales WHERE user_id = User.id $rdC ) ) AS totVisits");
		
		$this->paginate['fields'] = array("User.id", "User.first_name", "User.last_name", "COUNT(CustomerVisit.id) AS totVisits");
		
		$this->paginate['joins'] = array(array('table'=>'customer_visits', 'alias'=>'CustomerVisit', 'type'=>'left', 'conditions'=>array('User.id=CustomerVisit.user_id '.$vC)));
		$this->paginate['group'] = 'User.id';
		$this->User->virtualFields['totVisits'] = 'COUNT(CustomerVisit.id)';
		if( !empty($this->request->params['named']['sort']) && $this->request->params['named']['sort'] == 'totVisits' ){
			$this->paginate['order'] = 'totVisits '.$this->request->params['named']['direction'];
		}else{
			$this->paginate['order'] = 'totVisits desc';
		}
		
		$this->_userRoleConditions($conditions); 
		$users = $this->paginate('User', $conditions);
		
		$this->set('users', $users);
		if($this->request->is('ajax')){
			$this->render('visits_dashboard');
		}
	}

	public function deleteAllUsers(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			$userids=explode(",", $this->request->data['deleteAllValue']);
			$users_ids = array();
				foreach($userids as $duid){
					$this->User->id = $duid; 
					$data = array('last_update_by' => $this->Auth->user('id'), 'status'=>DELETED );
					
					$this->User->save($data); 
					//$this->User->saveField('status', DELETED); 
				  
				}
			/*$this->User->updateAll(
				array('User.status' => DELETED),
				array('User.id' => $users_ids)
			);
			*/
			//$this->User->deleteAll(array('User.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Users was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}

	public function calendardata(){
		$this->Calendar->addEvent('event 1');
		$this->Calendar->addEvent('event 2', 10);
		$this->Calendar->addEvent('event 3', 10, 10);
		$this->Calendar->addEvent('event 4', 10, 10, 10);
		$calendardata = $this->Calendar->makeCalendar();
		$this->set(compact('calendardata'));
		$this->Calendar->makeEvents();
	}

	public function targets(){
		$this->loadModel('UserTarget');
		$cDate = date('Y-m-d');
		$cDateArr = explode("-", $cDate);
		if(!empty($this->request->query['yr'])){
			$year = $this->request->query['yr'];
		}else{
			$year = $cDateArr['0'];
		}
		if(!empty($this->request->query['month'])){
			$month = $this->request->query['month'];
		}else{
			$month = $cDateArr['1'];
		}
		//$conditions = array('UserTarget.year'=>$year, 'UserTarget.month'=>$month);
		$conditions = array();
		if (!empty($this->request->query['q']) ){
					$conditions['User.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
				}
		if(!empty($this->request->query['tt'])){
			$conditions['UserTarget.type']  = $this->request->query['tt'];
		}
		
		
		/* $this->UserTarget->belongsTo = array('User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('id', 'first_name', 'last_name'), 'type'=>'Left') );
		$this->UserTarget->belongsTo = array('BrandGroup' => array('className' => 'BrandGroup', 'foreignKey' => 'brand_group_id', 'fields' => array('id', 'name'), 'type'=>'Left') ); */
		
		$this->paginate['order'] = array('UserTarget.id' => 'desc');
		$targets = $this->paginate('UserTarget', $conditions); //pr($targets);
		$this->set(compact('targets','year','month'));
	}
	public function updatetarget($type = 'Call', $id = null){
		
		
		$date = date('Y-m-d');
		$dateArray = explode('-', $date); 
		$this->loadModel('UserTarget');
		$this->loadModel('Audit');
		$userData = $this->UserTarget->read(null, $id);
		if ($this->data){
			//pr($this->data);die();
			//Check for unique
			$user_id = $this->data['UserTarget']['user_id'];
			$depot_id = $this->User->field('depot_id', array('User.id'=>$user_id) );
			$conditions = array('user_id'=>$user_id, 'UserTarget.depot_id'=>$depot_id, 'type'=>$this->data['UserTarget']['type'], 'brand_group_id'=>$this->data['UserTarget']['brand_group_id'] );
			
			if(!empty($this->data['UserTarget']['id'])){
				$conditions['UserTarget.id !='] = $this->data['UserTarget']['id'];
			}
			$is_added = $this->UserTarget->find('count', array('conditions'=>$conditions));
			if ($is_added  > 0){
				$this->Session->setFlash(__('This entry already exists'));
			}else{
				$this->request->data['UserTarget']['added_by'] = $this->Auth->user('id');
				$this->request->data['UserTarget']['depot_id'] = $depot_id;
				if ($this->data['UserTarget']['type'] == 'Call' || $this->data['UserTarget']['type'] == 'Sale' || $this->data['UserTarget']['type'] == 'Redistribution'){
					$this->request->data['UserTarget']['target'] = serialize($this->request->data['target']);
				}
				/* if ($this->data['UserTarget']['type'] == 'Sale' ){
					$this->request->data['UserTarget']['target'] = serialize($this->request->data['target']);
				} */
				//pr($this->request->data);die();
				//pr($this->data);
				$this->UserTarget->save($this->request->data);
				$this->Audit->saveDeletedData($userData['UserTarget']['id'], 'UserTarget', $this->Auth->user('id') ,serialize($userData),'User Target Has been Updated', STATUS_EDIT);
				$this->Session->setFlash(__('Target was Saved successfully'));
				$this->redirect(array('controller'=>'users', 'action'=>'targets', $type ) );
			}
		}
		$users = $this->User->usersList();
		$this->loadModel('BrandGroup');
		$groups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		//$months =
		if ($id){
			$this->request->data = $this->UserTarget->read(null, $id);
		}
		$this->set(compact('users','months','dateArray','type','id','groups'));
	}
	
	public function deletetarget($id = null){
		$this-> loadModel('Audit');
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		//pr($this->request);
		if ($id){
			$this->loadModel('UserTarget');
			$data = array();
			$usertarget = $this->UserTarget->find('first', array('conditions' => array('md5(UserTarget.id)' => $id )));
			 $data['serialize'] = serialize($usertarget);//pr($data['serialize']);die();
			 $data['model_id'] = $usertarget['UserTarget']['id'];
			if($this->UserTarget->deleteAll(array('md5(id)'=>$id), false)){ 
				$this->Audit->saveDeletedData($data['model_id'], 'UserTarget', $this->Auth->user('id') , $data['serialize'],'User Target Has been Deleted', STATUS_DELETE);
				$this->Session->setFlash(__('Target was deleted'));
			}
			$this->redirect(array('controller'=>'users','action' => 'targets'));
		}
	}
	
}  
