<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class CustomersController extends AppController {	
	var $components = array('FileUpload' => array(
							'allow_non_image_files' => false
						),'Option');
						
	function beforeFilter(){
        $this->user = $this->Auth->user();
    }					
/**
 * Controller name
 *
 * @var string
 */
	
	 public function verifieddate(){ 
		$this->autoRender = false;
		//265, 162, 86, 335, 336, 293, 232, 4, 42, 27, 51, 194, 49, 272, 48
		$uid = array(265, 162, 86, 335, 336, 293, 232, 4, 42, 27, 51, 194, 49, 272, 48);
		//$uid =265;
		/* $custs = $this->Customer->find('all', array('fields'=>array('id','verified_latitude','verified_longitude'),'conditions'=>array('verified_by' => $uid, 'verified_date'=>null))); pr(count($custs)); //pr($custs); */
		
		$custs = $this->Customer->find('all', array('fields'=>array('id','verified_latitude','verified_longitude','verified_by'),'conditions'=>array('verified_latitude NOT' => null, 'verified_longitude NOT'=>null, 'verified_date'=>null))); pr(count($custs)); //pr($custs);
		
		/* $this->loadModel('CustomerVisit');
		foreach($custs as $cust){
			$data[] = $this->CustomerVisit->find('all',array('fields'=>array('id','customer_id','visiting_date','user_id',),'conditions'=>array('CustomerVisit.customer_id'=>$cust['Customer']['id'],'CustomerVisit.latitude'=>$cust['Customer']['verified_latitude'], 'CustomerVisit.longitude'=>$cust['Customer']['verified_longitude'], 'CustomerVisit.visiting_date >'=>'2019-09-01 00:00:00')));			
		} */  
		
		$this->loadModel('Order');
		foreach($custs as $cust){
			$data[] = $this->Order->find('all',array('fields'=>array('id','customer_id','order_date','user_id',),'conditions'=>array('Order.customer_id'=>$cust['Customer']['id'],'Order.latitude'=>$cust['Customer']['verified_latitude'], 'Order.longitude'=>$cust['Customer']['verified_longitude'], 'Order.order_date >'=>'2019-09-01 00:00:00')));			
		}  
		 
		
	/* 	$this->loadModel('RedistributorSale');
		$this->RedistributorSale->unbindModel(array('hasMany' => array('RedistributorSaleItem')));
		foreach($custs as $cust){
			$data[] = $this->RedistributorSale->find('all',array('fields'=>array('id','customer_id','sale_date','user_id',),'conditions'=>array('RedistributorSale.customer_id'=>$cust['Customer']['id'],'RedistributorSale.latitude'=>$cust['Customer']['verified_latitude'], 'RedistributorSale.longitude'=>$cust['Customer']['verified_longitude'])));			
		}   */
		
		/* $this->loadModel('Incentive');
		foreach($custs as $cust){
			$data[] = $this->Incentive->find('all',array('fields'=>array('customer_id','incentive_date','user_id'),'conditions'=>array('Incentive.customer_id'=>$cust['Customer']['id'],'Incentive.latitude'=>$cust['Customer']['verified_latitude'], 'Incentive.longitude'=>$cust['Customer']['verified_longitude'])));			
		} */
		
		pr(count($data)); //pr($data); 
		
		/* foreach($data as $i=>$d){ 

			if(!empty($d[0]['Incentive']['customer_id'])){
				$up[$i]['id'] = $d[0]['Incentive']['customer_id'];
				$up[$i]['verified_date'] = date('Y-m-d', strtotime($d[0]['Incentive']['incentive_date']));
				$up[$i]['verified_by'] = $d[0]['Incentive']['user_id'];
			}
		} */

		pr(count($up)); pr($up);  
		
		//$cdata = $this->Customer->saveAll($up); pr(count($cdata));pr($cdata);

	} 
	
	/* public function verifiedby(){
		$this->autoRender = false;
		$uid = array(265, 162, 86, 335, 336, 293, 232, 4, 42, 27, 51, 194, 49, 272, 48);
		
		//$uid = 265;
		
		$this->loadModel('CustomerVisit');
		$cvs = $this->CustomerVisit->find('all', array('fields'=>array('customer_id','latitude','longitude','user_id','visiting_date'),'conditions'=>array('CustomerVisit.user_id' => $uid))); //pr(count($cvs)); 
		
		foreach($cvs as $cv){
			$data[$cv['CustomerVisit']['user_id']][] = $this->Customer->find('all',array('fields'=>array('id','verified_date','verified_by',),'conditions'=>array('Customer.id'=>$cv['CustomerVisit']['customer_id'],'Customer.verified_latitude'=>$cv['CustomerVisit']['latitude'], 'Customer.verified_longitude'=>$cv['CustomerVisit']['longitude'],'Customer.verified_date'=>date('Y-m-d', strtotime($cv['CustomerVisit']['visiting_date'])), 'Customer.verified_by NOT' => $cv['CustomerVisit']['user_id'])));
			
		}
		
		//pr(count($data)); pr($data); 
		
	 	foreach($data as $uid=>$ds){ 
			foreach($ds as $i=>$d){
				if(!empty($d)){	
					$up[$i]['id'] = $d[0]['Customer']['id'];
					//$up[$i]['verified_date'] = date('Y-m-d', strtotime($d[0]['RedistributorSale']['sale_date']));
					$up[$i]['verified_by'] = $uid;
				}
			}
		}
		
		pr(count($up)); pr($up);
		//$cdata = $this->Customer->saveAll($up); pr(count($cdata));pr($cdata);
	} */
	
	public function cust_index(){  
	
	
		
		/* $conditions = array('Customer.status !=' => DELETED); */
		$conditions = array('Customer.status' => ACTIVE);
		if(isset($this->request->query['verified']) && strlen($this->request->query['verified']) > 0){
			if ($this->request->query['verified'] == 1 ){
			
				$order=$this->paginate['order'] = array('Customer.verified_date' => 'desc','Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');
				
				$conditions['Customer.verified_latitude NOT'] = null;
				$conditions['Customer.verified_longitude NOT'] = null;
				
				if (!empty($this->request->query['usr']) ){
					$conditions['Customer.verified_by'] = $this->request->query['usr'];
				}
				
				if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
					$conditions[] = array('Customer.verified_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
				}elseif (!empty($this->request->query['from'])){
					$conditions['Customer.verified_date >= '] = $this->request->query['from'];
				} elseif (!empty($this->request->query['to'])){
					$conditions['Customer.verified_date <= '] = $this->request->query['to'];
				}
				
			}else{
				$conditions['Customer.verified_latitude'] = null;
				$conditions['Customer.verified_longitude'] = null;
			}
		}else{
			
			$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
			
			if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
				$conditions[] = array('Customer.created BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
			}elseif (!empty($this->request->query['from'])){
				$conditions['Customer.created >= '] = $this->request->query['from'];
			} elseif (!empty($this->request->query['to'])){
				$conditions['Customer.created <= '] = $this->request->query['to'];
			}
			
			if (!empty($this->request->query['usr']) ){
				$conditions['Customer.user_id'] = $this->request->query['usr'];
			}
		}
		
		
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['Customer.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['Customer.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if ( !empty($this->request->query['dv'])){
            $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		
		$conditions['Customer.first_name NOT'] = null;
		$conditions['Customer.last_name NOT'] = null;
		
		
		
		
		//$this->Customer->_userCondition($conditions, $this->user);
		$this->Customer->_userRoleCondition($conditions, $this->user, $this->paginate);
		$joins =  array();
		$joins = isset($this->paginate['joins'])?$this->paginate['joins']:array();
		

		$querystring = $this->request->query;
	   // pr($conditions);
		if(isset($this->request->query['export'])){  			
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}	
			/* $conditions['Customer.verified_by NOT']=null;
			$conditions['Customer.verified_date']=null; */
			//$conditions['Customer.verified_by'] = null;
			
			$customers = $this->Customer->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins, 'limit'=>10000, 'offset'=>$offset));
		}else {
		    $customers = $this->paginate('Customer', $conditions);	  
		}
		//pr($customers);
		
		if(!empty($customers)){
			$cust_ids = array();
			foreach($customers as $customer){
				array_push($cust_ids, $customer['Customer']['id']);
			}
			
			$lastVisitData = $this->Customer->customerLastVisit($cust_ids);	//pr($lastVisitData);
		}
        $this->set(compact('querystring','customers','offset', 'lastVisitData'));

		$Opdata =  array();
		$param = isset($querystring ) ? $querystring  : array();

		$this->Option->Options($Opdata, $this->user, $param);

		$this->loadModel('User');
		
		/* $users = $this->User->usersListByRole($this->user); */
		
		/*** usersListByRole($user, $isService=false, $varified=false) ***/
		$users = $this->User->usersListByRole($this->user, false, true);
		
			
		$this->set(compact('users'));
		
		//$this->_selectOptions();
		if(isset($this->request->query['export'])){
			if (!empty($this->request->query['verified']) ){
			$this->set('filename', 'verified_customers');
			}else{
				$this->set('filename', 'customers');
			}
			$this->render('export_customer','export_xls');
		}
		
		$this->render('index');
	}
	
	public function index(){ 

//pr($this->Auth->user());
		/* $conditions = array('Customer.status !=' => DELETED); */
		
		$userCond = array();
		$conditions = array(
			'Customer.status' => ACTIVE,
			'Customer.first_name IS NOT NULL',
			'Customer.last_name IS NOT NULL'
		);
		
		if(isset($this->request->query['verified']) && strlen($this->request->query['verified']) > 0){
			if ($this->request->query['verified'] == 1 ){
			
				$order=$this->paginate['order'] = array('Customer.verified_date' => 'desc','Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');
				
				/* $conditions['OR']['Customer.verified_latitude NOT'] = null;
				$conditions['OR']['Customer.verified_longitude NOT'] = null; */
				
				$conditions['NOT']['OR'] = array(
					'Customer.verified_latitude' => null,
					'Customer.verified_longitude' => null,
					'Customer.verified_by' => null,
					'Customer.verified_date' => null
				);
				

				
				if (!empty($this->request->query['usr']) ){
					$conditions['Customer.verified_by'] = $this->request->query['usr'];
				}
				
				if ( !empty($this->request->query['verifiedfrom']) && !empty($this->request->query['verifiedto'])){
					$conditions['Customer.verified_date BETWEEN ? AND ?'] = array($this->request->query['verifiedfrom'], $this->request->query['verifiedto'].' 23:59:59');			
				}elseif (!empty($this->request->query['verifiedfrom'])){
					$conditions['Customer.verified_date >= '] = $this->request->query['verifiedfrom'];
				} elseif (!empty($this->request->query['verifiedto'])){
					$conditions['Customer.verified_date <= '] = $this->request->query['verifiedto'].' 23:59:59';
				}
				
			}else{
				$conditions['OR'] = array(
					'Customer.verified_latitude' => null,
					'Customer.verified_longitude' => null,
					'Customer.verified_by' => null,
					'Customer.verified_date' => null
				);
				
			}
		}else{
			
			$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
			
			if (!empty($this->request->query['usr']) ){
				$conditions['Customer.user_id'] = $this->request->query['usr'];
			}
		}
		
		if(empty($order)){
			$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
		}
		
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions['Customer.created BETWEEN ? AND ?'] = array($this->request->query['from'], $this->request->query['to'].' 23:59:59');			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Customer.created >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Customer.created <= '] = $this->request->query['to'].' 23:59:59';
		}
		
		
		if (!empty($this->request->query['q']) ){
			$keywordCond = array(
				'OR' => array(
					'Customer.first_name LIKE' => '%' . $this->request->query['q'] . '%',
					'Customer.last_name LIKE' => '%' . $this->request->query['q'] . '%'
				)
			);
			// Merge keywordCond with existing conditions using AND
			$conditions = array(
				'AND' => array(
					$conditions,
					$keywordCond
				)
			);
			
		}
		if (!empty($this->request->query['st']) ){
			$userCond['User.state_id'] = $conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if ( !empty($this->request->query['dv'])){
            $userCond['User.division_id'] = $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$userCond['User.region_id'] = $conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$userCond['User.depot_id'] = $conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		
		if (!empty($this->request->query['cid']) ){
			$conditions['Customer.id'] = $this->request->query['cid'];
		}
		
		if (isset($this->request->query['user_status']) && $this->request->query['user_status'] !== '') {
		    if ($this->request->query['user_status'] == '1') {
                $conditions['User.status'] = 1;
            } elseif ($this->request->query['user_status'] == '0') {
                $conditions['User.status NOT'] = 1;
            }
        }

        if (!empty($this->request->query['category']) ){
			$conditions['Customer.category'] = $this->request->query['category'];
		}
		
		
		
		
		
		//$this->Customer->_userCondition($conditions, $this->user);
		$this->Customer->_userRoleCondition($conditions, $this->user, $this->paginate);
		$joins =  array();
		$joins = isset($this->paginate['joins'])?$this->paginate['joins']:array();
		

		$querystring = $this->request->query; 
		//pr($this->request->query);
	    //pr($conditions); 
		if(isset($this->request->query['export'])){  			
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				/* if($offset > 10000){
					$offset = 0;
				} */
			}else{
				$offset = 0;
			}	
			/* $conditions['Customer.verified_by NOT']=null;
			$conditions['Customer.verified_date']=null; */
			//$conditions['Customer.verified_by'] = null;
			
			$customers = $this->Customer->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins, 'limit'=>EXPORT_LIMIT, 'offset'=>$offset));
		}else {
		    $customers = $this->paginate('Customer', $conditions);	  
		}
	//	pr($customers);
		
		if(!empty($customers)){
			$cust_ids = array();
			foreach($customers as $customer){
				array_push($cust_ids, $customer['Customer']['id']);
			}
			
			$lastVisitData = $this->Customer->customerLastVisit($cust_ids);	//pr($lastVisitData);
		}
		
		$this->loadModel('Role');
		$roles = $this->Role->find('list', array('fields' => array('id', 'name')));
		
        $this->set(compact('querystring','customers','offset', 'lastVisitData', 'roles'));

		/* $Opdata =  array();
		$param = isset($querystring ) ? $querystring  : array();

		$this->Option->Options($Opdata, $this->user, $param);

		$this->loadModel('User');
		
		//$users = $this->User->usersListByRole($this->user);
		
		### usersListByRole($user, $isService=false, $varified=false, $queryConditions = array()) ###
		$users = $this->User->usersListByRole($this->user, false, true);
		
			
		$this->set(compact('users'));
		
		//$this->_selectOptions(); */
		
		$this->_selectOptions($userCond, true);
		
		if(isset($this->request->query['export'])){
			if (!empty($this->request->query['verified']) ){
			$this->set('filename', 'verified_customers');
			}else{
				$this->set('filename', 'customers');
			}
			$this->render('export_customer','export_xls');
		}
		
	}
	
	
	
	public function add(){
		$this->loadModel('User');
		if ($this->request->data){
			//pr($this->request->data); die();
			//die('');
			$is_exists = $this->Customer->find('count', array('conditions'=>array('Customer.phone'=>$this->request->data['Customer']['phone']) ));
			
			if ($is_exists > 0){
				$this->Session->setFlash(__('This phone number already associated with other customer'));
			}else{
				$image_ok = true;
			
				if (!empty($this->request->data['Customer']['image']['name'])){
					if ($this->FileUpload->upload($this->request->data['Customer'],'image')) {
						$this->request->data['Customer']['file_id'] = $this->FileUpload->fileId;
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					$this->request->data['Customer']['user_id'] = $this->Auth->user('id');
					
					
					
					if(empty($this->request->data['Customer']['region_id']) && !empty($this->Auth->user('region_id'))){
						$this->request->data['Customer']['region_id'] = $this->Auth->user('region_id');
					}
					
					if(empty($this->request->data['Customer']['division_id']) && !empty($this->Auth->user('division_id'))){
						$this->request->data['Customer']['division_id'] = $this->Auth->user('division_id');
					}elseif(!empty($this->request->data['Customer']['region_id'])){
						
						$this->loadModel('DivisionsRegion');
						$division = $this->DivisionsRegion->findByRegionId($this->request->data['Customer']['region_id']); //pr($division);
						
						$this->request->data['Customer']['division_id'] = $division['DivisionsRegion']['division_id'];
					}
					
					if(empty($this->request->data['Customer']['depot_id']) && !empty($this->Auth->user('depot_id')) ){
						$this->request->data['Customer']['depot_id'] = $this->Auth->user('depot_id');
					}
					$customer = $this->Customer->save($this->request->data);
					
					if(empty($customer)){
							$this->Session->setFlash(__('There is some error to save customer data'));
					}else{	
						
						if(empty($customer['Customer']['route_id']) || empty($this->request->data['Customer']['route_id'])){
							/** Email  **/
							$email = new CakeEmail();
							$email->from(array('support@drupway.com'=> 'Y3 Support'));
							$email->to(array('smalution2037@gmail.com','drupwaycrm@gmail.com'));
							$email->emailFormat('html');
							$email->subject("Y3 - Route Null Customer Web App Add");
							$email->viewVars(array('customer' => $customer, 'user_id'=> $this->Auth->user('id')));
							$email->template('null_route_customer');
							$email->send('null_route_customer'); 
							/**** ----------------------------------------------------- ****/
						}
						
						$customer_id = $customer['Customer']['id'];
						if (!empty($this->request->data['Customer']['user_ids'])){
							$userIds = $this->request->data['Customer']['user_ids'];
							$this->loadModel('CustomerAssign');
							$this->CustomerAssign->primaryKey = null;
							$assignData = array();
							foreach($userIds as $uid){
								$assignData[] = array('customer_id'=>$customer_id, 'user_id'=>$uid, 'assign_by'=>$this->request->data['Customer']['user_id']);
							}
							@$this->CustomerAssign->saveAll($assignData);
						}
						$this->Session->setFlash(__('Customer was added sucessfully'));
						$this->redirect('/customers');
					}
				}
			}
		}
		$users = $this->User->usersListByRole($this->user);

		$this->set(compact('users'));
		$this->request->data['Customer']['user_ids'] = array();
		$this->_selectOptions();
		
		//SHOW DAY WISE ROUTES
		if($this->Auth->user('Role.id') == DH || $this->Auth->user('Role.grade') == SalesRep || $this->Auth->user('Role.grade') == BikeRep){
		//if($this->user['Role']['grade'] > BranchInChargeGrade ){
			$routes = array();
			$this->loadModel('UserRoute');
			
			//$day =date('D', strtotime(date('Y-m-d'))); 
			//$week = getY3Week();
			
			$userRouteCond['UserRoute.user_id'] = $this->Auth->user('id');
			
			$PTGCalendar = $this->_getPTGCalendarData(date('Y-m-d'));
			$userRouteCond['UserRoute.year'] = date('Y');
			$userRouteCond['UserRoute.month'] = $PTGCalendar['month'];
			$userRouteCond['UserRoute.week']= $PTGCalendar['week'];
			$userRouteCond['UserRoute.day']= date('l');
			
			
			//pr($userRouteCond); 
			$rtIds = $this->UserRoute->find('list', array('conditions'=>$userRouteCond, 'fields'=>array('user_id', 'route_ids')));
            if(!empty($rtIds)){
				$this->loadModel('Route');
				//$rtIds = array_keys ($rtIds); 
				$rtIds = explode(',', $rtIds[$this->Auth->user('id')]);
				$routes = $this->Route->find('list', array('conditions'=>array('id'=>$rtIds), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc'))); //pr(count($routes) );
			}
			$this->set(compact('routes'));	
		}
	}
	
	public function edit($id=0){
		$this->loadModel('User');
		$this->loadModel('Audit');
		$roledata=array(SUPPORT);
		$this->roleBasePermission($roledata);
		$userData = $this->Customer->read(null, $id);
		if(!$id){
			$this->redirect('/customers');
		}
		if ($this->request->data){
			$is_exists = $this->Customer->find('count', array('conditions'=>array('Customer.phone'=>$this->request->data['Customer']['phone'], 'Customer.id !='=>$id)));
			
			if ($is_exists > 0){
				$this->Session->setFlash(__('This phone number already associated with other customer'));
			}else{
				$image_ok = true;
			
				if (!empty($this->request->data['Customer']['image']['name'])){
					if ($this->FileUpload->upload($this->request->data['Customer'],'image')) {
						$this->request->data['Customer']['file_id'] = $uploaded_file_id = $this->FileUpload->fileId;
						if ($this->request->data['Customer']['oldFile_id']){
							$this->FileUpload->removeFileId($this->request->data['Customer']['oldFile_id']);
						}
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					//$this->request->data['Customer']['user_id'] = $this->Auth->user('id');
					if (!empty($this->request->data['Customer']['oldFile_id']) && $this->request->data['Customer']['remove_img'] == "1"){
						$this->FileUpload->removeFileId($this->request->data['Customer']['oldFile_id']);
						if(!isset($uploaded_file_id)){
							$this->request->data['Customer']['file_id'] = 0;
						}
					}
					$customer = $this->Customer->save($this->request->data);
					
					if(empty($customer)){
                        $this->Session->setFlash(__('There is some error to save customer data'));
                    }else{
					
						if(empty($customer['Customer']['route_id']) || empty($this->request->data['Customer']['route_id'])){
							/** Email  **/
							$email = new CakeEmail();
							$email->from(array('support@drupway.com'=> 'Y3 Support'));
							$email->to(array('smalution2037@gmail.com','drupwaycrm@gmail.com'));
							$email->emailFormat('html');
							$email->subject("Y3 - Route Null Customer Web App Edit");
							$email->viewVars(array('customer' => $customer, 'user_id'=> $this->Auth->user('id')));
							$email->template('null_route_customer');
							$email->send('null_route_customer'); 
							/**** ----------------------------------------------------- ****/
						}
						
						$this->loadModel('CustomerAssign');
						$this->CustomerAssign->primaryKey = null;
						$this->CustomerAssign->deleteAll(array('customer_id'=>$id), false);
						
						if (!empty($this->request->data['Customer']['user_ids'])){
							$userIds = $this->request->data['Customer']['user_ids'];
							$assignData = array();
							foreach($userIds as $uid){
								$assignData[] = array('customer_id'=>$id, 'user_id'=>$uid, 'assign_by'=>$this->Auth->user('d') );
							}
							//pr($assignData);
							@$this->CustomerAssign->saveAll($assignData);
						}
						$this->Audit->saveDeletedData($userData['Customer']['id'], 'Customer', $this->Auth->user('id') , serialize($userData),'Customer Has been updated', STATUS_EDIT);
						$this->Session->setFlash(__('Customer was updated sucessfully'));
						$this->redirect(array('action'=>'index'));
					}
				}
				
			}
		}else{
		
			$this->Customer->id = $id;
			$this->request->data = $this->Customer->read();
			$this->request->data['Customer']['user_ids'] = array();
			$this->loadModel('CustomerAssign');
			$this->CustomerAssign->primaryKey = null;
			$assigned = $this->CustomerAssign->find('all', array('conditions'=>array('customer_id'=>$id)));
			if ($assigned){
				foreach($assigned as $assign){
					$this->request->data['Customer']['user_ids'][] = $assign['CustomerAssign']['user_id'];
				}
			}
		}
		$users = $this->User->usersListByRole($this->user);
		
		$this->set(compact('users'));
		//$this->request->data['Customer']['user_ids'] = array();
		$this->_selectOptions();
		$this->render('add');
	}
	
	/**
     * view method
     *
     * @param string $id
     * @return void
     */
	 
	public function view($id = null){
		$this->Customer->id = $id;
        if (!$this->Customer->exists()) {
            throw new NotFoundException(__('Invalid customer'));
        }
		$belongsTo = array(		
			'Route' => array('className' => 'Route', 'foreignKey' => 'route_id', 'fields' => array('id', 'title'), 'type'=>'left'));
		$this->Customer->belongsTo = array_merge($this->Customer->belongsTo, $belongsTo);
        $this->set('customer', $this->Customer->read(null, $id));
	}
	
	/**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Customer->id = $id;
		$customer = $this->Customer->read();
        if (!$customer) {
            throw new NotFoundException(__('Invalid Customer'));
        }
		$data = array();
		$data['serialize'] = serialize($customer);
		$data['model_id'] = $customer['Customer']['id'];
        if ($this->Customer->delete()) {
			$this->loadModel('Audit');
			if ($customer['Customer']['file_id']){
				$this->FileUpload->removeFileId($customer['Customer']['file_id']);
			}
			$this->Audit->saveDeletedData($data['model_id'], 'Customer', $this->Auth->user('id') , $data['serialize'],'Customer Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Customer was deleted successfully'));
            $this->redirect(array('action' => 'inactivated_customers'));
        }
        $this->Session->setFlash(__('Customer was not deleted'));
        $this->redirect(array('action' => 'inactivated_customers'));
    }

	
	public function inactivate($id = null) {
		$this->loadModel('Audit');
		///	$this->gradPermission(1);
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }


        $this->Customer->id = $id;
		 $this->Customer->unbindModelAll();
        $custData = $this->Customer->read(null,$id); //pr($custData );
		
        if (!$this->Customer->exists()) {
            throw new NotFoundException(__('Invalid Customer'));
        }
		/* if(empty($custData['Customer']['route_id'])){
			$this->Session->setFlash(__('Route cannot be empty. Please update the route of the customer first!!'));
			$this->redirect(array('action' => 'index'));
		} */
		$data = array('inactive_date'=>date('Y-m-d'),'status'=>INACTIVE); 

        if ($this->Customer->save($data)) {
			$this->Audit->saveDeletedData($id, 'Customer', $this->Auth->user('id') , serialize($custData),'Customer Has been Inactivated',STATUS_DELETE);
            $this->Session->setFlash(__('Customer was inactivated successfully'));
            $this->redirect(array('action' => 'inactivated_customers'));
        }
        $this->Session->setFlash(__('Customer was not inactivated'));
        $this->redirect(array('action' => 'inactivated_customers'));
    }
	
	public function inactivateAllCustomers(){
	     
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }

        $this->loadModel('Audit');

		
		if(!empty($this->request->data['deleteAllValue'])){
			$custids=explode(",", $this->request->data['deleteAllValue']);
			$customer_ids = array();

			$timestamp = time();
			$inactiveDate = date('Y-m-d');

				foreach($custids as $cid){
					$this->Customer->id = $cid; 
					$custData = $this->Customer->read(null, $cid);

					//$this->Customer->saveField('status', INACTIVE); 
					$this->Customer->save(['id' => $cid,'status' => INACTIVE,'inactive_date' => $inactiveDate]);

					$this->Audit->saveDeletedData($cid, 'Customer', $this->Auth->user('id') , serialize($custData),'Customer Has been Deactivated (Bulk-'. $timestamp . ')',STATUS_DELETE);


				}
			
			$this->Session->setFlash(__('All selected Customers was inactivated successfully') );
			$this->redirect(array('action'=>'inactivated_customers'));
		}
		exit;
	}
	
	function activateall(){
		if (!empty($this->request->data['deleteAllValue'])){ 
			$this->Customer->updateAll(array('Customer.status' => ACTIVE), array('Customer.id' => explode(",", $this->request->data['deleteAllValue']) ) );
			$this->Session->setFlash(__('Selected customers was activated successfully'));
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	
	public function inactivated_customers(){
	
		//$conditions = array('Customer.status !=' => ACTIVE);
		$conditions = array(
			'Customer.status NOT' => ACTIVE,
			'Customer.first_name IS NOT NULL',
			'Customer.last_name IS NOT NULL'
		);
		
		
		
		
		if (!empty($this->request->query['q']) ){
			//	$conditions['OR']['Customer.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			//	$conditions['OR']['Customer.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
			//$conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
			//$conditions['OR']['Customer.id'] =  $this->request->query['q'];

			$keywordCond = array(
				'OR' => array(
					'Customer.first_name LIKE' => '%' . $this->request->query['q'] . '%',
					'Customer.last_name LIKE' => '%' . $this->request->query['q'] . '%'
				)
			);
			// Merge keywordCond with existing conditions using AND
			$conditions = array(
				'AND' => array(
					$conditions,
					$keywordCond
				)
			);
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if (!empty($this->request->query['dv']) ){
            $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		if (!empty($this->request->query['usr']) ){
			$conditions['Customer.user_id'] = $this->request->query['usr'];
		}
		
		/*if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Customer.created BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Customer.created >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Customer.created <= '] = $this->request->query['to'];
		}*/

		if (!empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Customer.inactive_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Customer.inactive_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Customer.inactive_date <= '] = $this->request->query['to'];
		}
		
		//$this->Customer->_userCondition($conditions, $this->user);
		$this->Customer->_userRoleCondition($conditions, $this->user, $this->paginate);
		
		//$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
		$order=$this->paginate['order'] = array('Customer.created' => 'desc','Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');

		$querystring = $this->request->query;
		if(isset($this->request->query['export'])){
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();			
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				// if($offset > 10000){
					// $offset = 0;
				// }
			}else{
				$offset = 0;
			}		
			$customers = $this->Customer->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>EXPORT_LIMIT, 'offset'=>$offset));
		} else {
		    $customers = $this->paginate('Customer', $conditions);	  
		}
		
        $this->set(compact('querystring','customers','offset'));

		//$this->_selectOptions();
		$this->_ioptions();
		if(isset($this->request->query['export'])){
			$this->set('filename', 'inactivecustomers');
			$this->render('export_customer','export_xls');
		}
	}
	
	
	
	
	function _selectOptions($userCond = array(), $varified=false){ 

		$this->loadModel('User');	
		$users = $this->User->usersListByRole($this->user, false, $varified, $userCond);
		$this->set(compact('users'));
		$Opdata = isset($this->request->data['Customer'] ) ? $this->request->data['Customer']  : array();
		$param = !empty($this->request->query ) ? $this->request->query  : array();
		$this->Option->Options($Opdata, $this->user, $param);
	}
	
	
	function _ioptions(){
		$this->loadModel('User');	
		$users = $this->User->usersListByRole($this->user);
		$this->set(compact('users'));
		$Opdata['region_id'] = isset($this->request->query['rg']) ? $this->request->query['rg']  : array();
		$Opdata['depot_id'] = isset($this->request->query['dp']) ? $this->request->query['dp']  : array();
		$this->Option->Options($Opdata, $this->user);
	}
	
	function getLatLong(){
		$data = $this->request->data;
		$result = array();
		$data['zip'] = !empty($data['zip']) ? empty($data['zip']) : (!empty($data['zipcode']) ? empty($data['zipcode']) : '');
		$address = $data['address'].'+'.$data['city'].'+'.$data['state'].'+'.$data['zip'];
		$address = urlencode($address);
		//$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=".DEFAULT_RESION;
		$url = "https://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&key=".GOOGLEMAP_API_KEY."&region=".DEFAULT_RESION;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);
		curl_close($ch);
		$response_a = json_decode($response);
		$result['lat'] = isset($response_a->results[0]->geometry->location->lat)?$response_a->results[0]->geometry->location->lat:0;
		
		$result['long'] = isset($response_a->results[0]->geometry->location->lng)?$response_a->results[0]->geometry->location->lng:0;
		$this->set('result', $result);
	}
	

	
	
	
	
	
	
	
	public function visits($opr='', $id=0){
		$this->loadModel('CustomerVisit');
		$conditions = array();

        $query = $querystring = $this->request->query;
        if(!empty($query['from']) || !empty($query['to']) ){
            $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
        }else{
            $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
        }
		$this->set(compact('querystring'));
		switch($opr){
			case 'add';
				//$this-> _updateAttendance_visitentry();
			case 'edit':
				$this->roleBasePermission(array(SUPPORT));
				$this->_update_customer_visits($id);
			break;
			case 'delete':
				$this->_delete_visits($id);
			break;
			case 'view':
				$this->CustomerVisit->id = $id;
				//$visit = $this->CustomerVisit->read();
                $visit = $this->request->data = $this->CustomerVisit->getSingleVisitYearTable($id, $cvisityear_tables);//pr($visit);
				$this->set('visit', $visit);
				$this->render('view_visit');
			break;
			default:
				/*if (!empty($this->request->query['q']) ){
					$conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
					$conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
				}
				if (!empty($this->request->query['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
                    if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                        $conditions[] = 'CustomerVisit.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
                    }
                    if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
                        $conditions[] = 'CustomerVisit.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
                    }
                    if (!empty($this->request->query['dp'])){
                        $conditions['CustomerVisit.depot_id'] = $this->request->query['dp'];
                    }

                }
				
				if (!empty($this->request->query['usr']) ){
					$conditions['CustomerVisit.user_id'] = $this->request->query['usr'];
				}
				if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
					$conditions[] = array('CustomerVisit.visiting_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to'].' 23:59:59' ));
					
				}elseif (!empty($this->request->query['from'])){
					$conditions['CustomerVisit.visiting_date >= '] = $this->request->query['from'];
				} elseif (!empty($this->request->query['to'])){
					$conditions['CustomerVisit.visiting_date <= '] = $this->request->query['to'];
				}
			   	if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
					$conditions[] = array('CustomerVisit.modified BETWEEN ? AND ?' => array($this->request->query['mfrom'], $this->request->query['mto']));
				} 
				//$this->CustomerVisit->visibleConditions($conditions, $this->user);
				$this->CustomerVisit->visibleroleConditions($conditions, $this->user, $this->paginate);
				$order=$this->paginate['order'] = array('CustomerVisit.id' => 'desc');*/

                $query = $querystring = $this->request->query;
                $type="monthly";
                $opt = !empty($opt) ? $opt : '';
                

                switch($type){
                    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);
                        $d1 = date('Y-m-d', $strtotime);
                        $d2 =  date('Y-m-d', strtotime('+1 month', $strtotime));


                        if(empty($query['from']) || empty($query['to']) ){
                            $d1 = date('Y-m-d', $strtotime);
                            $this->request->query['from'] = $query['from'] = $d1;

                            $d2 =  date('Y-m-t', $strtotime);
                            $this->request->query['to'] = $query['to'] = $d2;
                        }

                        break;
                }
                if(!empty($query['from']) || !empty($query['to']) ){
                    $type="between";
                    $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
                }else{
                    $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
                }
                //pr($cvisityear_tables);


                $navParams = $this->_nav_params($type, @$opt);
                $user = $this->user;
                $params = array_merge($navParams, compact('query', 'type','opt','cvisityear_tables','user'));
                $this->CustomerVisit->customerVisitAdditionalParam($params, $this->paginate, $conditions);

                $joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();

				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;
					}
						
					//$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();
					//$visits = $this->CustomerVisit->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
                    $visits = $this->CustomerVisit->customerVisitAll($params,$this->user);
				} else {
				    $visits = $this->paginate('CustomerVisit', $conditions);
				}

				$this->loadModel('Division');
                $this->loadModel('Region');
				$this->loadModel('Depot');
				$this->loadModel('User');
				$divisions = $this->Division->getList();
				$division_id = !empty($this->request->query['dv']) ? $this->request->query['dv'] : 0 ;
                $regions = $this->Region->getList($division_id);
				$region_id = !empty($this->request->query['rg']) ? $this->request->query['rg'] : 0 ;
				$depot_id = !empty($this->request->query['dp']) ? $this->request->query['dp'] : 0 ;

				$depots = $this->Depot->getList($region_id);
				$users = $this->User->usersList($depot_id);
				$this->set(compact('offset','visits','divisions', 'regions', 'depots', 'users','querystring'));

				if(isset($this->request->query['export'])){
					$this->set('filename','visited_customers'); 						 
					$this->render('export_visit','export_xls');
				}
				
			break;
		}
	}
	function _delete_visits($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        /*
        $this->CustomerVisit->id = $id;
        if (!$this->CustomerVisit->exists()) {
            throw new NotFoundException(__('Invalid customer visit'));
        }
		$customerId = $this->CustomerVisit->field('customer_id');	
		$customervisit = $this->CustomerVisit->read();*/

        if(empty($cvisityear_tables)){
            $query = $this->request->query;
            if(!empty($query['from']) || !empty($query['to']) ){
                $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
            }else{
                $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
            }
        }
        $customervisit = $this->request->data = $this->CustomerVisit->getSingleVisitYearTable($id, $cvisityear_tables);//pr($visit);
        if (empty($customervisit)) {
            throw new NotFoundException(__('Invalid customer visit'));
        }
        $customerId = $customervisit['CustomerVisit']['customer_id'];
			$data = array();
		$data['serialize'] = serialize($customervisit);
		$data['model_id'] = $customervisit['CustomerVisit']['id'];
		/*if ($this->CustomerVisit->delete()) {
			$this->loadModel('Customer');	
			$this->loadModel('Audit');		
			
			$this->Customer->verify_status( $customerId );
			$this->Audit->saveDeletedData($data['model_id'], 'CustomerVisit', $this->Auth->user('id') , $data['serialize'],'Customer Visit Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Customer visit was deleted successfully'));
            $this->redirect(array('action' => 'visits'));
        }*/

        $delcvRes = $this->CustomerVisit->deleteSingleVisitYearTable($id, $cvisityear_tables);
        if($delcvRes){
            $this->loadModel('Customer');
            $this->loadModel('Audit');

            $this->Customer->verify_status( $customerId );
            $this->Audit->saveDeletedData($data['model_id'], 'CustomerVisit', $this->Auth->user('id') , $data['serialize'],'Customer Visit Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Customer visit was deleted successfully'));
            $this->redirect(array('action' => 'visits'));
        }

        $this->Session->setFlash(__('Customer visit was not deleted'));
        $this->redirect(array('action' => 'visits'));
	}
	
	function _update_customer_visits($id){ 
		$this->loadModel('Audit');
        $query = $this->request->query;
        if(!empty($query['from']) || !empty($query['to']) ){
            $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
        }else{
            $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
        }
		if ($id){
				$this->CustomerVisit->id = $id;
				//$visitData = $this->CustomerVisit->read();//pr($visitData);
                $visitDataOld = $visitData = $this->CustomerVisit->getSingleVisitYearTable($id, $cvisityear_tables);//pr($visitData);exit;
				$visitData['CustomerVisit'] = serialize($visitData['CustomerVisit']);
			}
		if ($this->request->data){
			if (!$id){
				$this->request->data['CustomerVisit']['user_id'] = $this->user['id'];
			}
			//Get customer's depot_id
			$customer = $this->Customer->findById($this->request->data['CustomerVisit']['customer_id']);
			$this->request->data['CustomerVisit']['depot_id'] = $customer['Customer']['depot_id'];
			$this->request->data['CustomerVisit']['lg_area_id'] = $customer['Customer']['lg_area_id'];
			
			if (empty($this->request->data['CustomerVisit']['visiting_date'])){
				$this->request->data['CustomerVisit']['visiting_date'] = date('Y-m-d H:i:s');
			}
			/* if($this->CustomerVisit->save($this->request->data) && !empty($visitData)){
		//$this->Audit->saveDeletedData($visitData['CustomerVisit']['id'], 'CustomerVisit', $this->Auth->user('id') , $visitData['CustomerVisit'],'Customer Visit Has been Updated',STATUS_EDIT);
			} */
			
			//$visit = $this->CustomerVisit->save($this->request->data);
            $cvRes = false;
            if (!$id){
                //Add new visit to customer_visits table
				$visit = $this->CustomerVisit->save($this->request->data);
				
				/*****----- Check if entry is on correct route -----*****/
				/* $uid = $visit['CustomerVisit']['user_id']; 
				$date = date('Y-m-d', strtotime($visit['CustomerVisit']['visiting_date']));
				$PTGCalendar = $this->_getPTGCalendarData($date);
					
				$this->loadModel('Route');
				$userDayRouteIds = $this->Route->getUserDayRouteIds($uid,$date,$PTGCalendar); 
				if(!empty($userDayRouteIds)){
					if (!in_array($customer['Customer']['route_id'],$userDayRouteIds)){
						// Customer's route_id is not in $userDayRouteIds array
						$this->CustomerVisit->id = $visit['CustomerVisit']['id'];
						$this->CustomerVisit->saveField('not_on_day_route', 1);
						
						// find routes title
						$userDayRoutes = $this->Route->find('list', array('fields' => array('id', 'title'), 'conditions' => array('id' => $userDayRouteIds)));
						
						
						//Send notifying email
						### Email  ###
							$email = new CakeEmail('smtp');
							$email->from(array('support@drupway.com'=> 'Y3 Support'));
							$email->to(array('drupwaycrm@gmail.com','y3hqfin@fastmail.fm')); //y3hqfin@fastmail.fm = Anya
							$email->emailFormat('html');
							$email->subject("Y3 CRM ALERT - Visit entry on a day other than the user's day routes.");
							$email->viewVars(array('model' => 'CustomerVisit', 'data' => $visit, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
							$email->template('entry_on_different_route');
							$email->send('entry_on_different_route'); 
						### ----------------------------------------------------- ###
					}
				} */
				/*****------------------------------------*****/
				
            }else{
                //Update exist visit to the respective customer visits year table
                $cvRes = $this->CustomerVisit->updateCustomerVisitYearTable($this->request->data, $cvisityear_tables);
                if($cvRes){
                    $visit['CustomerVisit'] =  $this->request->data['CustomerVisit'];
                }
            }
			if(!empty($visit)){
				if(empty($id)){
					$uid1 = $this->user['id'];;
					$created_date = $visit['CustomerVisit']['created'];
					//$this->_updateAttendance_visitentry($uid1, $created_date);
				}else{
					//$this->Audit->saveDeletedData($visitData['CustomerVisit']['id'], 'CustomerVisit', $this->Auth->user('id') , $visitData['CustomerVisit'],'Customer Visit Has been Updated',STATUS_EDIT);
                    if($cvRes){
                        $this->Audit->saveDeletedData($visitDataOld['CustomerVisit']['id'], 'CustomerVisit', $this->Auth->user('id') , $visitData['CustomerVisit'],'Customer Visit Has been Updated',STATUS_EDIT);
                    }
				}
				
				
				
			}
			
			$this->Customer->verify_status($this->request->data['CustomerVisit']['customer_id']);
			$this->Session->setFlash('Last Record was save successfully');
			$this->redirect(array('action'=>'visits'));
		}
		$this->loadModel('Depot');
		$this->loadModel('LgArea');
		$depots = $this->Depot->getList();
		$customers = $this->Customer->customerListByRole($this->user);  //pr(count($customers)); //pr($customers);
		$lgAreas = $this->LgArea->find('list', array('fields'=>array('id','name'), 'order'=>array('name'=>'asc')));
		$opration = __('Add');
		if ($id){
			$this->CustomerVisit->id = $id;
			//$this->request->data = $this->CustomerVisit->read();
            $this->request->data = $this->CustomerVisit->getSingleVisitYearTable($id, $cvisityear_tables);//pr($visitData);exit;
			$opration = __('Update');
		}
		$this->set(compact('depots', 'customers', 'opration', 'lgAreas'));
		$this->render('updateVisits');
	}
	
	public function getDpCustomers($depot_id){
		$conditions = array('Customer.depot_id'=>$depot_id);
		$this->paginate['limit'] = 10;
		$this->paginate['order'] = array('Customer.amount'=>'desc', 'Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');
		$customers = $this->paginate('Customer', $conditions);
		$this->set('customers', $customers);
	}
	
	/* public function unvisited(){
		
		//$this->gradPermission(4);
		//$conditions = array('Customer.status !=' => DELETED);
		$userCond = array(); 
		
		$conditions = array(
			'Customer.status' => ACTIVE,
			'Customer.first_name IS NOT NULL',
			'Customer.last_name IS NOT NULL'
		);
		
		if (!empty($this->request->query['q']) ){
			$keywordCond = array(
				'OR' => array(
					'Customer.first_name LIKE' => '%' . $this->request->query['q'] . '%',
					'Customer.last_name LIKE' => '%' . $this->request->query['q'] . '%'
				)
			);
			// Merge keywordCond with existing conditions using AND
			$conditions = array(
				'AND' => array(
					$conditions,
					$keywordCond
				)
			);
		}
		if (!empty($this->request->query['st']) ){
			$userCond['User.state_id'] = $conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if (!empty($this->request->query['dv']) ){
            $userCond['User.division_id'] = $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$userCond['User.region_id'] = $conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$userCond['User.depot_id'] = $conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		
		if (!empty($this->request->query['from']) ){
			
			$from = $this->request->query['from'];
		}else{
			$from = date('Y-m-d', strtotime('-7 days'));
		}
		
		if (!empty($this->request->query['to']) ){
			$to = $this->request->query['to'];
		}else{
			$to = date('Y-m-d');
		}
		
		if (!empty($this->request->query['ns']) ){
		
			$this->paginate['joins'][] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id AND Order.order_date between "'.$from.'" AND "'.$to.'"'));
			
			$conditions['Order.id'] = null;
		}
		
		
        $query = $this->request->query;
		
		if (!empty($this->request->query['nv']) ){
			//$this->paginate['joins'][] = array('table' => 'customer_visits', 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.'"'));
            if(!empty($query['from']) || !empty($query['to']) ){
                $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
            }else{
                $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
            }

            $cvC =' AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.' 23:59:59"';
            if(!empty($cvisityear_tables)){
                if(count($cvisityear_tables)>1){
                    $cvisityear_tabSqlArray = array();
                    foreach ($cvisityear_tables as $year => $cv_tableName){
                        $cvisityear_tabSqlArray[] = " ( SELECT * FROM $cv_tableName as CustomerVisit WHERE 1 $cvC )";
                    }
                    $cvisityear_tabSql = "( ".implode(" UNION ALL ", $cvisityear_tabSqlArray)." )"; // UNION operation For Multiple customer_visits table as per year wise organized

                }else{
                    $cvisityear_tabSql = $cvisityear_tables[key($cvisityear_tables)]; // Single customer_visits table as per year wise organized
                }
                //pr($cvisityear_tabSql);
            }else{
                $cvisityear_tabSql ='customer_visits';
            }
            $this->paginate['joins'][] = array('table' => $cvisityear_tabSql, 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
			$conditions['CustomerVisit.id'] = null;
		}
		
		$this->Customer->_userCondition($conditions, $this->user);
		$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');

		$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;
			}
				
			$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();		
			$customers = $this->Customer->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		} else {
		    $customers = $this->paginate('Customer', $conditions);
		}
		$this->set('customers', $customers);
		$this->set(compact('offset','from', 'to','querystring'));
		$this->_selectOptions($userCond, true);
		
		if(isset($this->request->query['export'])){ 
			$this->set('filename','unvisited_customers');
			$this->render('export_unvisit','export_xls');
		}
	} */
	
	public function unvisited(){
		
		//$this->gradPermission(4);
		//$conditions = array('Customer.status !=' => DELETED);
		$userCond = array(); 
		
		$conditions = array(
			'Customer.status' => ACTIVE,
			'Customer.first_name IS NOT NULL',
			'Customer.last_name IS NOT NULL'
		);
		
		if(isset($this->request->query['verified']) && strlen($this->request->query['verified']) > 0){
			if ($this->request->query['verified'] == 1 ){
			
				$order=$this->paginate['order'] = array('Customer.verified_date' => 'desc','Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');
				
				$conditions['NOT']['OR'] = array(
					'Customer.verified_latitude' => null,
					'Customer.verified_longitude' => null,
					'Customer.verified_by' => null,
					'Customer.verified_date' => null
				);
				

				
				if (!empty($this->request->query['verified_by']) ){
					$conditions['Customer.verified_by'] = $this->request->query['verified_by'];
				}
				
				if ( !empty($this->request->query['verifiedfrom']) && !empty($this->request->query['verifiedto'])){
					$conditions['Customer.verified_date BETWEEN ? AND ?'] = array($this->request->query['verifiedfrom'], $this->request->query['verifiedto'].' 23:59:59');			
				}elseif (!empty($this->request->query['verifiedfrom'])){
					$conditions['Customer.verified_date >= '] = $this->request->query['verifiedfrom'];
				} elseif (!empty($this->request->query['verifiedto'])){
					$conditions['Customer.verified_date <= '] = $this->request->query['verifiedto'].' 23:59:59';
				}
				
			}else{
			    if($this->request->query['verified'] == 2){
			        $conditions['Customer.location_updated'] = 1;
			    }
			    
				$conditions['OR'] = array(
					'Customer.verified_latitude' => null,
					'Customer.verified_longitude' => null,
					'Customer.verified_by' => null,
					'Customer.verified_date' => null
				);
			}
		}else{
			
			$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
			
			if (!empty($this->request->query['usr']) ){
				$conditions['Customer.user_id'] = $this->request->query['usr'];
			}
		}
		
		if (!empty($this->request->query['q']) ){
			$keywordCond = array(
				'OR' => array(
					'Customer.first_name LIKE' => '%' . $this->request->query['q'] . '%',
					'Customer.last_name LIKE' => '%' . $this->request->query['q'] . '%'
				)
			);
			// Merge keywordCond with existing conditions using AND
			$conditions = array(
				'AND' => array(
					$conditions,
					$keywordCond
				)
			);
		}
		if (!empty($this->request->query['st']) ){
			$userCond['User.state_id'] = $conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if (!empty($this->request->query['dv']) ){
            $userCond['User.division_id'] = $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$userCond['User.region_id'] = $conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$userCond['User.depot_id'] = $conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		
		if (!empty($this->request->query['usr']) ){
			$conditions['Customer.user_id'] = $this->request->query['usr'];
		}
		
		if (!empty($this->request->query['from']) ){
			
			$from = $this->request->query['from'];
		}else{
			$from = date('Y-m-d', strtotime('-7 days'));
		}
		
		if (!empty($this->request->query['to']) ){
			$to = $this->request->query['to'];
		}else{
			$to = date('Y-m-d');
		}
		
		if (!empty($this->request->query['ns']) ){
		
			$this->paginate['joins'][] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id AND Order.order_date between "'.$from.'" AND "'.$to.'"'));
			
			$conditions['Order.id'] = null;
		}
		
		if (!empty($this->request->query['nrs']) ){
			$this->paginate['joins'][] = array('table' => 'redistributor_sales', 'type'=>'left', 'alias'=>'RedistributorSale', 'conditions'=>array('Customer.id=RedistributorSale.customer_id AND RedistributorSale.sale_date between "'.$from.'" AND "'.$to.'"'));
			$conditions['RedistributorSale.id'] = null;
		}
				
		$query = $this->request->query;
		
		if (!empty($this->request->query['nv']) ){
			//$this->paginate['joins'][] = array('table' => 'customer_visits', 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.'"'));
            if(!empty($query['from']) || !empty($query['to']) ){
                $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
            }else{
                $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
            }

            $cvC =' AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.' 23:59:59"';
            if(!empty($cvisityear_tables)){
                if(count($cvisityear_tables)>1){
                    $cvisityear_tabSqlArray = array();
                    foreach ($cvisityear_tables as $year => $cv_tableName){
                        $cvisityear_tabSqlArray[] = " ( SELECT * FROM $cv_tableName as CustomerVisit WHERE 1 $cvC )";
                    }
                    $cvisityear_tabSql = "( ".implode(" UNION ALL ", $cvisityear_tabSqlArray)." )"; // UNION operation For Multiple customer_visits table as per year wise organized

                }else{
                    $cvisityear_tabSql = $cvisityear_tables[key($cvisityear_tables)]; // Single customer_visits table as per year wise organized
                }
                //pr($cvisityear_tabSql);
            }else{
                $cvisityear_tabSql ='customer_visits';
            }
            $this->paginate['joins'][] = array('table' => $cvisityear_tabSql, 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
			$conditions['CustomerVisit.id'] = null;
		}
		
		$this->Customer->_userCondition($conditions, $this->user);
		$order=$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');

		$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;
			}
				
			$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();		
			$customers = $this->Customer->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>EXPORT_LIMIT_MIN, 'offset'=>$offset));
		} else {
		    $customers = $this->paginate('Customer', $conditions);
		}
		$this->set('customers', $customers);
		$this->set(compact('offset','from', 'to','querystring'));
		$this->_selectOptions($userCond, true);
		
		if(isset($this->request->query['export'])){ 
			$this->set('filename','unvisited_customers');
			$this->render('export_unvisit','export_xls');
		}
	}
	
	function notvisited(){
		//$this->gradPermission(4);
		$from = date('Y-m-01');
		$to = date('Y-m-d');
		
		
		$joins[] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id AND Order.order_date between "'.$from.'" AND "'.$to.'"'));
		$conditions['Order.id'] = null;
		
		$joins[] = array('table' => 'customer_visits', 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.'"'));
		$conditions['CustomerVisit.id'] = null;
		 
		$order = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');
		$this->Customer->_userCondition($conditions, $this->user);
		$customers = $this->Customer->find('all', array('conditions'=>$conditions, 'joins'=>$joins, 'order'=>$order, 'limit'=>100));
		$this->set('customers', $customers);
		$this->set(compact('from', 'to'));
		
	}
	/* public function visitednosale(){
		//$this->gradPermission(4);
		$conditions = array('Customer.status !=' => DELETED);
		
		$conditions['Customer.first_name NOT'] = null;
		$conditions['Customer.last_name NOT'] = null;
		
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['Customer.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['Customer.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if (!empty($this->request->query['dv']) ){
            $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		
		if (!empty($this->request->query['from']) ){
			
			$from = $this->request->query['from'];
		}else{
			$from = date('Y-m-d', strtotime('-7 days'));
		}
		
		if (!empty($this->request->query['to']) ){
			$to = $this->request->query['to'];
		}else{
			$to = date('Y-m-d');
		}

        $query = $this->request->query;

        if(!empty($query['from']) || !empty($query['to']) ){
            $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
        }else{
            $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
        }


		//$this->paginate['joins'][] = array('table' => 'customer_visits', 'type'=>'inner', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.'"'));
        $cvC =' AND DATE_FORMAT(CustomerVisit.visiting_date, "%Y-%m-%d") between "'.$from.'" AND "'.$to.' 23:59:59"';
        if(!empty($cvisityear_tables)){
            if(count($cvisityear_tables)>1){
                $cvisityear_tabSqlArray = array();
                foreach ($cvisityear_tables as $year => $cv_tableName){
                    $cvisityear_tabSqlArray[] = " ( SELECT * FROM $cv_tableName as CustomerVisit WHERE 1 $cvC )";
                }
                $cvisityear_tabSql = "( ".implode(" UNION ALL ", $cvisityear_tabSqlArray)." )"; // UNION operation For Multiple customer_visits table as per year wise organized

            }else{
                $cvisityear_tabSql = $cvisityear_tables[key($cvisityear_tables)]; // Single customer_visits table as per year wise organized
            }
            //pr($cvisityear_tabSql);
        }else{
            $cvisityear_tabSql ='customer_visits';
        }
        $this->paginate['joins'][] = array('table' => $cvisityear_tabSql, 'type'=>'inner', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
		
		$this->paginate['joins'][] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id AND Order.order_date between "'.$from.'" AND "'.$to.'"'));
		$conditions['Order.id'] = null;
		
		
		$this->Customer->_userCondition($conditions, $this->user);
		$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
		
		$customers = $this->paginate('Customer', $conditions);
		$this->set('customers', $customers);
		$this->set(compact('from', 'to'));
		$this->_selectOptions();
	} */
	
	public function visitednosale(){
		//$this->gradPermission(4);
		//$conditions = array('Customer.status !=' => DELETED);
		
		$userCond = array(); 
		
		$conditions = array(
			'Customer.status' => ACTIVE,
			'Customer.first_name IS NOT NULL',
			'Customer.last_name IS NOT NULL'
		);
		
		if (!empty($this->request->query['q']) ){
			$keywordCond = array(
				'OR' => array(
					'Customer.first_name LIKE' => '%' . $this->request->query['q'] . '%',
					'Customer.last_name LIKE' => '%' . $this->request->query['q'] . '%'
				)
			);
			// Merge keywordCond with existing conditions using AND
			$conditions = array(
				'AND' => array(
					$conditions,
					$keywordCond
				)
			);
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if (!empty($this->request->query['dv']) ){
            $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}
		
		if (!empty($this->request->query['from']) ){
			
			$from = $this->request->query['from'];
		}else{
			$from = date('Y-m-d', strtotime('-7 days'));
		}
		
		if (!empty($this->request->query['to']) ){
			$to = $this->request->query['to'];
		}else{
			$to = date('Y-m-d');
		}

        $query = $this->request->query;

        if(!empty($query['from']) || !empty($query['to']) ){
            $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
        }else{
            $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
        }

        $cvC =' AND CustomerVisit.visiting_date BETWEEN "' . $from . '" AND "' . $to . ' 23:59:59"';
        if(!empty($cvisityear_tables)){
            if(count($cvisityear_tables)>1){
                $cvisityear_tabSqlArray = array();
                foreach ($cvisityear_tables as $year => $cv_tableName){
                    $cvisityear_tabSqlArray[] = " ( SELECT * FROM $cv_tableName as CustomerVisit WHERE 1 $cvC )";
                }
                $cvisityear_tabSql = "( ".implode(" UNION ALL ", $cvisityear_tabSqlArray)." )"; // UNION operation For Multiple customer_visits table as per year wise organized

            }else{
                $cvisityear_tabSql = $cvisityear_tables[key($cvisityear_tables)]; // Single customer_visits table as per year wise organized
            }
            //pr($cvisityear_tabSql);
        }else{
            $cvisityear_tabSql ='customer_visits';
        }
        $this->paginate['joins'][] = array('table' => $cvisityear_tabSql, 'type'=>'inner', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
		
		//when both selected it mean Neither an order nor a redistributor sale
		
		if (!empty($this->request->query['ns']) ){
			$this->paginate['joins'][] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id AND Order.order_date between "'.$from.'" AND "'.$to.'"'));
			//$conditions['Order.id'] = null;
			//$conditions['OR']['Order.id'] = null;
			$conditions['AND'][] = array('Order.id' => null);			
		}
		
		if (!empty($this->request->query['nrs']) ){
			$this->paginate['joins'][] = array('table' => 'redistributor_sales', 'type'=>'left', 'alias'=>'RedistributorSale', 'conditions'=>array('Customer.id=RedistributorSale.customer_id AND RedistributorSale.sale_date between "'.$from.'" AND "'.$to.'"'));
			//$conditions['RedistributorSale.id'] = null;
			//$conditions['OR']['RedistributorSale.id'] = null;
			$conditions['AND'][] = array('RedistributorSale.id' => null);
		}
		
		
		$this->Customer->_userCondition($conditions, $this->user);
		$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc','Customer.amount' => 'desc');
		
		$group = $this->paginate['group'] = array('Customer.id');
		
		$customers = $this->paginate('Customer', $conditions);
		$this->set('customers', $customers);
		$this->set(compact('from', 'to'));
		$this->_selectOptions();
	}
	
	
	
/**
	//saleActivity by customer monthly
	public 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);
		
		$this->Customer->unbindModelAll(); **/
		
		/*$joins = array(array('table'=>'sales', 'alias'=>'Sale', 'type'=>'left', 'conditions'=>array('Customer.id = Sale.customer_id')));
		
		$fields = array('Customer.id', 'Customer.first_name', 'Customer.last_name', '(IFNULL(SUM(Sale.cal_qty),0) + IFNULL((SELECT SUM(cal_qty) FROM redistributor_saleitems WHERE customer_id = Sale.customer_id AND sale_date LIKE "'.$date.'%"),0)) AS total_sale', '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE customer_id = Sale.customer_id AND sale_date LIKE "'.$date.'%"),0)) AS total_amount');
		
		$this->Customer->virtualFields['total_amount'] = '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE customer_id = Sale.customer_id AND sale_date LIKE "'.$date.'%"),0))';*/
		
	/**	$conditions = array('Sale.sale_date LIKE "'.$date.'%"', 'Customer.status !=' => DELETED);
		$this->Customer->_userCondition($conditions, $this->user);
		
		$joins = array(array('table'=>"(SELECT customer_id, cal_qty, sale_date, amount FROM sales WHERE sale_date LIKE  '$date%' UNION  SELECT customer_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE sale_date LIKE  '$date%')", 'alias'=>'Sale', 'type'=>'left', 'conditions'=>array('Sale.customer_id = Customer.id')));
		
		$fields = array('Customer.id', 'Customer.first_name', 'Customer.last_name', 'SUM(Sale.cal_qty) AS total_sale', 'SUM(Sale.amount) AS total_amount');
		
		$this->Customer->virtualFields['total_amount'] = 'SUM(Sale.amount)';
	
		$this->paginate['fields'] = $fields;
		$this->paginate['group'] = array('Customer.id');
		$this->paginate['order'] = array('total_amount'=>'desc');
		$this->paginate['joins'] = $joins;
		
		$customers = $this->paginate('Customer', $conditions);
		
		//Custom paging
		//$this->paginate['model'] = 'customer';
		//$this->paginate['date'] = $date;
		//$this->paginate['user'] = $this->user; 
		//$this->loadModel('SaleActivity');
		//$customers = $this->paginate('SaleActivity', $conditions);
		
		
		if ($customers){
			$this->Customer->saleActivity($customers, compact('date', 'prev', 'next', 'current'));
		}
		
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list',  array('fields'=>array('id', 'name')));
		$this->set(compact('customers', 'brands', 'date', 'prev', 'next', 'current','strtotime'));
		if(!$this->request->is('ajax')){
			$this->render('sale_activity_report');
		}
	}  **/
	
	//saleActivity by customer monthly
    public 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('Customer.status'=>ACTIVE);
        $saConditions[] = 'Sale.customer_id = Customer.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 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'];


        if(!empty($this->request->query['dv'])){
            $division_id = $this->request->query['dv'];
        }else{
            $division_id = 0;
            if(!empty($this->user['division_id']) && $this->user['role_id'] == DIVISIONMANAGER){
                $this->request->query['dv'] = $division_id = $this->user['division_id'];
            }
        }
        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'];
        }



        if (!empty($this->request->query['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
            if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                $total_amt_cond .=' AND depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
            }
            if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
                $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;
            $total_amt_cond .= ' AND brand_group_id='.$brand_group_id;
            //pr($saConditions);exit;
        }
        if (!empty($this->request->query['customer_id'])){
            $customer_id = $this->request->query['customer_id'];
            $conditions[] = 'Sale.customer_id='.$customer_id;
            $total_amt_cond .= ' AND customer_id='.$customer_id;
            //pr($saConditions);exit;
        }

        $this->Customer->unbindModelAll();


        /*$joins = array(array('table'=>'sales', 'alias'=>'Sale', 'type'=>'left', 'conditions'=>array('Customer.id = Sale.customer_id')));

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

        $this->Customer->virtualFields['total_amount'] = '(IFNULL(SUM(Sale.amount),0) + IFNULL((SELECT SUM(amount) FROM redistributor_saleitems WHERE customer_id = Sale.customer_id AND sale_date LIKE "'.$date.'%"),0))';*/



        $this->Customer->_userCondition($conditions, $this->user);
		$saletype = "";
		if(!empty($query['saletype'])){
			$saletype = $query['saletype'];
		}
		
		switch($saletype){
			case 'Sale':
				$joins = array(array('table'=>"(SELECT customer_id,brand_group_id, cal_qty, sale_date, amount FROM sales WHERE $total_amt_cond)", 'alias'=>'Sale', 'type'=>'left', 'conditions'=>$saConditions));
				break;
				
			case 'Redistribution Sales':
				$joins = array(array('table'=>"(SELECT customer_id, brand_group_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE $total_amt_cond )", 'alias'=>'Sale', 'type'=>'left', 'conditions'=>$saConditions));
				break;
				
			default:
				$joins = array(array('table'=>"(SELECT customer_id,brand_group_id, cal_qty, sale_date, amount FROM sales WHERE $total_amt_cond UNION  SELECT customer_id, brand_group_id, cal_qty, sale_date, amount FROM redistributor_saleitems WHERE $total_amt_cond )", 'alias'=>'Sale', 'type'=>'left', 'conditions'=>$saConditions));
				break;
				
		}

        

        $fields = array('Customer.id', 'Customer.first_name', 'Customer.last_name', 'SUM(Sale.cal_qty) AS total_sale', 'SUM(Sale.amount) AS total_amount');

        $this->Customer->virtualFields['total_amount'] = 'SUM(Sale.amount)';

        $this->paginate['fields'] = $fields;
        $group = $this->paginate['group'] = array('Customer.id');
        $order = $this->paginate['order'] = array('total_amount'=>'desc');
        $this->paginate['joins'] = $joins;

//pr($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;
            }
            $customers = $this->Customer->find('all',array('fields' => $fields,'conditions' => $conditions,'joins'=>$joins,'order'=>$order, 'limit'=>EXPORT_LIMIT_15K, 'offset'=>$offset,'group'=>$group));
        }else{
            $customers = $this->paginate('Customer', $conditions); //pr($customers); //exit;
        }

        //Custom paging
        //$this->paginate['model'] = 'customer';
        //$this->paginate['date'] = $date;
        //$this->paginate['user'] = $this->user;
        //$this->loadModel('SaleActivity');
        //$customers = $this->paginate('SaleActivity', $conditions);

        $params = array_merge($navParams, compact('query','type', 'division_id','region_id','depot_id','date', 'prev', 'next', 'current','brand_group_id'));
        if ($customers){
            $this->Customer->saleActivity($customers, $params);
        }

        //$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')));
        $customerAvail = $this->Customer->customerListByRole($this->user);
        //$customerAvail = array();
        $this->set(compact('customers', 'brands', 'date', 'prev', 'next', 'current','strtotime','type','offset','query','customerAvail'));
        $this->_selectOptions();
        //if(!$this->request->is('ajax')){
            /*$this->render('sale_activity_report');*/
            if(isset($this->request->query['export'])){
                if($type == 'between'){
                    $fileName = 'Sale_activity_report_'.$query['from'].'_to_'.$query['to'];
                }else{
                    $fileName = 'Sale_activity_report_'.date('F_Y', $params['strtotime']);
                }

                $this->set('filename', $fileName);
                $this->render('export_sale_activity_report','export_xls');
			   //$this->render('export_sale_activity_report');
            }else{
				$this->render('sale_activity_report');
			}
        //}

    }
	
/**
 * Action: maps
 *
 * @var string
 */
	public function maps(){
		//$this->gradPermission(3);
		
		/* $conditions = array('Customer.status !=' => DELETED); */
		
		$userCond = array(); 
		$conditions = array('Customer.status' => ACTIVE, 'Customer.verified_latitude IS NOT NULL', 'Customer.verified_longitude IS NOT NULL', 'Customer.first_name IS NOT NULL', 'Customer.last_name IS NOT NULL');
		
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['Customer.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['Customer.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$userCond['User.state_id'] = $conditions['Customer.state_id'] = $this->request->query['st'];
		}
		if (!empty($this->request->query['dv']) ){
           $userCond['User.division_id'] = $conditions['Customer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$userCond['User.region_id'] = $conditions['Customer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$userCond['User.depot_id'] = $conditions['Customer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['usr'])) {
			$conditions['Customer.user_id'] = $this->request->query['usr'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Customer.route_id'] = $this->request->query['rt'];
		}		
		$this->Customer->_userCondition($conditions, $this->user);
		if (!empty($this->request->query['ofst']) ){
			$offset = $this->request->query['ofst'] - 1;
		}else{
			$offset= 0;
		} 
		$limit = 1000;
		//$totalCustomers = $this->Customer->find('count', array('conditions'=> $conditions));
		/* $customers = $this->Customer->find('all', array('conditions'=> $conditions,'offset'=>$offset, 'limit'=>1000, 'order'=>array('Customer.id'=>'desc')) ); */
		//pr($conditions);
		$customers = $this->Customer->find('all', array('conditions'=> $conditions,'offset'=>$offset, /* 'limit'=>1000, */ 'order'=>array('Customer.id'=>'desc')) ); 
		
		//pr(count($customers));
		//$endlimit = ($totalCustomers < $limit)? $totalCustomers: $limit;
		$this->set(compact('customers', 'totalCustomers', 'limit', 'offset', 'endlimit'));
		
		$this->_selectOptions($userCond);		
	}

/**
 * Action: maps
 *
 * @var string
 */
	public function deleteAllCustomers(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Customer->deleteAll(array('Customer.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Customer was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	 /*public function deleteAllCustomersvisit(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('CustomerVisit');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->CustomerVisit->deleteAll(array('CustomerVisit.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Customer Visit was deleted successfully') );
			$this->redirect(array('action'=>'visits'));
		}
		exit;
	}*/

    public function deleteAllCustomersvisit(){
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->loadModel('CustomerVisit');

        if(empty($cvisityear_tables)){
            $query = $this->request->query;
            if(!empty($query['from']) || !empty($query['to']) ){
                $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
            }else{
                $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
            }
        }//pr($query);exit;
        if(!empty($this->request->data['deleteAllValue'])){
            $cvAllIds = explode(",", $this->request->data['deleteAllValue']);
            foreach ($cvAllIds as $id){
                $this->CustomerVisit->deleteSingleVisitYearTable($id, $cvisityear_tables);
            }
            $this->Session->setFlash(__('All selected Customer Visit was deleted successfully') );
            $this->redirect(array('action'=>'visits'));
        }




        exit;
    }
  
  
/** Action send_sms
 * @params: @type (string), @opt(date)
 * return : void()
 */
	function send_sms($is_cust=''){
		if ($is_cust){
			$this->user_phones();
		
		}elseif(isset($this->request->query['smsToAll']) && $this->request->query['smsToAll'] == 'yes'){
			
		}elseif($this->request->data){
			if (!empty($this->request->data['phones'])){	
				$recipent = implode(",",$this->request->data['phones']);
			}elseif( !empty($this->request->data['query']) ){
				$query = json_decode($this->request->data['query'], true);
				
				$conditions = array('Customer.status !=' => DELETED);
				if (!empty($query['q']) ){
					$conditions['OR']['Customer.first_name LIKE'] =  '%'.$query['q'].'%';
					$conditions['OR']['Customer.last_name LIKE'] =  '%'.$query['q'].'%';
				}
				if (!empty($query['st']) ){
					$conditions['Customer.state_id'] = $query['st'];
				}
				if (!empty($query['rg']) ){
					$conditions['Customer.region_id'] = $query['rg'];
				}
				if (!empty($query['dp']) ){
					$conditions['Customer.depot_id'] = $query['dp'];
				}
				
				if (!empty($query['usr']) ){
					$conditions['Customer.user_id'] = $query['usr'];
				}
				
				if ( !empty($query['from']) && !empty($query['to'])){
					$conditions[] = array('Customer.created BETWEEN ? AND ?' => array($query['from'], $query['to']));			
				}elseif (!empty($query['from'])){
					$conditions['Customer.created >= '] = $query['from'];
				} elseif (!empty($query['to'])){
					$conditions['Customer.created <= '] = $query['to'];
				}
				
				$this->Customer->_userRoleCondition($conditions, $this->user, $this->paginate);
				$customers = $this->Customer->find('list',array('fields'=>array('id','phone'), 'conditions' =>$conditions));
				
				$recipent = implode(",",$customers);
			}
				
				
			if(!empty($recipent)){	
				$ch = curl_init(); 
				if( !empty($this->request->data['sender']) ){
					$sender = trim($this->request->data['sender']);
				}else{
					$sender = 'y3dist';
				}
				$message = trim($this->request->data['message']);
				$message = urlencode($message);
				$url = "http://www.netbulksms.com/components/com_spc/smsapi.php?username=Y3dist&password=y3dist&sender=$sender&recipient=$recipent&message=$message";
				$output = "";
				curl_setopt($ch,CURLOPT_URL,$url);
				curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
				$output = curl_exec($ch);
				curl_close($ch);				
				echo $output;
			}else{
				echo __('No recipient phone number found, please try again');
			}
			exit;
		}
			
	}
/* Action send_sms
* @params: @type (string), @opt(date)
* return : void()
*/
	function user_phones($user=null){
				
		$userid = $this->request->query['userid'];
		$customersData = $this->Customer->find('all',array('fields'=>array('Customer.id', 'Customer.first_name','Customer.last_name','Customer.phone'),'conditions'=>array('Customer.id' => explode(",",$userid ) )));
		$str='<ul calss="smsuser">';
	    foreach($customersData as $customersDatas){
           $str .= "<input id='phone_".$customersDatas['Customer']['id']."' type='hidden' name='phones[]' value='".$customersDatas['Customer']['phone']."' /><li class='rad5' cid='".$customersDatas['Customer']['id']."' id='label".$customersDatas['Customer']['id']."'>".$customersDatas['Customer']['phone'].' ('.$customersDatas['Customer']['first_name'].')'."</li>";
		}
		$str .= '</ul>';
		//$return = pr($customersData);
		echo $str;
		exit;
	}
/* Action send_sms
* @params: @type (string), @opt(date)
* return : void()
*/
	function send_message($user=null){
				
		$userid = $this->request->query['senduserID'];
		$mesage = $this->request->query['mesage'];
		$customersData = $this->Customer->find('all',array('fields'=>array('Customer.first_name','Customer.last_name','Customer.phone'),'conditions'=>array('Customer.id' => impload(",",$userid ))));
		$str='';
	    foreach($customersData as $customersDatas){
           $str .=$customersDatas['Customer']['phone'].',';
		}
        
		$this->smspage_callback($str,$mesage);
		//$return = pr($customersData);

		echo json_encode("Message sent successfully");
		exit;
	}

	function smspage_callback($phonestr,$message) {
		//http://www.netbulksms.com/components/com_spc/smsapi.php?username=xxx&password=yyy&sender=qqq&recipient=www&message=test
		http://www.netbulksms.com/components/com_spc/smsapi.php?username=xxx&password=yyy&sender=qqq&recipient=www&message=test

/*username: Y3dist
Password is y3dist
Anya Ugochukwu Mobile: 08129915553 */
		
		$ch = curl_init();  
		$recipent = implode(",", $this->request->data['phones']);
		$message = trim($this->request->data['message']);
		$url = "http://www.netbulksms.com/components/com_spc/smsapi.php?username=xxx&password=yyy&sender=y3dist&recipient=$recipent&message=$message";

		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_HEADER, false); 

		$output = curl_exec($ch);

		curl_close($ch);
		
		echo $output;
		exit;
    }

    public function customer_verify($id = 0, $unverify = 0 ){
		if($this->request->is('post')){
			$verifyStatus = ($unverify == 0)?$this->user['id']:0;
			if($id){
				$this->Customer->id = $id;
				$customer = $this->Customer->saveField('verified', $verifyStatus);
				if($unverify){
					$this->Session->setFlash(__('Customer unverified successfully'));
				}else{
					$this->Session->setFlash(__('Customer verified successfully'));
				}
			}elseif(!empty($this->request->data['deleteAllValue'])){
				$this->Customer->updateAll(array('Customer.verified'=>$verifyStatus ), array('Customer.id'=>explode(",", $this->request->data['deleteAllValue'])) );
				if($unverify){
					$this->Session->setFlash(__('All selected customer was unverified successfully') );
				}else{
					$this->Session->setFlash(__('All selected customer was verified successfully') );
				}
			}
			
		}
		if(!$this->request->is('ajax')){
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	public function customer_unverify($id = 0 ){
		$this->customer_verify($id, 1);
	}
	public function previousdayactivity($cid = null){
		$this->set(compact('cid'));
	}
	/* function _updateAttendance_visitentry(){
		$this->loadModel('Attendance');
		$date = date('Y-m-d');
		$data = array();
		$emp_id = $this->Auth->user('employee_id');
		if(!empty($emp_id)){
			$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
			
			if(empty($attendance) ){
				if($attendance['Attendance']['in_time'] == ''){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> date('Y-m-d H:i:s'), 'in_time'=> date('H:i:s'), 'date'=>$date);
				}
				$this->Attendance->save($data);
			}
			else{

				$this->_updateAttendance_visitexit();
			}
		} 
	}
	function _updateAttendance_visitexit(){
		$this->loadModel('Attendance');		
		$date = date('Y-m-d');
		$data = array();
		$emp_id = $this->Auth->user('employee_id');
		$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
		
		$cnt = $this->Attendance->find('count', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
		
			if($attendance){
				if($attendance['Attendance']['out_time'] == ''){
                    if($cnt < 2){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
                    }else{
                    $data['Attendance'] = array('id' =>$attendance['Attendance']['id'],'emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
                    }
                }else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'], 'out_time' => date('H:i:s'), 'punch_time' => date('Y-m-d H:i:s'));
				}
				$this->Attendance->save($data);
			}
	} */
	
	
	/*This function use for HRMS attendance update from apps*/
	
	/* function _updateAttendance_visitentry($id,$cdate){
		$this->loadModel('User');
		$eid = $this->User->find('first', array('fields'=> array('employee_id'), 'conditions'=>array('User.id' => $id)));
		$emp_id = $eid['User']['employee_id'];
		
		$this->loadModel('Attendance');
		//$this->loadModel('Employee');
		//$this->loadModel('Company');
		//$this->Attendance->useDbConfig = 'hrminfo';
		//$this->Employee->useDbConfig = 'hrminfo';
		//$this->Company->useDbConfig = 'hrminfo';
		if(!empty($emp_id)){
			$date = date('Y-m-d',strtotime($cdate));
			$data = array();
			$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
			if(empty($attendance) ){
				if($attendance['Attendance']['in_time'] == ''){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $cdate, 'in_time'=> date('H:i:s',strtotime($cdate)), 'date'=>$date);
				}
				$this->Attendance->save($data);
			}
			else{
				$this->_updateAttendance_visitexit($emp_id,$cdate);
			}
		} 
	}
	function _updateAttendance_visitexit($emp_id,$cdate){
		$this->loadModel('Attendance');
		//$this->loadModel('Employee');
		//$this->loadModel('Company');
		//$this->Attendance->useDbConfig = 'hrminfo';
		//$this->Employee->useDbConfig = 'hrminfo';
		//$this->Company->useDbConfig = 'hrminfo';
		
		$date = date('Y-m-d',strtotime($cdate));
		$data = array();
		
		$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date),'order' => array('id'=>'DESC')));
		
		$cnt = $this->Attendance->find('count', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
		
			if($attendance){
				if($attendance['Attendance']['out_time'] == ''){
					if($cnt < 2){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $cdate, 'out_time'=> date('H:i:s',strtotime($cdate)), 'date'=>$date);
					}else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'],'emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $cdate, 'out_time'=> date('H:i:s',strtotime($cdate)), 'date'=>$date);
					}
				}else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'], 'out_time' => date('H:i:s',strtotime($cdate)), 'punch_time' => $cdate);
				}
				$this->Attendance->save($data);
			}
	} */
	
	
	
	
	public function bikesupervisor_checklist($opr='', $id=0){
		$this->loadModel('BikesupervisorChecklist');
		$conditions = array();

		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		switch($opr){
			case 'add';
				//$this-> _add_bikesupervisor_checklist(); 
			case 'edit':
				$this->roleBasePermission(array(SUPPORT));
				$this->_update_bikesupervisor_checklist($id);
			break;
			case 'delete':
				$this->_delete_bikesupervisor_checklist($id);
			break;
			case 'view':
				$this->BikesupervisorChecklist->id = $id;
				$checklist = $this->BikesupervisorChecklist->read();
				$this->set('checklist', $checklist);
				$this->render('view_bikesupervisor_checklist');
			break;
			default:
			
				$userCond = array();
				
				if (!empty($this->request->query['q']) ){
					$conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
					$conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
				}
				
				if(!empty($this->request->query['dv']) && empty($this->request->query['rg'])){
					$userCond['User.division_id'] = $conditions['Customer.division_id'] = $this->request->query['dv'];
					
                    $division_id = $this->request->query['dv'];
                    $divisionRegion = ClassRegistry::init('DivisionsRegion');
                    $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' =>$this->request->query['dv'])));
                    $conditions['BikesupervisorChecklist.region_id IN'] = $rIds;
                }else{
                    $division_id = 0;
                }
				if (!empty($this->request->query['rg']) ){
					$userCond['User.region_id'] = $conditions['Customer.region_id'] = $this->request->query['rg'];
					$conditions['BikesupervisorChecklist.region_id'] = $this->request->query['rg'];
				}
				
				if (!empty($this->request->query['dp']) ){
					$userCond['User.depot_id'] = $conditions['Customer.depot_id'] = $this->request->query['dp'];
					$conditions['BikesupervisorChecklist.depot_id'] = $this->request->query['dp'];
				}
				
				if (!empty($this->request->query['usr']) ){
					$conditions['BikesupervisorChecklist.user_id'] = $this->request->query['usr'];
				}
				
				if (!empty($this->request->query['checklist']) && !empty($this->request->query['status']) ){
					$conditions['BikesupervisorChecklist.'.$this->request->query['checklist']] = $this->request->query['status'];
				}
				
				if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
					$conditions[] = array('BikesupervisorChecklist.check_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to'].' 23:59:59' ));
					
				}elseif (!empty($this->request->query['from'])){
					$conditions['BikesupervisorChecklist.check_date >= '] = $this->request->query['from'];
				} elseif (!empty($this->request->query['to'])){
					$conditions['BikesupervisorChecklist.check_date <= '] = $this->request->query['to'];
				}
			   	if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
					$conditions[] = array('BikesupervisorChecklist.modified BETWEEN ? AND ?' => array($this->request->query['mfrom'], $this->request->query['mto']));
				} 
				//$this->CustomerVisit->visibleConditions($conditions, $this->user);
				$this->BikesupervisorChecklist->visibleroleConditions($conditions, $this->user, $this->paginate);
				$order=$this->paginate['order'] = array('BikesupervisorChecklist.id' => 'desc');
				
				$contain = $this->BikesupervisorChecklist->contain(array(
								'User' => array(
									'fields' => array('name')
								),
								'Customer' => array(
									
									'Route' => array(
										'fields' => array('title')
									),
									'fields' => array('name'),
								),
								'Region' => array(
									'fields' => array('title')
								),
								'Depot' => array(
									'fields' => array('title')
								),
							));
				
				$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;
					}
						
					$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();		
					$checklists = $this->BikesupervisorChecklist->find('all',array('contain'=>$contain,'conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
				} else {
				    $checklists = $this->paginate('BikesupervisorChecklist', $conditions);
				}
				
				/* $this->loadModel('Division');
				$this->loadModel('Region');
				$this->loadModel('Depot');
				$this->loadModel('User');
				$divisions = $this->Division->getList();
                $regions = $this->Region->getList($division_id);
				$depots = $this->Depot->getList();
				$users = $this->User->usersList(); */
				$Opdata =  array();
				$param = isset($querystring ) ? $querystring  : array();

				$this->Option->Options($Opdata, $this->user, $param);
				
				/* $this->loadModel('User');
				$users = $this->User->usersListByRole();  */
				
				$this->_selectOptions($userCond, true);
				
				$this->set(compact('offset','checklists', 'users','querystring'));

				if(isset($this->request->query['export'])){
					$this->set('filename','bike_supervisor_checklist'); 						 
					$this->render('export_bike_supervisor_checklist','export_xls');
				}
				
			break;
		}
	}
	
 
	
	function _update_bikesupervisor_checklist($id){
		$this->loadModel('Audit');
		if ($id){
				$this->BikesupervisorChecklist->id = $id;
				$checkData = $this->BikesupervisorChecklist->read();//pr($visitData);
				$checkData['BikesupervisorChecklist'] = serialize($checkData['BikesupervisorChecklist']);
			}
		if ($this->request->data){ //pr($this->request->data); die();
			if (!$id){
				$this->request->data['BikesupervisorChecklist']['user_id'] = $this->user['id'];
			}
			//Get customer's depot_id
			$customer = $this->Customer->findById($this->request->data['BikesupervisorChecklist']['customer_id']);
			$this->request->data['BikesupervisorChecklist']['division_id'] = $customer['Customer']['division_id'];
			$this->request->data['BikesupervisorChecklist']['region_id'] = $customer['Customer']['region_id'];
			$this->request->data['BikesupervisorChecklist']['depot_id'] = $customer['Customer']['depot_id'];
			
		/* 	$this->request->data['BikesupervisorChecklist']['region_id'] = $this->user['region_id'];
			$this->request->data['BikesupervisorChecklist']['depot_id'] = $this->user['depot_id']; */
			
			
			if (empty($this->request->data['BikesupervisorChecklist']['check_date'])){
				$this->request->data['BikesupervisorChecklist']['check_date'] = date('Y-m-d H:i:s');
			}
			if($this->BikesupervisorChecklist->save($this->request->data) && !empty($checkData)){ 
				$this->Audit->saveDeletedData($checkData['BikesupervisorChecklist'], 'BikesupervisorChecklist', $this->Auth->user('id') , $checkData['BikesupervisorChecklist'],'Bike Rep Supervisor Checklist Has been Updated',STATUS_EDIT);
			}
			//$this->Customer->verify_status($this->request->data['CustomerVisit']['customer_id']);
			$this->Session->setFlash('Last Record was save successfully');
			$this->redirect(array('action'=>'bikesupervisor_checklist'));
		}
		/* $this->loadModel('Depot');
		$depots = $this->Depot->getList(); */
		$customers = $this->Customer->customerListByRole($this->user);
		
		$opration = __('Add');
		if ($id){
			$this->BikesupervisorChecklist->id = $id;
			$this->request->data = $this->BikesupervisorChecklist->read();
			$opration = __('Update');
		}
		$this->set(compact('customers', 'opration'));
		$this->render('update_bikesupervisor_checklist');
	}
	
	function _delete_bikesupervisor_checklist($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->BikesupervisorChecklist->id = $id;
        if (!$this->BikesupervisorChecklist->exists()) {
            throw new NotFoundException(__('Invalid BikeRep Supervisor Checklist'));
        }
		$customerId = $this->BikesupervisorChecklist->field('customer_id');	
		$BikesupervisorChecklist = $this->BikesupervisorChecklist->read();
			$data = array();
		$data['serialize'] = serialize($BikesupervisorChecklist);
		$data['model_id'] = $BikesupervisorChecklist['BikesupervisorChecklist']['id'];
		if ($this->BikesupervisorChecklist->delete()) {
			$this->loadModel('Customer');	
			$this->loadModel('Audit');		
			
			//$this->Customer->verify_status( $customerId );
			$this->Audit->saveDeletedData($data['model_id'], 'BikesupervisorChecklist', $this->Auth->user('id') , $data['serialize'],'BikeRep SupervisorChecklist Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('BikeRep SupervisorChecklist was deleted successfully'));
            $this->redirect(array('action' => 'bikesupervisor_checklist'));
        }
        $this->Session->setFlash(__('BikeRep SupervisorChecklist was not deleted'));
        $this->redirect(array('action' => 'bikesupervisor_checklist'));
	}
	
	public function deleteAllBikesupervisorChecklist(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('BikesupervisorChecklist');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->BikesupervisorChecklist->deleteAll(array('BikesupervisorChecklist.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected BikeRep SupervisorChecklist was deleted successfully') );
			$this->redirect(array('action'=>'bikesupervisor_checklist'));
		}
		exit;
	}
	
	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');
                }

                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: customer_visits_table_auto_organise
     * Desc: rename current customer_visits table to customer_visits_[YEAR] (eg: customer_visits_2021)
     * create a structure of renamed table to customer_visits with autoincrement value to the table
     * run via cron
     * Note: [YEAR] is the year value of the just prev year of the new year
     * Author: Sridhar
     * Date: 15 Nov 2021
     *-----------------------------------------------------*/
    function customer_visits_table_auto_organise(){
        $this->loadModel('CustomerVisit');
        $APPMODE = "LIVE";

        if($APPMODE =='LIVE'){
            $this->CustomerVisit->customer_visits_table_auto_organise();
            exit;
        }else{
            exit;
        }

    }
}
