<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::import('Controller', 'Functions');
/**
 * Controller name
 *
 * @var string
 */
class ServicesController extends AppController
{
	var $response;
	var $user;
	var $appLogs;
	var $uses = array('User', 'Service');
	var $token;
	public $paginate = array(
		'paramType' => 'querystring'
	);
	var $components = array('FileUpload' => array(
							'allow_non_image_files' => false
						));
	function beforeFilter(){
		$this->Auth->allow();
		
		$this->response = $data = array();		
		$this->response['error'] = 2;
		//Log Entry
		$this->loadModel('AppLog');
		$logData = array('input'=>serialize($this->request->data), 'url'=>$this->request->url ) ;
		//pr($this->request->data['jsonString']);
		if (!empty($this->request->data['jsonString'])){
			$string = preg_replace("/[\r\n\t]+/", " ", $this->request->data['jsonString']);
			$jsonString = utf8_encode($string);
			$this->request->data = json_decode($jsonString, true );			
		}
		
		if (!empty($this->data['token']) || !empty($this->request->query['token'])){
			$this->token = isset($this->data['token'])? $this->data['token'] : $this->request->query['token'];
			$this->user = $this->User->findBySessionToken($this->token);
			if(APP_LOGS){
				$this->appLogs = $this->AppLog->save($logData);
			}
			if($this->user){
				$this->user = array_merge($this->user['User'], $this->user);
				$logData['user_id'] = $this->user['id'];			
			}
			
			if(!empty($this->user['User']['status']) && $this->user['User']['status'] != ACTIVE){
			//if($this->user['status'] != ACTIVE){
				$this->response['error'] = 5;
				$this->response['message'] = 'Your account has been inactivated. Please contact administrator.';
				echo json_encode($this->response);
				$logData['output'] = serialize($this->response); 
				if(APP_LOGS){
					$this->appLogs = $this->AppLog->save($logData);
				}
				exit;
			}
			
			if(!$this->user){
				$this->response['message'] = 'Invalid token';
				$this->response['error'] = 3;
				echo json_encode($this->response);
				
				$logData['output'] = serialize($this->response); 
				if (!empty($this->appLogs['AppLog']['id']) && APP_LOGS){
					$this->AppLog->id = $this->appLogs['AppLog']['id'];
					$this->appLogs = $this->AppLog->save($logData);
				}				
				exit;
			}
			
			
		}else{
			
			$this->response['message'] = 'Invalid request';
			echo json_encode($this->response);
			$logData['output'] = serialize($this->response); 
			if(APP_LOGS){
				$this->appLogs = $this->AppLog->save($logData);
			}
			exit;
		}	
		
		//Check for duplicate request
		if (!empty($this->request->data['request_id']) && APP_LOGS){
			$rdData = $this->Service->getRequestLogs($this->request->data['request_id']);
			if ($rdData){
				//if ($rdData['status'] == 0 || $rdData['status'] == '0'){
				if ($rdData['status'] == 0 || $rdData['status'] == 4) {	
					echo json_encode(unserialize($rdData['response']), JSON_ERROR_CTRL_CHAR );
					exit;
				}
			}
		}
	}
	
	
	
	/**
	 * getAppSettingsData Action
	 * default list of comon data
	 */
	function getAppSettingsData(){
		//echo 'dfsdf';
		//pr($this->request);
		//die();
		$data = array();
		$this->loadModel('State');
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$this->loadModel('LgArea');
		$this->loadModel('Brand');
		$this->loadModel('Customer');
		$this->loadModel('Consumer');
		$this->loadModel('Redistributor');
		$this->response['error'] = 0;
		
		/**  Current Year Calendar **/
		$current_year_calendar = $this->getYearlyCalendar(date("Y"));
		$this->user['current_year_calendar'] = $current_year_calendar;
		
		/**  Current Month No **/
		$current_month_no = getMonthNo($current_year_calendar, date('Y-m-d'));
		$this->user['current_month_no'] = $current_month_no;
				
		$monthArray = $current_year_calendar[$current_month_no];
		
		/** Get Current Month's Weeks **/
		$current_week_no = getWeekNo($monthArray, date('Y-m-d'));
		$this->user['current_week_no'] = $current_week_no;

		$depots = $this->Depot->find('all', array('fields'=>array('id', 'title', 'region_id'), 'order' => array('title'=>'asc')));
		
		$data['depots'] = ($depots)?$depots:null;
		//$regions = $this->Region->find('all', array('fields' => array('id', 'title'), 'order' => array('title'=>'asc')));
		$data['regions'] = $this->Service->reagionList(); //$regions;		
		//LGA Conditions
		$lgaConditions = array();
		if(!empty($this->user['Role']['grade']) && $this->user['Role']['grade'] > 2){
			$lgaConditions['state_id'] = $this->user['state_id'];
		}
		$data['lgas'] = $this->LgArea->find('all', array('conditions'=>$lgaConditions, 'order' => array('name'=>'asc')));
		$data['states'] = $this->Service->statesList();
		
		
		if($this->user['Role']['id'] == DH || $this->user['Role']['grade'] == SalesRep || $this->user['Role']['grade'] == BikeRep){		
			$data['routes'] = $this->Service->routesList($this->user);
		}else{
			$data['routes'] = $this->Service->routesList();
		}
		
		//$data['states'] = $this->State->find('list', array('fields' => array('id', 'state'), 'order' => array('state'=>'asc')));
		
		$users = $this->User->usersListByRole($this->user, true);
		if ($users){
			$data['users'] = $users;
		}else{
			$data['users'] = null;
		}
		
		/* all users in below depot see only Allstars Niger brand while making sales entry on the mobile.
			a.	Kano 2 – Maradi
			b.	Sokoto 2 – Dosso 
		*/
		$brandCond['Brand.status'] = 1; //pr($this->user['depot_id']);  pr(SOKOTO2DOSSO); pr(KANO2MARADI);
		if(($this->user['depot_id'] == SOKOTO2DOSSO) || ($this->user['depot_id'] == KANO2MARADI)){
			$brandCond['Brand.id'] = ALLSTARSNIGERRETAIL;
		}
		//pr($brandCond);
		$data['brands'] = $this->Brand->find('all', array('conditions'=>$brandCond));
		
		
		$data['userTargets'] = $this->Service->targetCalStatus($this->user['id']);
		$distributors = $this->Service->getDistributorList();
		$data['distributors'] = ($distributors)?$distributors:null;
		
		$data['paymentMode'] = $this->Service->paymentMode();
		$data['bankList'] = $this->Service->bankList();
		
		$expenseTypeList = $this->Service->expenseTypeList();		
		$data['expenseTypeList'] = ($expenseTypeList)?$expenseTypeList:null;
		 $data['comment'] = $this->Service->comment();
		$redistributors = $this->Redistributor->redistributorListByRole($this->user, true);
		if($redistributors){
			$data['redistributors'] = $redistributors;
		}else{
			$data['redistributors'] = null;
		}
		$data['units'] = get_units();
		$data['incentiveType'] = incentive_type();
		
		$this->_compaignStatusCheck();
		$this->loadModel('Compaign');
		
		$activeCompaigns = $this->Compaign->find('all', array('conditions'=>array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date")));
		if ($activeCompaigns){
			$data['activeCompaigns'] = $activeCompaigns;
		}else{
			$data['activeCompaigns'] = null;
		}
		
		$this->_eventStatusCheck();
		
		$this->loadModel('Calendar');		
		$this->loadModel('CalendarUser');
		$this->loadModel('CalendarDepot');
		$this->loadModel('CalendarRegion');
		
		$cal_uId = $this->CalendarUser->find('list',array('fields'=>array('id','calendar_id'),'conditions'=>array('user_id'=>$this->user['id']))); //pr($cal_uId);
		
		$cal_dId = $this->CalendarDepot->find('list',array('fields'=>array('depot_id','calendar_id'),'conditions'=>array('depot_id'=>$this->user['depot_id']))); //pr($cal_dId);
		
		$cal_rId = $this->CalendarRegion->find('list',array('fields'=>array('region_id','calendar_id'),'conditions'=>array('region_id'=>$this->user['region_id']))); //pr($cal_rId);
		
		
		$cal_ids = array_unique (array_merge ($cal_uId, $cal_dId, $cal_rId)); //pr($cal_ids);
		
		
		$this->Calendar->unbindModel(
			array('hasAndBelongsToMany' => array('User', 'Depot','Region'))
		);
		$activeEvents = $this->Calendar->find('all', array('conditions'=>array('Calendar.id'=>$cal_ids,'Calendar.status'=>ACTIVE, "'".date('Y-m-d H:i:s')."' between Calendar.eventopendate AND Calendar.eventclosedate"))); //pr($activeEvents);
		
		/* $activeEvents = $this->Calendar->find('all', array('conditions'=>array('Calendar.status'=>ACTIVE, "'".date('Y-m-d')."' between Calendar.eventopendate AND Calendar. 	eventclosedate"))); */
		if ($activeEvents){
			$data['activeEvents'] = $activeEvents;
			$data['eventCount'] = count($activeEvents);
		}else{
			$data['activeEvents'] = null;
			$data['eventCount'] = 0;
		}
		
		$customer = $this->Customer->customerListByRole($this->user, true);
		$data['customers'] = $customer['customersList'];
		$data['customersWithDepot'] = $customer['customers'];
		
		$data['consumers'] = array();
		//$consumer = $this->Consumer->consumerListByRole($this->user, true);
		//$data['consumers'] = $consumer['consumersList'];
		//$data['customersWithDepot'] = $customer['customers'];
		
		/** Get User's Assets **/
		$this->loadModel('AssetUser');
		$this->AssetUser->bindModel(
			array('belongsTo' => array(
					'Asset' => array('Asset' => 'User', 'foreignKey' => 'asset_id', 'fields' => array('id', 'number'), 'type'=>'left'),
				)
			)
		); 
		
		$assets = [];
		$assetData = $this->AssetUser->find('all', array('fields'=>array('Asset.id', 'Asset.number', 'Asset.status'), 'conditions' => array('AssetUser.user_id' => $this->user['id'], 'Asset.status' => ACTIVE))); 
		if(!empty($assetData)){
			foreach($assetData as $k => $asset){
				$assets[$k]['id'] = $asset['Asset']['id'];
				$assets[$k]['number'] = $asset['Asset']['number'];
			}
		}		
		
		$data['userAssets'] = $assets;
		
		$this->loadModel('ExpType');
		$assetExpTypes = $this->ExpType->find('list', array('fields' => array('id' , 'name'), 'conditions' => array('ExpType.category_id IN' => [EXP_CAT_MO_BIKE, EXP_CAT_MO_VEHICLE])));
		
		$data['assetExpTypes'] = $assetExpTypes;
		
		$customer_categories = getCustomerCategories();
		$data['customerCategories'] = array_keys($customer_categories);
		
		$this->response['data'] = $data;
		echo json_encode($this->response);
		exit;
	}
	
	function _compaignStatusCheck(){
		$this->loadModel('Compaign');
		//$this->Compaign->recursive = -1;
		$this->Compaign->unBindModel(array('hasAndBelongsToMany'=>array('Customer', 'Route', 'Depot', 'Region'), 'belongsTo' => array('Brand')));
		
		$inactive_campaign = $this->Compaign->find('list', array('fields'=>array('id'), 'conditions'=>array('Compaign.status'=>ACTIVE, 'Compaign.end_date <' =>date('Y-m-d')))); 
		
		if(!empty($inactive_campaign)){
			$this->Compaign->updateAll(
				array('Compaign.status' =>INACTIVE),
				array('Compaign.id' => $inactive_campaign)
			);
		}
	}
	
	function _eventStatusCheck(){
		$this->loadModel('Calendar');
		$this->Calendar->recursive = -1;
		
		$inactive_events = $this->Calendar->find('list', array('fields'=>array('id'), 'conditions'=>array('Calendar.status'=>ACTIVE, 'Calendar.eventclosedate <' =>date('Y-m-d H:i:s')))); 
		
		if(!empty($inactive_events)){
			$this->Calendar->updateAll(
				array('Calendar.status' =>INACTIVE),
				array('Calendar.id' => $inactive_events)
			);
		}
	}
	
	function getEventData(){
		//echo 'dfsdf';
		//pr($this->request);
		//die();
		$data = array();
		
		$this->loadModel('Calendar');		
		$this->loadModel('CalendarUser');
		$this->loadModel('CalendarDepot');
		$this->loadModel('CalendarRegion');
		
		$cal_uId = $this->CalendarUser->find('list',array('fields'=>array('id','calendar_id'),'conditions'=>array('user_id'=>$this->user['id']))); //pr($cal_uId);
		
		$cal_dId = $this->CalendarDepot->find('list',array('fields'=>array('depot_id','calendar_id'),'conditions'=>array('depot_id'=>$this->user['depot_id']))); //pr($cal_dId);
		
		$cal_rId = $this->CalendarRegion->find('list',array('fields'=>array('region_id','calendar_id'),'conditions'=>array('region_id'=>$this->user['region_id']))); //pr($cal_rId);
		
		
		$cal_ids = array_unique (array_merge ($cal_uId, $cal_dId, $cal_rId)); //pr($cal_ids);
		
		
		$this->Calendar->unbindModel(
			array('hasAndBelongsToMany' => array('User', 'Depot','Region'))
		);
		$activeEvents = $this->Calendar->find('all', array('conditions'=>array('Calendar.id'=>$cal_ids,'Calendar.status'=>ACTIVE, "'".date('Y-m-d H:i:s')."' between Calendar.eventopendate AND Calendar.eventclosedate"))); //pr($activeEvents);
		
		/* $activeEvents = $this->Calendar->find('all', array('conditions'=>array('Calendar.status'=>ACTIVE, "'".date('Y-m-d')."' between Calendar.eventopendate AND Calendar. 	eventclosedate"))); */
		if ($activeEvents){
			$data['activeEvents'] = $activeEvents;
			$data['eventCount'] = count($activeEvents);
		}else{
			$data['activeEvents'] = null;
			$data['eventCount'] = 0;
		}
		
		
		$this->response['data'] = $data;
		echo json_encode($this->response);
		exit;
	}
	
	
	function getMoreCustomer(){
		
		/**  Current Year Calendar **/
		$current_year_calendar = $this->getYearlyCalendar(date("Y"));
		$this->user['current_year_calendar'] = $current_year_calendar;
		
		/**  Current Month No **/
		$current_month_no = getMonthNo($current_year_calendar, date('Y-m-d'));
		$this->user['current_month_no'] = $current_month_no;
				
		$monthArray = $current_year_calendar[$current_month_no];
		
		/** Get Current Month's Weeks **/
		$current_week_no = getWeekNo($monthArray, date('Y-m-d'));
		$this->user['current_week_no'] = $current_week_no;
		
		//pr($this->request->data);
		$this->loadModel('Customer');
		$this->response['error'] = 0;
		$data = array();
		$customer = $this->Customer->moreCustomerListByRole($this->user, $this->request->data['customerIds']);
		if ($customer['customersList']){
			$data['customers'] = $customer['customersList'];
		}else{
			$this->response['error'] = 2;
			$this->response['message'] = __('No more customer is there');
		}
		$this->response['data'] = $data; //$this->request->data;
		echo json_encode($this->response);
		exit;
	}
	function customersList(){
		
		/**  Current Year Calendar **/
		$current_year_calendar = $this->getYearlyCalendar(date("Y"));
		$this->user['current_year_calendar'] = $current_year_calendar;
		
		/**  Current Month No **/
		$current_month_no = getMonthNo($current_year_calendar, date('Y-m-d'));
		$this->user['current_month_no'] = $current_month_no;
				
		$monthArray = $current_year_calendar[$current_month_no];
		
		/** Get Current Month's Weeks **/
		$current_week_no = getWeekNo($monthArray, date('Y-m-d'));
		$this->user['current_week_no'] = $current_week_no;
		
		$this->loadModel('Customer');
		$customer = $this->Customer->customerListByRole($this->user, true);
		$customers = $customer['customersList'];
		$this->response['error'] = 0;
		if ($customers){
			$data['customers'] = $customers;
		}else{
			$data['customers'] = null;
		}
		
		$this->response['data'] = $data;
		echo json_encode($this->response);
		exit;		
	}
	public function customers(){
		$this->loadModel('Customer');
		$this->loadModel('User');
		//$conditions = array();
		$conditions = array('Customer.status' => ACTIVE);
		$this->Customer->hasMany = array('CustomerAssign' => array('className' => 'CustomerAssign', 'foreignKey' => 'customer_id', 'fields' => array( 'user_id'), 'type'=>'left') );
		
		//$this->Customer->_userCondition($conditions, $this->user);
		$this->Customer->_userRoleCondition($conditions, $this->user, $this->paginate);
		
		$this->paginate['order'] = array('Customer.first_name'=>'asc', 'Customer.last_name'=>'asc');
		$this->response['error'] = 0;
		$customers = $this->paginate('Customer', $conditions);
		
		$i = ($this->params->params['paging']['Customer']['page'] - 1) * $this->params->params['paging']['Customer']['limit'];
		if ($customers){
			$users = $this->User->usersList();
			foreach($customers as $key => $customer){
				if($customer['File']['name']){
					$path = Router::url('/files/photos/small/' . $customer['File']['name'], true);
				}else{
					$path = Router::url('/files/photos/small/default_small.jpg', true);
				}
				$customers[$key]['Customer']['image_path'] = $path;
				
				$customers[$key]['sno'] = ++$i;
				
				if (!empty($customer['CustomerAssign'])){
					foreach($customer['CustomerAssign'] as $assignTo){
						$uid = @$assignTo['user_id'];
						if (!empty($users[$uid])){
							$customers[$key]['assignTo'][$uid] = $users[$uid];
						}
					}
					
				}else{
					$customers[$key]['assignTo'] = null;
				}
				unset($customers[$key]['CustomerAssign']);
			}
		}
		$this->response['data'] = $customers;
		$paging = array();
		$paging['page'] = $this->params->params['paging']['Customer']['page'];
		$paging['current'] = $this->params->params['paging']['Customer']['current'];
		$paging['count'] = $this->params->params['paging']['Customer']['count'];
		$paging['pageCount'] = $this->params->params['paging']['Customer']['pageCount'];
		
		if (!empty($this->params->params['paging']['Customer']['prevPage'])){
			$paging['prev'] = Router::url(array('controller'=>'services', 'action'=>'customers', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Customer']['page'] - 1), 'ext'=>'json'), true);
		}
		if (!empty($this->params->params['paging']['Customer']['nextPage'])){
			
			$paging['next'] = Router::url(array('controller'=>'services', 'action'=>'customers', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Customer']['page'] + 1), 'ext'=>'json'), true);
		}
	
		$this->response['paging'] = $paging;
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function updatecustomer(){
		$this->loadModel('Customer');
		//pr($this->data);
		
		if ($this->request->data){
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			$is_exists = 0;
			if (!empty($this->request->data['phone']) ){
				$this->request->data['phone'] = trim($this->request->data['phone']);
				$conditions = array('Customer.phone'=>$this->request->data['phone']);
				if(!empty($this->request->data['id'])){
					$conditions['Customer.id != '] = $this->request->data['id'];
					
				}
				$is_exists = $this->Customer->find('count', array('conditions'=>$conditions));
			}
			
			if ($is_exists > 0){
				$this->response['message'] = __('This customer already exists');
				$this->response['error'] = SYNC_NOT_REQUIRED;
			}else{
				$image_ok = true;
				//$this->response['files'] = $_FILES;
				if($_FILES){
					$this->request->data['image'] = $_FILES['image'];
				}
				if (!empty($this->request->data['image']['name'])){
					if ($this->FileUpload->upload($this->request->data,'image')) {
						$this->request->data['file_id'] = $this->FileUpload->fileId;
						if (!empty($this->request->data['oldFile_id'])){
							$this->FileUpload->removeFileId($this->request->data['oldFile_id']);
						}
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					if (empty($this->request->data['id'])){
						$this->request->data['user_id'] = $this->user['User']['id'];
					}elseif(!empty($this->request->data['id'])){
						//unset($this->request->data['user_id']);
					}
					//$this->response['data'] = $customer = $this->Customer->save($this->request->data);
					if(isset($this->request->data['view_details']) && $this->request->data['view_details'] == true){
						$this->request->data['view_details'] = 1;
					}
					
					/* $this->request->data['location_updated'] = 1;  */
					
					if (empty($this->request->data['division_id']) && !empty($this->user['User']['division_id'])){
						$this->request->data['division_id'] = $this->user['User']['division_id'];
					}elseif(!empty($this->request->data['region_id'])){
						
						$this->loadModel('DivisionsRegion');
						$division = $this->DivisionsRegion->findByRegionId($this->request->data['region_id']); //pr($division);
						
						$this->request->data['division_id'] = $division['DivisionsRegion']['division_id'];
					}
					
					$customer = $this->Customer->save($this->request->data);
					
					if(empty($customer['Customer']['route_id']) || empty($this->request->data['route_id'])){
						/** Email  **/
						$email = new CakeEmail('smtp');
						$email->from(array('support@drupway.com'=> 'Y3 Support'));
						//$email->to(array('smalution2037@gmail.com','drupwaycrm@gmail.com'));
						$email->to(array('drupwaycrm@gmail.com','smalution2037@gmail.com'));
						$email->emailFormat('html');
						$email->subject("Y3 - Route Null Customer Mobile App");
						$email->viewVars(array('customer' => $customer, 'user_id'=> $this->user['User']['id']));
						$email->template('null_route_customer');
						$email->send('null_route_customer'); 
						/**** ----------------------------------------------------- ****/
					}
					
					if (!empty($this->request->data['id'])){
						$customer_id = $this->request->data['id'];
					}else{
						$customer_id = $customer['Customer']['id'];
					}
					if (!empty( $this->request->data['assignToOption'])){
						$userIds = $this->request->data['assignToOption'];
						$this->loadModel('CustomerAssign');
						$this->CustomerAssign->primaryKey = null;
						$this->CustomerAssign->deleteAll(array('customer_id'=>$customer_id), false);
						$assignData = array();
						foreach($userIds as $uid=>$name){
							$assignData[] = array('CustomerAssign' => array('customer_id'=>$customer_id, 'user_id'=>$uid, 'assign_by'=>$this->user['User']['id']));
						}
						@$this->CustomerAssign->saveAll($assignData);
					}
					$this->response['error'] = 0;
					$this->response['message'] = __('Customer was added sucessfully');
					
				}
			}
		}
		if(!empty($this->request->data['request_id']) && empty($this->request->data['id']) ){
			$customer_id = empty($customer_id)?0:$customer_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $customer_id);
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function getCustomer(){
		$this->loadModel('Customer');
		if(empty($this->request->data['customer_id'])){
			$this->response['message'] = __('Customer id should not be empty');
		}else{
			$id = $this->Customer->id = $this->request->data['customer_id'];
			$this->request->data = $this->Customer->read();
		}
		if (!$this->request->data){
			$this->response['message'] = __('Invalid request');
		}else{
			$this->request->data['Customer']['assigned_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 $key=>$assign){
					$uid = $assign['CustomerAssign']['user_id'];
					$this->request->data['Customer']['assigned_user_ids'][$uid] = $uid;
				}
			}
			if($this->request->data['File']['name']){
				$this->request->data['Customer']['image_path'] = Router::url('/files/photos/small/' . $this->request->data['File']['name'], true);
			}
			
			$this->response['error'] = 0;
			$this->response['data'] = $this->request->data;
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/**
     * deleteCustomer method
     *
     * @param string $id
     * @return void
     */
    public function deleteCustomer() {
		$this->loadModel('Customer');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['customer_id'])){
			$this->response['message'] = __('Customer id should not be empty');
		}else{
			$id = $this->Customer->id = $this->request->data['customer_id'];
			$customer = $this->Customer->read();
		}
       
	   
        if (!$customer) {
             $this->response['message'] =  __('Invalid Customer');
        }
		
        if ($this->Customer->delete()) {
			if ($customer['Customer']['file_id']){
				$this->FileUpload->removeFileId($customer['Customer']['file_id']);
			}
			$this->response['message'] = __('Customer was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('Customer was not deleted');   
		}
		echo json_encode($this->response);
		exit;
    }

	/**
	 *get customer visit
	 *
	*/
	public function getCustomerVisit(){
		$this->loadModel('CustomerVisit');
		$conditions = array();
		$query = $navParams = array();
        $type = $opt = '';
        $user = $this->user;
		
		//$this->CustomerVisit->visibleRoleConditions($conditions, $this->user, $this->paginate);
        
		
		//// To fetch current month data only
		$conditions['CustomerVisit.visiting_date >= '] = date('Y-m-01');
		
		/* $query['from'] = date('Y-m-d', strtotime('-6 month', strtotime(date('Y-m-d'))) );
        $query['to'] = date('Y-m-d'); */
		
		$query['from'] = date('Y-m-01');
        $query['to'] = date('Y-m-d');
		
        if(!empty($query['from']) || !empty($query['to']) ){
            $type="between";
            $cvisityear_tables = customerVisitYearTables(@$query['from'], @$query['to']);
        }else{
            $cvisityear_tables = customerVisitYearTables(@$opt, @$opt);
        }
        
        $params = array_merge($navParams, compact('query', 'type','opt','cvisityear_tables','user'));
        $this->CustomerVisit->customerVisitAdditionalParam($params, $this->paginate, $conditions);
		//$this->CustomerVisit->visibleConditions($conditions, $this->user);
		$this->paginate['order'] = array('CustomerVisit.id' => 'desc');
		$visits = $this->paginate('CustomerVisit', $conditions);
		if($visits){
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['CustomerVisit']['page'] - 1) * $this->params->params['paging']['CustomerVisit']['limit'];
			foreach($visits as $key=>$visit){
				$visits[$key]['sno'] = ++$i;
			}
			$this->response['data'] = $visits;
			$paging = array();
			$paging['page'] = $this->params->params['paging']['CustomerVisit']['page'];
			$paging['current'] = $this->params->params['paging']['CustomerVisit']['current'];
			$paging['count'] = $this->params->params['paging']['CustomerVisit']['count'];
			$paging['pageCount'] = $this->params->params['paging']['CustomerVisit']['pageCount'];
			
			if (!empty($this->params->params['paging']['CustomerVisit']['prevPage'])){
				$paging['prev'] = Router::url(array('controller'=>'services', 'action'=>'getCustomerVisit', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['CustomerVisit']['page'] - 1), 'ext'=>'json'), true);
			}
			if (!empty($this->params->params['paging']['CustomerVisit']['nextPage'])){
				
				$paging['next'] = Router::url(array('controller'=>'services', 'action'=>'getCustomerVisit', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['CustomerVisit']['page'] + 1), 'ext'=>'json'), true);
			}
		
			$this->response['paging'] = $paging;
		}else{
			$this->response['message'] = __('Data not found');
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	//Start Consumer Section
		function getMoreConsumer(){
		//pr($this->request->data);
		$this->loadModel('Consumer');
		$this->response['error'] = 0;
		$data = array();
		$consumer = $this->Consumer->moreConsumerListByRole($this->user, $this->request->data['consumerIds']);
		if ($consumer['consumersList']){
			$data['consumers'] = $consumer['consumersList'];
		}else{
			$this->response['error'] = 2;
			$this->response['message'] = __('No more consumer is there');
		}
		$this->response['data'] = $data; //$this->request->data;
		echo json_encode($this->response);
		exit;
	}
	function consumersList(){
		$this->loadModel('Consumer');
		$consumer = $this->Consumer->consumerListByRole($this->user, true);
		$consumers = $consumer['consumersList'];
		$this->response['error'] = 0;
		if ($consumers){
			$data['consumers'] = $consumers;
		}else{
			$data['consumers'] = null;
		}
		
		$this->response['data'] = $data;
		echo json_encode($this->response);
		exit;		
	}
	public function consumers(){
        
		$this->loadModel('Consumer');
		$this->loadModel('User');
		$conditions = array();
		$this->Consumer->hasMany = array('ConsumerAssign' => array('className' => 'ConsumerAssign', 'foreignKey' => 'consumer_id', 'fields' => array( 'user_id'), 'type'=>'left') );
		
		//$this->Consumer->_userCondition($conditions, $this->user);
		$this->Consumer->_userRoleCondition($conditions, $this->user, $this->paginate);
		
		$this->paginate['order'] = array('Consumer.first_name'=>'asc', 'Consumer.last_name'=>'asc');
		$this->response['error'] = 0;
		$consumers = $this->paginate('Consumer', $conditions);
        
		$i = ($this->params->params['paging']['Consumer']['page'] - 1) * $this->params->params['paging']['Consumer']['limit'];
		if ($consumers){
			$users = $this->User->usersList();
			foreach($consumers as $key => $consumer){
				if($consumer['File']['name']){
					$path = Router::url('/files/photos/small/' . $consumer['File']['name'], true);
				}else{
					$path = Router::url('/files/photos/small/default_small.jpg', true);
				}
				$consumers[$key]['Consumer']['image_path'] = $path;
				
				$consumers[$key]['sno'] = ++$i;
				
				if (!empty($consumer['ConsumerAssign'])){
					foreach($consumer['ConsumerAssign'] as $assignTo){
						$uid = @$assignTo['user_id'];
						if (!empty($users[$uid])){
							$consumers[$key]['assignTo'][$uid] = $users[$uid];
						}
					}
					
				}else{
					$consumers[$key]['assignTo'] = null;
				}
				unset($consumers[$key]['ConsumerAssign']);
			}
		}
        
		$this->response['data'] = $consumers;
		$paging = array();
		$paging['page'] = $this->params->params['paging']['Consumer']['page'];
		$paging['current'] = $this->params->params['paging']['Consumer']['current'];
		$paging['count'] = $this->params->params['paging']['Consumer']['count'];
		$paging['pageCount'] = $this->params->params['paging']['Consumer']['pageCount'];
		
		if (!empty($this->params->params['paging']['Consumer']['prevPage'])){
			$paging['prev'] = Router::url(array('controller'=>'services', 'action'=>'consumers', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Consumer']['page'] - 1), 'ext'=>'json'), true);
		}
		if (!empty($this->params->params['paging']['Consumer']['nextPage'])){
			
			$paging['next'] = Router::url(array('controller'=>'services', 'action'=>'consumers', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Consumer']['page'] + 1), 'ext'=>'json'), true);
		}
	
		$this->response['paging'] = $paging;
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function updateconsumer(){
		$this->loadModel('Consumer');
		//pr($this->data);
		
		if ($this->request->data){
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			$is_exists = 0;
			if (!empty($this->request->data['phone']) ){
				$this->request->data['phone'] = trim($this->request->data['phone']);
				$conditions = array('Consumer.phone'=>$this->request->data['phone']);
				if(!empty($this->request->data['id'])){
					$conditions['Consumer.id != '] = $this->request->data['id'];
					
				}
				$is_exists = $this->Consumer->find('count', array('conditions'=>$conditions));
			}
			
			if ($is_exists > 0){
				$this->response['message'] = __('This consumer already exists');
			}else{
				$image_ok = true;
				//$this->response['files'] = $_FILES;
				if($_FILES){
					$this->request->data['image'] = $_FILES['image'];
				}
				if (!empty($this->request->data['image']['name'])){
					if ($this->FileUpload->upload($this->request->data,'image')) {
						$this->request->data['file_id'] = $this->FileUpload->fileId;
						if (!empty($this->request->data['oldFile_id'])){
							$this->FileUpload->removeFileId($this->request->data['oldFile_id']);
						}
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					if (empty($this->request->data['id'])){
						$this->request->data['user_id'] = $this->user['User']['id'];
					}elseif(!empty($this->request->data['id'])){
						//unset($this->request->data['user_id']);
					}
					//$this->response['data'] = $consumer = $this->Consumer->save($this->request->data);
					if(isset($this->request->data['view_details']) && $this->request->data['view_details'] == true){
						$this->request->data['view_details'] = 1;
					}
					
					
					if (empty($this->request->data['division_id']) && !empty($this->user['User']['division_id'])){
						$this->request->data['division_id'] = $this->user['User']['division_id'];
					}
					
					
					$consumer = $this->Consumer->save($this->request->data);
					
					if (!empty($this->request->data['id'])){
						$consumer_id = $this->request->data['id'];
					}else{
						$consumer_id = $consumer['Consumer']['id'];
					}
					if (!empty( $this->request->data['assignToOption'])){
						$userIds = $this->request->data['assignToOption'];
						$this->loadModel('ConsumerAssign');
						$this->ConsumerAssign->primaryKey = null;
						$this->ConsumerAssign->deleteAll(array('consumer_id'=>$consumer_id), false);
						$assignData = array();
						foreach($userIds as $uid=>$name){
							$assignData[] = array('ConsumerAssign' => array('consumer_id'=>$consumer_id, 'user_id'=>$uid, 'assign_by'=>$this->user['User']['id']));
						}
						@$this->ConsumerAssign->saveAll($assignData);
					}
					$this->response['error'] = 0;
					$this->response['message'] = __('Consumer was added sucessfully');
					
				}
			}
		}
		if(!empty($this->request->data['request_id']) && empty($this->request->data['id']) ){
			$consumer_id = empty($consumer_id)?0:$consumer_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $consumer_id);
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function getConsumer(){
		$this->loadModel('Consumer');
		if(empty($this->request->data['consumer_id'])){
			$this->response['message'] = __('Consumer id should not be empty');
		}else{
			$id = $this->Consumer->id = $this->request->data['consumer_id'];
			$this->request->data = $this->Consumer->read();
		}
		if (!$this->request->data){
			$this->response['message'] = __('Invalid request');
		}else{
			$this->request->data['Consumer']['assigned_user_ids'] = array();
			$this->loadModel('ConsumerAssign');
			$this->ConsumerAssign->primaryKey = null;
			$assigned = $this->ConsumerAssign->find('all', array('conditions'=>array('consumer_id'=>$id)));
			if ($assigned){
			
				foreach($assigned as $key=>$assign){
					$uid = $assign['ConsumerAssign']['user_id'];
					$this->request->data['Consumer']['assigned_user_ids'][$uid] = $uid;
				}
			}
			if($this->request->data['File']['name']){
				$this->request->data['Consumer']['image_path'] = Router::url('/files/photos/small/' . $this->request->data['File']['name'], true);
			}
			
			$this->response['error'] = 0;
			$this->response['data'] = $this->request->data;
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/**
     * deleteCustomer method
     *
     * @param string $id
     * @return void
     */
    public function deleteConsumer() {
		$this->loadModel('Consumer');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$consumer = array();
		if(empty($this->request->data['consumer_id'])){
			$this->response['message'] = __('Consumer id should not be empty');
		}else{
			$id = $this->Consumer->id = $this->request->data['consumer_id'];
			$consumer = $this->Consumer->read();
		}
       
	   
        if (!$consumer) {
             $this->response['message'] =  __('Invalid Consumer');
        }
		
        if ($this->Consumer->delete()) {
			if ($consumer['Consumer']['file_id']){
				$this->FileUpload->removeFileId($consumer['Consumer']['file_id']);
			}
			$this->response['message'] = __('Consumer was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('Consumer was not deleted');   
		}
		echo json_encode($this->response);
		exit;
    }

	/**
     * deleteCustomerVisit method
     *
     * @param string $id
     * @return void
     */
    public function deleteCustomerVisit() {
		$this->loadModel('CustomerVisit');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['visit_id'])){
			$this->response['message'] = __('CustomerVisit id should not be empty');
		}else{
			$id = $this->CustomerVisit->id = $this->request->data['visit_id'];
			$customerVisit = $this->CustomerVisit->read();
		}
       if (!$customerVisit) {
             $this->response['message'] =  __('Invalid CustomerVisit');
        }
		
        if ($this->CustomerVisit->delete()) {
			$this->response['message'] = __('CustomerVisit was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('CustomerVisit was not deleted');   
		}
		echo json_encode($this->response);
		exit;
    }
	/**
     * updatevisit method
     *
     * @param string $id
     * @return void
     */
	function updatevisit(){
		if ($this->request->data){
			$this->loadModel('CustomerVisit');
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			
			
			/* if($this->request->data['customer_id'] == 291634){
				$this->request->data['jsonString'] = '{"token":"2144787865cf4f5c96b381.26374075","request_id":"null::20190926103319","created":"2019-09-26 10:33:19","customer_id":"291634","lg_area_id":"null","depot_id":"null","visiting_date":"2024-2-12 10:33:19","latitude":"19.1233087","longitude":"72.8620992","comment":"offline"}';
			
			$this->request->data = json_decode($this->request->data['jsonString'], true );  
			}  */
			
			if (!empty($this->request->data['newCustomer'])){
				$customerId = $this->_addCustomer($this->request->data['newCustomer']);
				$this->request->data['customer_id'] = $customerId;
			}
			
			if (!empty($this->request->data['customer_id'])){
				if(!empty($this->request->data['visit_id'])){
					$this->request->data['id'] = $this->request->data['visit_id'];
					//unset($this->request->data['user_id']);
					$this->request->data['app_modified'] = 1;
					
					$this->CustomerVisit->id = $this->request->data['id'];
					$AuditData = $this->CustomerVisit->read();
				}else{
					$this->request->data['user_id'] = $this->user['id'];
					$this->request->data['via_app'] = 1;
				}
				if (empty($this->request->data['visiting_date'])){
					$this->request->data['visiting_date'] = date('Y-m-d H:i:s');
				}
				
				$is_added = 0;
				if(empty($this->request->data['id'])){
					$conditions = array('CustomerVisit.customer_id' => $this->request->data['customer_id'], 'CustomerVisit.user_id'=>$this->user['id'], 'CustomerVisit.visiting_date' => $this->request->data['visiting_date'], 'CustomerVisit.created'=>$this->request->data['created'] );			
					//Check already added			
					$is_added = $this->CustomerVisit->find('count', array('conditions'=>$conditions));
				}
				if ($is_added > 0 && empty($this->request->data['id'])){	
					$this->response['message'] = __('This visit entry already added');
					$this->response['error'] = SYNC_NOT_REQUIRED;
				}else{
				
					$this->loadModel('Customer');
				
				
				
				//Get customer
				
				//$this->Customer->id = $this->request->data['customer_id'];
				$customer = $this->Customer->findById($this->request->data['customer_id']); 
				
				if(!empty($customer)){
					//ONLY FOR ADD		 
						if(empty($this->request->data['visit_id'])){
							
							$this->response['verifiedCode'] = 0;
							
							$isUnVerifiedCustomer = (empty($customer['Customer']['verified_latitude']) && empty($customer['Customer']['verified_longitude']) && empty($customer['Customer']['verified_by']) && empty($customer['Customer']['verified_date']));
							
							//verify customer by RM & marketing manager & Division Manager
							if($isUnVerifiedCustomer && ($this->user['role_id'] == 3 || $this->user['role_id'] == 2 || $this->user['role_id'] == 13)){ 
								if (!empty($this->request->data['latitude'])){ 
									if($this->request->data['latitude'] != 0 ){ 
										$verifiedData['Customer']['verified_latitude'] = $this->request->data['latitude'];
									}					
								}
								
								if (!empty($this->request->data['longitude'])){
									if($this->request->data['longitude'] != 0 ){
										$verifiedData['Customer']['verified_longitude'] = $this->request->data['longitude'];
									}
								}
								//pr($verifiedData);
								if(!empty($verifiedData) && !empty($this->request->data['customer_id'])){
									$verifiedData['Customer']['id'] = $this->request->data['customer_id'];
									
									$verifiedData['Customer']['location_updated'] = 1;
									
									$verifiedData['Customer']['verified_by'] = $this->user['id'];

									$verifiedData['Customer']['verified_date'] = date("Y-m-d", strtotime($this->request->data['visiting_date']));
									
									$vc = $this->Customer->save($verifiedData);
									$this->response['verifiedCode'] = 1;
								}
							}
							
							
							$this->response['updateCode'] = 0;
							//if($customer['Customer']['id'] == 272113){
							if($this->user['role_id'] > 3 && $customer['Customer']['location_updated'] == 0){
								
								if (!empty($this->request->data['latitude'])){
									if($this->request->data['latitude'] != 0 ){
										$updateCust['Customer']['latitude'] = $this->request->data['latitude'];
									}
								}
								
								if (!empty($this->request->data['longitude'])){
									if($this->request->data['longitude'] != 0 ){
										$updateCust['Customer']['longitude'] = $this->request->data['longitude'];
									}
								}

								if(!empty($updateCust) && !empty($this->request->data['customer_id'])){
									$updateCust['Customer']['location_updated'] = 1;
									$updateCust['Customer']['id'] = $this->request->data['customer_id'];
									$this->Customer->save($updateCust);
									$this->response['updateCode'] = 1;
								}
							}
							//}
						}else{
								//Edit entry
								
								/**** Audit START ****/
									if(!empty($AuditData)){
										$this->loadModel('Audit');
										$this->Audit->saveDeletedData($AuditData['CustomerVisit']['id'], 'CustomerVisit', $this->user['id'] , serialize($AuditData),'CustomerVisit Has been updated',STATUS_EDIT);
									}
								/**** Audit END ****/
							}	
				
					$this->request->data['depot_id'] = $customer['Customer']['depot_id'];
					$this->request->data['lg_area_id'] = $customer['Customer']['lg_area_id'];
					
					$this->request->data['state_id'] = $customer['Customer']['state_id'];
				
					$cvisit = $this->CustomerVisit->save($this->request->data);
					
					//ONLY FOR ADD		 
					if(empty($this->request->data['visit_id'])){
						/*****----- Check if entry is on correct route -----*****/
						$uid = $cvisit['CustomerVisit']['user_id']; 
						$date = date('Y-m-d', strtotime($cvisit['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 = $cvisit['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' => $cvisit, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
									$email->template('entry_on_different_route');
									$email->send('entry_on_different_route'); 
								/**** ----------------------------------------------------- ****/
								
								## Debug email - can be removed once issue has been fixed
									$email = new CakeEmail('smtp');
									$email->from(array('support@drupway.com'=> 'Y3 Support'));
									$email->to(array('drupwaycrm@gmail.com')); // y3hqfin@fastmail.fm = Anya
									$email->emailFormat('html');
									$email->subject("Y3 CRM ALERT - Not on route Visit : ".$cvisit['CustomerVisit']['id']);
									$body = json_encode($this->request->data['jsonString'], JSON_PRETTY_PRINT);
									$email->send($body);
								
								}
							}
							/*****------------------------------------*****/
						}
						
						$this->Customer->verify_status($this->request->data['customer_id']);
						$visit_id = $cvisit['CustomerVisit']['id'];
						$this->response['message'] = __('Last Record was save successfully');
						
						//UPDATE Attendance for add entry
						if(empty($this->request->data['id'])){
							$call['user_id'] = $this->user['id'];
							$call['emp_id'] = $this->user['employee_id'];
							$call['date'] = $this->request->data['created'];
							$FunctionsController = new FunctionsController;
							$FunctionsController->_updateAttendance($call);
						}
						
						$this->response['error'] = 0;
					}else{
						$this->response['message'] = __('Unable to save. Customer no longer exists in the system.');
						$this->response['error'] = SYNC_NOT_REQUIRED;
					}	
				}
				 
				
				
				//get user_id  for hrms integration.
				/* $this->loadModel('User');
				$uid1 = $this->request->data['user_id'];
				$created_date = $this->request->data['created'];
				$this->_updateAttendance_visitentry($uid1, $created_date); */
			
			}else{
				$this->response['message'] = __('Unable to save. Customer is missing.');
				$this->response['error'] = SYNC_NOT_REQUIRED;
			}
		}
		if(!empty($this->request->data['request_id']) && empty($this->request->data['id']) ){
			$visit_id = empty($visit_id)?0:$visit_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $visit_id);
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/*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);
			}
	} */
	
	
	/**
     * getVisit method
     *
     * @param: post params
     * @return void
     */
	function getVisit(){
		if(empty($this->request->data['visit_id'])){
			$this->response['message'] = __('visit id should not be empty');
		}else{
		
			$this->loadModel('CustomerVisit');
			$this->CustomerVisit->id = $this->request->data['visit_id'];
			$visit = $this->CustomerVisit->read();
			
			if ($visit){
				$this->response['data'] = $visit;
				$this->response['error'] = 0;
			}else{
				$this->response['message'] = __('Invalid Customer Visit');
			}
		}
		echo json_encode($this->response);
		exit;
	}
	
		
	public function getPaymentList()
	{
		$this->loadModel('Payment');
		$this->paginate['order'] = array('Payment.created'=>'desc','Payment.payment_date'=>'desc');
		
		$conditions = array();
		
		// To fetch current month data only
		$conditions['Payment.payment_date >= '] = date('Y-m-01');
		
		$this->Payment->_userCondition($conditions, $this->user);
		$payments = $this->paginate('Payment', $conditions);
		/*if (!$payments){
			$this->response['error'] = 2;
			$this->response['message'] = __('Data not found');
		}else{
		*/
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['Payment']['page'] - 1) * $this->params->params['paging']['Payment']['limit'];
			
			if ($payments){
				foreach ($payments as $key => $payment){
					$payments[$key]['sno'] = ++$i;
				}
			}
			
			$this->response['data'] = $payments;
			$paging = array();
			$paging['page'] = $this->params->params['paging']['Payment']['page'];
			$paging['current'] = $this->params->params['paging']['Payment']['current'];
			$paging['count'] = $this->params->params['paging']['Payment']['count'];
			$paging['pageCount'] = $this->params->params['paging']['Payment']['pageCount'];

			if (!empty($this->params->params['paging']['Payment']['prevPage'])){
				$paging['prev'] = Router::url(array('controller'=>'services', 'action'=>'getPaymentList', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Payment']['page'] - 1), 'ext'=>'json'), true);
			}
			if (!empty($this->params->params['paging']['Payment']['nextPage'])){
				
				$paging['next'] = Router::url(array('controller'=>'services', 'action'=>'getPaymentList', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Payment']['page'] + 1), 'ext'=>'json'), true);
			}
			$this->response['paging'] = $paging;
		//}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}		
	
	public function updatePayment(){
		
	    if ($this->request->data){
		    $this->loadModel('Payment');
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			
			$is_added =0;
			
			if (empty($this->request->data['region_id'])){
				$this->request->data['region_id'] = $this->user['region_id'];
			}
			if (empty($this->request->data['depot_id'])){
				$this->request->data['depot_id'] = $this->user['depot_id'];
			}
			
			/*if (!empty($this->request->data['id'])){
				unset($this->request->data['user_id']);
			}else{
				$this->request->data['user_id'] = $this->user['id'];
				if (empty($this->request->data['depot_id']) && !empty($this->user['depot_id'])){
					$this->request->data['depot_id'] = $this->user['depot_id'];
				}				
			}*/
			
			if (!empty($this->request->data['brand_id'])){ 
				$this->loadModel('Brand');
				$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$this->request->data['brand_id']))); 
				$this->request->data['brand_group_id'] = $group_id[$this->request->data['brand_id']]; 
			}
			
			
			if ( !empty($this->request->data['id'])){
				$this->request->data['id'] = $this->request->data['id'];
				//unset($this->request->data['user_id']);
				$this->request->data['app_modified'] = 1;
				
				$this->Payment->id = $this->request->data['id'];
				$AuditData = $this->Payment->read();
				
			}else{
				$this->request->data['user_id'] = $this->user['id'];
				
				$this->request->data['via_app'] = 1;
				
				$conditions = array('Payment.user_id'=>$this->user['id'], 'Payment.payment_date' => $this->request->data['payment_date'], 'Payment.distributor_id' => $this->request->data['distributor_id'], 'Payment.bank_id' => $this->request->data['bank_id'], 'Payment.brand_id' => $this->request->data['brand_id'], 'Payment.amount' => $this->request->data['amount'], 'Payment.created' =>$this->request->data['created'] );
				
				//Check already added			
				$is_added = $this->Payment->find('count', array('conditions'=>$conditions));
			}
			
			
			
			if ($is_added > 0 && empty($this->request->data['id'])){
				$this->response['message'] = __('This payment entry already added');
				$this->response['error'] = SYNC_NOT_REQUIRED;
			}else{
				
				$payment = $this->Payment->save($this->request->data);
				$this->response['date'] = $payment;
				$payment_id = $payment['Payment']['id'];
				if (!empty($this->request->data['id'] )){
	
					/**** Audit START ****/
						if(!empty($AuditData)){
							$this->loadModel('Audit');
							$this->Audit->saveDeletedData($AuditData['Payment']['id'], 'Payment', $this->user['id'] , serialize($AuditData),'Payment Has been updated',STATUS_EDIT);
						}
					/**** Audit END ****/
					
					$this->response['message'] = __('Payment was updated successfully');
				}else{
					$this->response['message'] = __('Payment was added successfully');
				}
				
				$this->response['error'] = 0;
			}
			
		}
		if(!empty($this->request->data['request_id']) && empty($this->request->data['id']) ){
			$payment_id = empty($payment_id)?0:$payment_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $payment_id);
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function deletePayment(){
		$this->loadModel('Payment');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['payment_id'])){
			$this->response['message'] = __('payment_id should not be empty');
		}else{
			$id = $this->Payment->id = $this->request->data['payment_id'];
			$payment = $this->Payment->read();
		}
		
		if (!$payment) {
			 $this->response['message'] =  __('Invalid payment');
		}
		
        if ($this->Payment->delete()) {
			
			/**** Audit START ****/
				$this->loadModel('Audit');
				$this->Audit->saveDeletedData($payment['Payment']['id'], 'Payment', $this->user['id'] , serialize($payment),'Payment Has been Deleted',STATUS_DELETE);
			/**** Audit END ****/
			
			$this->response['message'] = __('Payment was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('Payment was not deleted');   
		}
		echo json_encode($this->response);
		exit;
	}
	
	public function getPayment(){
		$this->loadModel('Payment');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['payment_id'])){
			$this->response['message'] = __('payment_id should not be empty');
		}else{
			$id = $this->Payment->id = $this->request->data['payment_id'];
			$payment = $this->Payment->read();
		}
		
		if (!$payment) {
			 $this->response['message'] =  __('Invalid payment');
		}else{
			$this->response['data'] = $payment;
			$this->response['error'] = 0;
		}
		
       
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function getExpenseList()
	{
		$this->loadModel('Expense');
		$this->paginate['order'] = array('Expense.created'=>'desc', 'Expense.exp_date'=>'desc');
		$conditions = array();
		
		// To fetch current month data only
		$conditions['Expense.exp_date >= '] = date('Y-m-01');
		
		//$this->Expense->_userCondition($conditions, $this->user);
		
		$this->Expense->_userRoleCondition($conditions, $this->user, $this->paginate);
		
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();
		$limit = $this->paginate['limit'] = PAGE_LIMIT;
		$this->Expense->bindModel(
					array(
					'belongsTo'=>array(
						'Asset' =>array(
						
							'className' => 'Asset',
							'foreignKey'=> 'asset_id',
							'fields' => array('id', 'number', 'type')
							)
						)
					)
		);
		
		$expenses = $this->paginate('Expense', $conditions);  //pr( $this->params->params['paging']);
		if (!$expenses){
			$this->response['message'] = __('Invalid request');
		}else{
		
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['Expense']['page'] - 1) * $this->params->params['paging']['Expense']['limit'];
			
			if ($expenses){
				foreach ($expenses as $key => $expense){
					$expenses[$key]['sno'] = ++$i;
				}
			}
			$this->response['data'] = $expenses;
			$paging = array();
			$paging['page'] = $this->params->params['paging']['Expense']['page'];
			$paging['current'] = $this->params->params['paging']['Expense']['current'];
			$paging['count'] = $this->params->params['paging']['Expense']['count'];
			$paging['pageCount'] = $this->params->params['paging']['Expense']['pageCount'];

			if (!empty($this->params->params['paging']['Expense']['prevPage'])){
				$paging['prev'] = Router::url(array('controller'=>'services', 'action'=>'getExpenseList', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Expense']['page'] - 1), 'ext'=>'json'), true);
			}
			if (!empty($this->params->params['paging']['Expense']['nextPage'])){
				
				$paging['next'] = Router::url(array('controller'=>'services', 'action'=>'getExpenseList', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Expense']['page'] + 1), 'ext'=>'json'), true);
			}
			$this->response['paging'] = $paging;
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function updateExpense()
	{
	   //pr($this->request->data);
		if ($this->request->data)
		{
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			$is_added = 0;
			$this->loadModel('Expense');
			
			if(empty($this->request->data['division_id']) && ($this->user['Role']['id'] == DIVISIONMANAGER || $this->user['Role']['grade'] >= RM)){
				$this->request->data['division_id'] = $this->user['division_id'];
			}			
			if (empty($this->request->data['region_id']) && $this->user['Role']['grade'] >= RM){
				$this->request->data['region_id'] = $this->user['region_id'];
			}
			if (empty($this->request->data['depot_id']) && $this->user['Role']['grade'] >= DH){
				$this->request->data['depot_id'] = $this->user['depot_id'];
			}
			
			if ($this->request->data['region_id'] === 0) {
				$this->request->data['region_id'] = null;
			}
			if ($this->request->data['depot_id'] === 0) {
				$this->request->data['depot_id'] = null;
			}
			
			
			/*** default all expenses posted by users from these two depots (Sokoto 2- Dosso and Kano 2- Maradi) only to report on one Brand “AllStars Niger Retail” - $brand_id = 14. And For Other depots “Yes Consumer” - $brand_id = 1 ***/
			
			if(!empty($this->request->data['depot_id'])){
				$this->request->data['brand_id'] = get_expense_brand_id($this->request->data['depot_id']);
			}
			
			if (!empty($this->request->data['brand_id'])){ 
				$this->loadModel('Brand');
				$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$this->request->data['brand_id']))); 
				$this->request->data['brand_group_id'] = $group_id[$this->request->data['brand_id']]; 
			}
			
			if ( !empty($this->request->data['id'])){
				//$this->request->data['id'] = $this->request->data['id'];
				//unset($this->request->data['user_id']);
				$this->request->data['app_modified'] = 1;
				
				if (empty($this->request->data['division_id']) && ($this->user['Role']['id'] == DIVISIONMANAGER || $this->user['Role']['grade'] >= RM)){
					$this->request->data['division_id'] = $this->user['division_id'];
				}
				
				$this->Expense->id = $this->request->data['id'];
				$AuditData = $this->Expense->read();
			}else{
				$this->request->data['user_id'] = $this->user['id'];
				//$this->request->data['asset_id'] = $this->user['Asset']['id'];
				$this->request->data['via_app'] = 1;
				
				
				$conditions = array('Expense.user_id'=>$this->user['id'], 'Expense.exp_date' => $this->request->data['exp_date'], 'Expense.exp_type_id' => $this->request->data['exp_type_id'], 'Expense.exp_amount' => $this->request->data['exp_amount'], 'Expense.created' =>$this->request->data['created'] );
			
				//Check already added			
				$is_added = $this->Expense->find('count', array('conditions'=>$conditions)); 
			}
			
			
			if ($is_added > 0 && empty($this->request->data['id'])){
				$this->response['message'] = __('This expense entry already added');
				$this->response['error'] = SYNC_NOT_REQUIRED;
			}else{
				
				if(empty($this->request->data['id'])){
					if (!empty($this->request->data['exp_type_id']) && empty($this->request->data['asset_id'])){ 
						$this->loadModel('ExpType');
						$assetExpTypes = $this->ExpType->find('list', array('fields' => array('id' ), 'conditions' => array('ExpType.category_id IN' => [EXP_CAT_MO_BIKE, EXP_CAT_MO_VEHICLE])));
						
						if (in_array($this->request->data['exp_type_id'], $assetExpTypes)){
							if (empty($this->request->data['asset_id'])){
								$this->loadModel('AssetUser');
								$userassets = $this->AssetUser->find('all', array('fields'=>array('AssetUser.id', 'AssetUser.asset_id'), 'conditions' => array('AssetUser.user_id' => $this->user['id'])));
								if(count($userassets) == 1){
									$this->request->data['asset_id'] = $userassets[0]['AssetUser']['asset_id'];
								}
								
							}
							
						}
					}
				}
				
				
				
				$expence = $this->Expense->save($this->request->data);
				$this->response['data'] = $expence;
				$expence_id = $expence['Expense']['id'];
				
				/** Email  **/
				if(isset($expence['Expense']['user_id']) && ($expence['Expense']['user_id'] == 0)){
					
					$email = new CakeEmail('smtp');
					$email->from(array('support@drupway.com'=> 'Y3 Support'));
					$email->to(array('drupwaycrm@gmail.com', 'samikshad@drupway.com')); 
					$email->emailFormat('html');
					$email->subject("Y3 CRM ALERT - Expense without a user is saved - " . $expence['Expense']['id']);
					
					$emailBody .= "<p><strong>Date:</strong> " . date('Y-m-d H:i:s') . "</p>";
					
					if ( !empty($this->request->data['id'])){
						$emailBody .= "<p><strong>Modified By:</strong> " . $this->user['id'] . "</p>";
					}else{
						$emailBody .= "<p><strong>Added By:</strong> " . $this->user['id'] . "</p>";
					}
					
					$emailBody .= "<h4>Request Data (JSON)</h4>";
					$emailBody .= "<pre>" . h(json_encode($this->request->data, JSON_PRETTY_PRINT)) . "</pre>";
					
					$email->send($emailBody);					
				}
				/**** ----------------------------------------------------- ****/
				
				
				if (!empty($this->request->data['id'] ) || !empty($this->request->data['expense_id']) ){
					
					/**** Audit START ****/
						if(!empty($AuditData)){
							$this->loadModel('Audit');
							$this->Audit->saveDeletedData($AuditData['Expense']['id'], 'Expense', $this->user['id'] , serialize($AuditData),'Expense Has been updated',STATUS_EDIT);
						}
					/**** Audit END ****/
					
					$this->response['message'] = __('Expense was updated successfully');
				}else{
					$this->response['message'] = __('Expense was added successfully');
				}
				
				$this->response['error'] = 0;
			}
			
			
			if(!empty($this->request->data['request_id']) && empty($this->request->data['id']) ){
				$expence_id = empty($expence_id)?0:$expence_id;
				$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $expence_id);
			}
			echo json_encode($this->response);
			exit;
		
		}else{
			$this->response['message'] = __('Invalid request');
		}
	}
	
	
	public function deleteExpense(){
		$this->loadModel('Expense');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['expense_id'])){
			$this->response['message'] = __('expense_id should not be empty');
		}else{
			$id = $this->Expense->id = $this->request->data['expense_id'];
			$expense = $this->Expense->read();
		}
		
		if (!$expense) {
			 $this->response['message'] =  __('Invalid expense');
		}
		
        if ($this->Expense->delete()) {
			
			/**** Audit START ****/
				$this->loadModel('Audit');
				$this->Audit->saveDeletedData($expense['Expense']['id'], 'Expense', $this->user['id'] , serialize($expense),'Expense Has been Deleted',STATUS_DELETE);
			/**** Audit END ****/
			
			$this->response['message'] = __('Expense was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('Expense was not deleted');   
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	public function getExpense(){
		$this->loadModel('Expense');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['expense_id'])){
			$this->response['message'] = __('expense_id should not be empty');
		}else{
			$id = $this->Expense->id = $this->request->data['expense_id'];
			
			$this->Expense->bindModel(
					array(
					'belongsTo'=>array(
						'Asset' =>array(
						
							'className' => 'Asset',
							'foreignKey'=> 'asset_id',
							'fields' => array('id', 'number', 'type')
							)
						)
					)
		);
			$expense = $this->Expense->read();
		}
		
		if (!$expense) {
			 $this->response['message'] =  __('Invalid expense');
		}else{
			$this->response['data'] = $expense;
			$this->response['error'] = 0;
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	function _addCustomer($data){
		$this->loadModel('Customer');
		//pr($this->data);		
		if ($data){			
			$is_exists = 0;			
			if (!empty($data['phone']) ){
				$data['phone'] = trim($data['phone']);
				$conditions = array('Customer.phone'=>$data['phone']);		
				
				// if (!empty($data['email'])){
					// $conditions['LOWER(Customer.email)'] = strtolower($data['email']);
				// }
				// $conditions['Customer.status'] = ACTIVE;
				$customer = $this->Customer->find('first', array('conditions'=>$conditions));
			}
			
			if (!empty($customer)){
				$customer_id = $customer['Customer']['id'];
			}else{
				$image_ok = true;
				//$this->response['files'] = $_FILES;
				if($_FILES){
					$data['image'] = $_FILES['image'];
				}
				if (!empty($data['image']['name'])){
					if ($this->FileUpload->upload($data,'image')) {
						$data['file_id'] = $this->FileUpload->fileId;
						if (!empty($data['oldFile_id'])){
							$this->FileUpload->removeFileId($data['oldFile_id']);
						}
					} 
				}
				
				$data['user_id'] = $this->user['User']['id'];
				$customer = $this->Customer->save($data);
				
				if (!empty($data['id'])){
					$customer_id = $data['id'];
				}else{
					$customer_id = $customer['Customer']['id'];
				}
				if (!empty( $data['assignToOption'])){
					$userIds = $data['assignToOption'];
					$this->loadModel('CustomerAssign');
					$this->CustomerAssign->primaryKey = null;
					$this->CustomerAssign->deleteAll(array('customer_id'=>$customer_id), false);
					$assignData = array();
					foreach($userIds as $uid=>$name){
						$assignData[] = array('CustomerAssign' => array('customer_id'=>$customer_id, 'user_id'=>$uid, 'assign_by'=>$data['user_id']));
					}
					@$this->CustomerAssign->saveAll($assignData);
				}
				$customer_id = $customer['Customer']['id'];	
			}
			return $customer_id;
		}
	}
	
	
	/**
     * updatevisit method
     *
     * @param string $id
     * @return void
     */
	function updatechecklist(){ 
	
	
	
	
		if ($this->request->data){ 
			$this->loadModel('BikesupervisorChecklist');
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			
			/* if (!empty($this->request->data['newCustomer'])){
				$customerId = $this->_addCustomer($this->request->data['newCustomer']);
				$this->request->data['customer_id'] = $customerId;
			} */
			if(!empty($this->request->data['checklist_id'])){
				$this->request->data['id'] = $this->request->data['checklist_id'];
				//unset($this->request->data['user_id']);
				$this->request->data['app_modified'] = 1;
			}else{
				$this->request->data['user_id'] = $this->user['id'];
				$this->request->data['via_app'] = 1;
			}
			if (empty($this->request->data['visiting_date'])){
				$this->request->data['check_date'] = date('Y-m-d H:i:s');
			}else{
				$this->request->data['check_date'] = $this->request->data['visiting_date'];
			}
			
			/*//Get customer
			$this->loadModel('Customer');
			//$this->Customer->id = $this->request->data['customer_id'];
			$customer = $this->Customer->findById($this->request->data['customer_id']);
			$this->request->data['depot_id'] = $customer['Customer']['depot_id'];
			$this->request->data['lg_area_id'] = $customer['Customer']['lg_area_id'];
			$this->request->data['state_id'] = $customer['Customer']['state_id'];
			*/
			$is_added = 0;
			
			
			if(empty($this->request->data['id'])){
				$conditions = array('BikesupervisorChecklist.customer_id' => $this->request->data['customer_id'], 'BikesupervisorChecklist.user_id'=>$this->user['id'], 'BikesupervisorChecklist.check_date' => $this->request->data['check_date'], 'BikesupervisorChecklist.created'=>$this->request->data['created'] );			
				//Check already added			 
				
				$is_added = $this->BikesupervisorChecklist->find('count', array('conditions'=>$conditions));   
			}
			if ($is_added > 0 && empty($this->request->data['id'])){	
				$this->response['message'] = __('This entry already added');
				$this->response['error'] = SYNC_NOT_REQUIRED;
			}else{ 
			
					//Get customer
					$this->loadModel('Customer');
					//$this->Customer->id = $this->request->data['customer_id'];
					$customer = $this->Customer->findById($this->request->data['customer_id']); 
			
			
				//ONLY FOR ADD		
				if(empty($this->request->data['checklist_id'])){		
					$this->response['verifiedCode'] = 0;
					
					//verify customer by RM & marketing manager & Division Manager
					if((empty($customer['Customer']['verified_latitude']) && empty($customer['Customer']['verified_longitude'])) && ($this->user['role_id'] == 3 || $this->user['role_id'] == 2 || $this->user['role_id'] == 13)){ 
						if (!empty($this->request->data['latitude'])){
							if($this->request->data['latitude'] != 0 ){
								$verifiedData['Customer']['verified_latitude'] = $this->request->data['latitude'];
							}					
						}
						
						if (!empty($this->request->data['longitude'])){
							if($this->request->data['longitude'] != 0 ){
								$verifiedData['Customer']['verified_longitude'] = $this->request->data['longitude'];
							}
						}
						
						if(!empty($verifiedData) && !empty($this->request->data['customer_id'])){
							$verifiedData['Customer']['id'] = $this->request->data['customer_id'];
							
							$verifiedData['Customer']['location_updated'] = 1;
							
							$verifiedData['Customer']['verified_by'] = $this->user['id'];
							
							$verifiedData['Customer']['verified_date'] = date("Y-m-d", strtotime($this->request->data['check_date']));
							
							$vc = $this->Customer->save($verifiedData);
							$this->response['verifiedCode'] = 1;
						}
					}
					
					
					$this->response['updateCode'] = 0;
					//if($customer['Customer']['id'] == 272113){
					if($this->user['role_id'] > 3 && $customer['Customer']['location_updated'] == 0){
						
						if (!empty($this->request->data['latitude'])){
							if($this->request->data['latitude'] != 0 ){
								$updateCust['Customer']['latitude'] = $this->request->data['latitude'];
							}
						}
						
						if (!empty($this->request->data['longitude'])){
							if($this->request->data['longitude'] != 0 ){
								$updateCust['Customer']['longitude'] = $this->request->data['longitude'];
							}
						}

						if(!empty($updateCust) && !empty($this->request->data['customer_id'])){
							$updateCust['Customer']['location_updated'] = 1;
							$updateCust['Customer']['id'] = $this->request->data['customer_id'];
							$this->Customer->save($updateCust);
							$this->response['updateCode'] = 1;
						}
					}
					//}
					
				}	
			

			/* $this->request->data['region_id'] = $this->user['region_id'];
			$this->request->data['depot_id'] = $this->user['depot_id']; */
			
				$this->request->data['division_id'] = $customer['Customer']['division_id'];
				$this->request->data['region_id'] = $customer['Customer']['region_id'];
				$this->request->data['depot_id'] = $customer['Customer']['depot_id'];
			
			
				$bchecklist = $this->BikesupervisorChecklist->save($this->request->data); 
				//$this->Customer->verify_status($this->request->data['customer_id']);
				$checklist_id = $bchecklist['BikesupervisorChecklist']['id'];
				$this->response['message'] = __('Last Record was save successfully');
				
				$this->response['error'] = 0;
			}
			
			
			
			//get user_id  for hrms integration.
			/* $this->loadModel('User');
			if(!empty($this->request->data['user_id']) && !empty($this->request->data['created'])){}
				$uid1 = $this->request->data['user_id'];
				$created_date = $this->request->data['created'];
				$this->_updateAttendance_visitentry($uid1, $created_date);
			}*/
		}
		if(!empty($this->request->data['request_id']) && empty($this->request->data['id']) ){
			$checklist_id = empty($checklist_id)?0:$checklist_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $checklist_id);
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/**
	 *get BikesupervisorChecklist
	 *
	*/
	public function getBikesupervisorChecklist(){
		$this->loadModel('BikesupervisorChecklist');
		$conditions = array();
		
		
		$this->BikesupervisorChecklist->visibleRoleConditions($conditions, $this->user, $this->paginate);
		//$this->CustomerVisit->visibleConditions($conditions, $this->user);
		$this->paginate['order'] = array('BikesupervisorChecklist.id' => 'desc');
		$visits = $this->paginate('BikesupervisorChecklist', $conditions);
		if($visits){
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['BikesupervisorChecklist']['page'] - 1) * $this->params->params['paging']['BikesupervisorChecklist']['limit'];
			foreach($visits as $key=>$visit){
				$visits[$key]['sno'] = ++$i;
			}
			$this->response['data'] = $visits;
			$paging = array();
			$paging['page'] = $this->params->params['paging']['BikesupervisorChecklist']['page'];
			$paging['current'] = $this->params->params['paging']['BikesupervisorChecklist']['current'];
			$paging['count'] = $this->params->params['paging']['BikesupervisorChecklist']['count'];
			$paging['pageCount'] = $this->params->params['paging']['BikesupervisorChecklist']['pageCount'];
			
			if (!empty($this->params->params['paging']['BikesupervisorChecklist']['prevPage'])){
				$paging['prev'] = Router::url(array('controller'=>'services', 'action'=>'getBikesupervisorChecklist', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['BikesupervisorChecklist']['page'] - 1), 'ext'=>'json'), true);
			}
			if (!empty($this->params->params['paging']['BikesupervisorChecklist']['nextPage'])){
				
				$paging['next'] = Router::url(array('controller'=>'services', 'action'=>'getBikesupervisorChecklist', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['BikesupervisorChecklist']['page'] + 1), 'ext'=>'json'), true);
			}
		
			$this->response['paging'] = $paging;
		}else{
			$this->response['message'] = __('Data not found');
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/**
     * deleteBikesupervisorChecklist method
     *
     * @param string $id
     * @return void
     */
    public function deleteBikesupervisorChecklist() {
		$this->loadModel('BikesupervisorChecklist');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$customer = array();
		if(empty($this->request->data['checklist_id'])){
			$this->response['message'] = __('BikesupervisorChecklist id should not be empty');
		}else{
			$id = $this->BikesupervisorChecklist->id = $this->request->data['checklist_id'];
			$bikesupervisorChecklist = $this->BikesupervisorChecklist->read();
		}
       if (!$bikesupervisorChecklist) {
             $this->response['message'] =  __(BikesupervisorChecklist);
        }
		
        if ($this->BikesupervisorChecklist->delete()) {
			$this->response['message'] = __('BikesupervisorChecklist was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('BikesupervisorChecklist was not deleted');   
		}
		echo json_encode($this->response);
		exit;
    }
}