<?php
App::uses('AppController', 'Controller');
/**
 * 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(!$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'){
					echo json_encode(unserialize($rdData['response']), JSON_ERROR_CTRL_CHAR );
					exit;
				}
			}
		}
	}
	
	
	
	/**
	 * getAppSettingsData Action
	 * default list of comon data
	 */
	 //appsetting
	function getAppSettingsData(){
		$data = array();
		
		$this->loadModel('Depot');
		$this->loadModel('LgArea');
		$this->loadModel('Customer');
		$this->loadModel('Consumer');
		$this->response['error'] = 0;
		
		$depots = $this->Depot->find('all', array('fields'=>array('id', 'title', 'region_id'), 'order' => array('title'=>'asc')));
		
		$data['depots'] = ($depots)?$depots:null;
		
		$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();
		$data['routes'] = $this->Service->routesList();

		$users = $this->User->usersListByRole($this->user, true);
		if ($users){
			$data['users'] = $users;
		}else{
			$data['users'] = null;
		}
		$data['comment'] = $this->Service->comment();
		$brands = $this->Service->brand_price_list();
		$data['brands'] = $brands;
		$sale_types = sale_type();
		$data['saleType'] = array_keys($sale_types);
		$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;
		$sku = array();
		$skuList = get_sku();
		if($skuList){
			foreach( $skuList as $k => $sk){
				$sku[] = array('id'=>$k, 'value'=>$sk);
			}
		}
		$data['sku'] = $sku;
		$fiType = array();
		$free_issue_type = incentive_type();
		if($free_issue_type){
			foreach( $free_issue_type as $fik => $fi_val){
				$fiType[] = array('id'=>$fik, 'value'=>$fi_val);
			}
		}
		$data['freeIssueType'] = $fiType;
		
		$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;
		}

		$categories = categories();
		foreach( $categories as $k => $d){
			$data['categories'][] = array('id'=> $k, 'value' =>$d);
		}
		$subcategories = subcategories();
		foreach( $subcategories as $k => $d){
			$data['subcategories'][] = array('id'=> $k, 'value' =>$d);
		}
		$paymentterms = paymentterms();
		foreach( $paymentterms as $d){
			$data['paymentterms'][]  = array('id'=> $d, 'value' =>$d);
		}
		$customer = $this->Customer->customerListByRole($this->user, true);
		$data['customers'] = $customer['customersList'];
		$data['customersWithDepot'] = $customer['customers'];
		
		$this->response['data'] = $data;
		echo json_encode($this->response);
		exit;
	}
	
	function getMoreCustomer(){
		//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(){
		$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();
		$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');
			}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;
					}
					$customer = $this->Customer->save($this->request->data);
					
					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;
    }
//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;
					}
					$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;
    }

	/**
	 *get customer visit
	 *
	*/
	public function getCustomerVisit(){
		$this->loadModel('CustomerVisit');
		$cDateTime = time();
		$td = date('Y-m-d', strtotime("0 day", $cDateTime) );
		$yd = date('Y-m-d', strtotime("1 day", $cDateTime) );
		$conditions = array();
		$conditions[] = array('CustomerVisit.visiting_date BETWEEN ? AND ?' => array($td,$yd ));
		
		$this->CustomerVisit->visibleRoleConditions($conditions, $this->user, $this->paginate);
		//$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;
	}
	/**
     * 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 (!empty($this->request->data['newCustomer'])){
				$customerId = $this->_addCustomer($this->request->data['newCustomer']);
				$this->request->data['customer_id'] = $customerId;
			}
			if(!empty($this->request->data['visit_id'])){
				$this->request->data['id'] = $this->request->data['visit_id'];
				unset($this->request->data['user_id']);
			}else{
				$this->request->data['user_id'] = $this->user['id'];
			}
			if (empty($this->request->data['visiting_date'])){
				$this->request->data['visiting_date'] = date('Y-m-d H:i:s');
			}
			
			//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('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 customer visit entry already added');
			}else{
				$cvisit = $this->CustomerVisit->save($this->request->data);
				$visit_id = $cvisit['CustomerVisit']['id'];
				$this->response['message'] = __('Last Record was save successfully');
			}
			
			$this->response['error'] = 0;
			
			$this->loadModel('User');
			$uid1 = $this->request->data['user_id'];
			$this->loadModel('CustomerVisit');
			//$vdate = $this->CustomerVisit->find('all',array('fields' => array('created'), 'conditions'=>array('CustomerVisit.id'=>194)));
			$vdate=$this->request->data['CustomerVisit']['visiting_date'] = date('Y-m-d H:i:s');
			$this->_updateAttendance_visitentry($uid1,$vdate);
		}
		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,$date1){
		$this->loadModel('User');
		$eid = $this->User->find('first', array('fields'=> array('employee_id'), 'conditions'=>array('User.id' => $id)));
		$emp_id = $eid['User']['employee_id'];
		$vdate=$date1;
		$currentDate = strtotime($vdate);
		$futureDate = $currentDate+29;
		$vd = date("H:i:s", $futureDate);
		$vd1=date("Y-m-d H:i:s", $futureDate);
		$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');
		$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'=> $vd1, 'in_time'=> $vd, 'date'=>$date);
			}
			$this->Attendance->save($data);
		}
		else{

			$this->_updateAttendance_visitexit($emp_id,$vdate);
		}
		 
	}
	function _updateAttendance_visitexit($emp_id,$vdate){
		$this->loadModel('Attendance');
		$this->loadModel('Employee');
		$this->loadModel('Company');
		$this->Attendance->useDbConfig = 'hrminfo';
		$this->Employee->useDbConfig = 'hrminfo';
		$this->Company->useDbConfig = 'hrminfo';
		$currentDate = strtotime($vdate);
		$futureDate = $currentDate+29;
		
		$vd = date("H:i:s", $futureDate);
		$vd1=date("Y-m-d H:i:s", $futureDate);
		$date = date('Y-m-d');
		$data = array();
		
		$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
		
			if($attendance){
				if($attendance['Attendance']['out_time'] == ''){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=>$vd1, 'out_time'=> $vd, 'date'=>$date);
				}else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'], 'out_time' => $vd, 'punch_time' => $vd1);
				}
				$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();
		$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 );
			}
			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'];
				}				
			}
				
			$payment = $this->Payment->save($this->request->data);
			$this->response['date'] = $payment;
			$payment_id = $payment['Payment']['id'];
			if (!empty($this->request->data['id'] )){
				$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()) {
			$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();
		$this->Expense->_userCondition($conditions, $this->user);
		$expenses = $this->paginate('Expense', $conditions);
		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 );
			}
			$this->loadModel('Expense');
			
			if (empty($this->request->data['depot_id'])){
				$this->request->data['depot_id'] = $this->user['depot_id'];
			}
			if ( !empty($this->request->data['id'])){
				$this->request->data['id'] = $this->request->data['id'];
				unset($this->request->data['user_id']);
			}else{
				$this->request->data['user_id'] = $this->user['id'];
			}
			$expence = $this->Expense->save($this->request->data);
			$this->response['data'] = $expence;
			$expence_id = $expence['Expense']['id'];
			if (!empty($this->request->data['id'] ) || !empty($this->request->data['expense_id']) ){
				$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()) {
			$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'];
			$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;
		}
	}
}
