<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::import('Controller', 'Functions'); 
/**
 * Controller name
 *
 * @var string
 */
class SalesappController extends AppController
{
	var $response;
	var $user;
	var $uses = array('User', 'Service');
	var $token;
	var $appLogs;
	 
	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($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){
				$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(APP_LOGS){
				$this->appLogs = $this->AppLog->save($logData);
			}
			if(!$this->user){
				$this->response['message'] = 'Invalid token';
				$this->response['error'] = 3;
				echo json_encode($this->response);
				//pr($this->appLogs);
				$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;
				}
			}
		}
	}
	
	/**
	 * saleOrders method
	 *
	 */
	public function saleOrders(){
		$this->loadModel('Order');
		$this->loadModel('Sale');
		
		$conditions = array();
		$this->response['error'] = 0;
		
		// To fetch current month data only
		$conditions['Order.order_date >= '] = date('Y-m-01'); 
		
		$this->Sale->_userRoleCondition($conditions, $this->user, $this->paginate);
		//$this->Sale->_userCondition($conditions, $this->user);
		$this->paginate['order'] = array('Order.order_date' => 'desc', 'Order.created' => 'desc');
		
		$this->Order->hasMany = array('sales'=>array('className' => 'Sale', 'foreignKey' => 'order_id', 'finderQuery' => 'SELECT sales.id, sales.brand_id, sales.user_id, sales.customer_id, sales.depot_id, sales.unit, sales.cal_qty, sales.unit_price, sales.quantity, sales.amount, sales.sale_date, sales.order_id, Brand.name FROM `sales` AS `sales` LEFT JOIN `brands` AS `Brand` ON (`sales`.`brand_id`=`Brand`.`id`) WHERE `sales`.`order_id` IN ({$__cakeID__$})'), 'freeItems'=>array('className' => 'freeItems', 'foreignKey' => 'order_id', 'finderQuery' => 'SELECT freeItems.id, freeItems.brand_id, freeItems.order_id, freeItems.depot_id, freeItems.unit, freeItems.cal_qty, freeItems.quantity, freeItems.quantity, freeItems.sale_date, freeItems.compaign_id, Brand.name FROM `free_items` AS `freeItems` LEFT JOIN `brands` AS `Brand` ON (`freeItems`.`brand_id`=`Brand`.`id`) WHERE `freeItems`.`order_id` IN ({$__cakeID__$})'));
		
		$orders = $this->paginate('Order', $conditions);
		
		$i = ($this->params->params['paging']['Order']['page'] - 1) * $this->params->params['paging']['Order']['limit'];			
		if ($orders){
			foreach ($orders as $key => $order){
				$orders[$key]['sno'] = ++$i;
			}
		}
		
		$this->response['data'] = $orders;
		
		$paging = array();
		//pr($this->params->params['paging']);
		$paging['page'] = $this->params->params['paging']['Order']['page'];
		$paging['current'] = $this->params->params['paging']['Order']['current'];
		$paging['count'] = $this->params->params['paging']['Order']['count'];
		$paging['pageCount'] = $this->params->params['paging']['Order']['pageCount'];
		$paging['limit'] = $this->params->params['paging']['Order']['limit'];
		
		if (!empty($this->params->params['paging']['Order']['prevPage'])){
			$paging['prev'] = Router::url(array('controller'=>'salesapp', 'action'=>'saleOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Order']['page'] - 1), 'ext'=>'json'), true);
		}
		if (!empty($this->params->params['paging']['Order']['nextPage'])){
			$paging['next'] = Router::url(array('controller'=>'salesapp', 'action'=>'saleOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Order']['page'] + 1), 'ext'=>'json'), true);
		}
	
		$this->response['paging'] = $paging;
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	
	
	/**
	 * updatesale method
	 *
	 */
	public function updatesale(){
		
		if ($this->request->data){ //pr($this->request->data); //die();
			
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			
			$data = $stockStatus = array();
			$this->loadModel('Order');
			$this->loadModel('Sale');
			$this->loadModel('FreeItem');
			$this->loadModel('Brand');
			
					
			if( empty($this->request->data['sales']) || count($this->request->data['sales']) == 0 )
			{
				$this->response['message'] = __('Something missing, Please check your sale data entry table');
				$this->response['error'] = 2;
			}
			else
			{
				//Add New Customer
				if (!empty($this->request->data['newCustomer'])){
					$customerId = $this->_add_customer($this->request->data['newCustomer']);
					$this->request->data['customer_id'] = $customerId;
				}
				
				if (!empty($this->request->data['customer_id'])){
					
					$orderData = array('customer_id' => $this->request->data['customer_id'],'order_date'=>$this->request->data['sale_date'], 'items'=>count($this->request->data['sales']), 'total' => $this->request->data['grand_total'] );
					
					if(!empty($this->request->data['order_id'])){
						$orderData['id'] = $this->request->data['id'] = $this->request->data['order_id'];
						$orderData['app_modified'] = 1;
						
						$this->Order->id = $this->request->data['id'];
						
						$exists = $this->Order->exists();

						if (!$exists) {

							$this->response['message'] = __('Order no longer exists in the system.');
							$this->response['error'] = SYNC_NOT_REQUIRED;

							echo json_encode($this->response);
							exit;
						}
						
						$this->Order->bindModel(
						array(
						'belongsTo'=>array(
							'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name', 'role_id'), 'type'=>'inner'),
						)));					
						$AuditData = $this->Order->read();
						
					}else{
						$orderData['user_id'] = $this->user['id'];
						$orderData['via_app'] = 1;
						
						if (!empty($this->request->data['latitude'])){
							$orderData['latitude'] = $this->request->data['latitude'];
						}
						
						if (!empty($this->request->data['longitude'])){
							$orderData['longitude'] = $this->request->data['longitude'];
						}
					
					}				
					
					$is_added = 0;
					
					if(empty($this->request->data['id'])){
						
						/** ---------------------------------------------------------
						 * Generate normalized sales signature from request
						 * --------------------------------------------------------- */

						$salesData = $this->request->data['sales'];

						$tmp = array();

						foreach ($salesData as $s) {

							$tmp[] = $s['brand_id'] . ':' . $s['unit'] . ':' . number_format($s['quantity'], QTY_DECIMALS, '.', '');
						}

						sort($tmp);

						$salesSignature = md5(implode('|', $tmp));
						
						
						/** ---------------------------------------------------------
						 * Duplicate check conditions
						 * --------------------------------------------------------- */						
						$conditions = array('Order.customer_id' => $this->request->data['customer_id'],'Order.order_date'=>$this->request->data['sale_date'], 'Order.user_id'=>$this->user['id'], 'Order.items'=>count($this->request->data['sales']), 'Order.total' => $this->request->data['grand_total'] );
											
						
						if (!empty($this->request->data['created'])){
							$orderData['created'] = $this->request->data['created'];

													
							$created = $this->request->data['created'];
							
							if (date('Y-m-d', strtotime($created)) == date('Y-m-d')) {
								// SAME DAY → use 2 minute duplicate protection
								// Prevent duplicates within the last 2 minute (including exact matches)
								$conditions['Order.created >='] = date("Y-m-d H:i:s", strtotime("-2 minutes", strtotime($created)));
								$conditions['Order.created <='] = $created;

							} else {
								// DIFFERENT DAY
								if (strtotime($created) >= strtotime('-15 days')) {
									// LAST 15 DAYS → → use FULL DAY match instead of 2 minute window
									$conditions['DATE(Order.created)'] = date('Y-m-d', strtotime($created));

								} else {
									// OLDER THAN 15 DAYS → fallback to order_date
									$conditions['Order.order_date'] = $this->request->data['sale_date'];
								}
							}

						}
						
						/** ---------------------------------------------------------
						 * STEP 1:
						 * Find possible matching orders only
						 * --------------------------------------------------------- */

						$possibleOrders = $this->Order->find('list', array('fields' => array('Order.id'),
							'conditions' => $conditions,'recursive' => -1));


						/** ---------------------------------------------------------
						 * STEP 2:
						 * Compare sales signatures
						 * --------------------------------------------------------- */

						if (!empty($possibleOrders)) {

							$salesRows = $this->Sale->find('all', array(
								'conditions' => array('Sale.order_id' => array_values($possibleOrders)),
								'fields' => array('Sale.order_id','Sale.brand_id','Sale.unit','Sale.quantity'
								),
								'order' => array('Sale.id'),
								'recursive' => -1
							));


							/** ---------------------------------------------------------
							 * Group sales rows by order_id
							 * --------------------------------------------------------- */

							$grouped = array();
							if(!empty($salesRows)){
								foreach ($salesRows as $row) {

									$oid = $row['Sale']['order_id'];

									$grouped[$oid][] =
										$row['Sale']['brand_id'] . ':' . $row['Sale']['unit'] . ':' . number_format($row['Sale']['quantity'], QTY_DECIMALS, '.', '');
								}
							}
								


							/** ---------------------------------------------------------
							 * Compare signatures
							 * --------------------------------------------------------- */

							foreach ($grouped as $oid => $items) {

								sort($items);

								$dbSignature = md5(implode('|', $items));

								if ($dbSignature === $salesSignature) {

									$is_added = 1;
									break;
								}
							}
						}
						
						//Check already added
						//$is_added = $this->Order->find('count', array('conditions'=>$conditions)); 
					}
	
					
					//if ($is_added > 0 || $this->request->data['customer_id']==0){
					if ($is_added > 0 && empty($this->request->data['id'])){
						$this->response['message'] = __('This sales entry already added');
						$this->response['error'] = SYNC_NOT_REQUIRED;
					}else{
						
						$this->loadModel('Customer');
						$customer = $this->Customer->findById($this->request->data['customer_id']);
						
						if(!empty($customer)){
							// Start transaction
							$this->Order->getDataSource()->begin();
							try {
								//ONLY FOR ADD		 
								if(empty($this->request->data['order_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'] = $orderData['order_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;
										}
									}
									//} 
								}
								
								
								$order = $this->Order->save($orderData);
								
								/* $this->loadModel('Customer');
								$this->Customer->id = $this->request->data['customer_id'];
								$depot_id = $this->Customer->field('depot_id'); */
								
								$depot_id = $customer['Customer']['depot_id'];
								
								$order_id = $order['Order']['id'];
								
								$created = $order['Order']['created'];
								
								//ONLY FOR ADD		 
								if(empty($this->request->data['order_id'])){
																	
									/*****----- Check if entry is on correct route -----*****/
								
									$uid = $order['Order']['user_id']; 
									$date = date('Y-m-d', strtotime($order['Order']['order_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->Order->id = $order_id ;
											$this->Order->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 - Sale entry on a day other than the user's day routes.");
												$email->viewVars(array('model' => 'Order', 'data' => $order, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
												$email->template('entry_on_different_route');
												$email->send('entry_on_different_route'); 
											/**** ----------------------------------------------------- ****/
										}
									}
									/*****------------------------------------*****/
									
									$via_app = 1;
								}else{
									$this->Order->id = $order_id;
									//$via_app = $this->Order->field('via_app');
									
									$order = $this->Order->find('first', array(
										'fields' => array('Order.via_app', 'Order.created'),
										'conditions' => array('Order.id' => $order_id),
										'recursive' => -1
									));

									$via_app = $order['Order']['via_app'];
									$created = $order['Order']['created'];
					
									$this->Sale->deleteAll(array('order_id'=>$order_id), false);
									$this->FreeItem->deleteAll(array('order_id'=>$order_id), false);
								}
								
								foreach ($this->request->data['sales'] as $key => $sale ){
									
									$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$sale['brand_id'])));
									
									$data[] = array(
										'brand_id'=> $sale['brand_id'],
										'brand_group_id' =>$group_id[$sale['brand_id']],
										'order_id'=> $order_id,
										'user_id'=>$this->user['id'], 
										'depot_id'=>$depot_id, 
										'customer_id'=>$this->request->data['customer_id'],
										'sale_date'=>$this->request->data['sale_date'],
										'unit'=>$sale['unit'], 
										'unit_price'=>$sale['unit_price'], 
										'quantity' =>$sale['quantity'], 
										'cal_qty' => @$this->Sale->calQty($sale['brand_id'], $sale['unit'], $sale['quantity']), 
										'amount'=>$sale['amount'],
										'via_app' => $via_app,
										'created' => $created
									);			
									
								}
								//Free Data
								
								$freeData = array();
								if (!empty($this->request->data['freeItems'])){
									
									foreach ($this->request->data['freeItems'] as $key => $freeItem ){
										
										$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$freeItem['brand_id'])));
										
										$unit_price = $this->Brand->getUnitPrice('sale', $freeItem['brand_id'], $freeItem['unit']);
										$amount = $freeItem['quantity'] * $unit_price;
										
										$freeData[] = array(
											'order_id' => $order_id,
											'brand_id' => $freeItem['brand_id'],
											'brand_group_id' =>$group_id[$freeItem['brand_id']],
											'depot_id' => $depot_id, 
											'user_id'=>$this->user['id'], 
											'customer_id'=>$this->request->data['customer_id'],
											'sale_date' => $this->request->data['sale_date'],
											'unit' => $freeItem['unit'],
											'quantity' => $freeItem['quantity'],
											'unit_price'=>$unit_price, 
											'amount'=>$amount,
											'compaign_id' => $freeItem['compaign_id'],
											'cal_qty' => @$this->Sale->calQty($freeItem['brand_id'], $freeItem['unit'], $freeItem['quantity']),
											'via_app' => $via_app,
											'created' => $created
										);
									 
									}
								}
								if ($data){
									//pr($data);
									$saveItems = @$this->Sale->saveAll($data);
									if(!$saveItems ){
										$this->Order->id = $order_id;
										$this->Order->delete();
									}
									if ($freeData){
										@$this->FreeItem->saveAll($freeData);
									}
									$this->Customer->verify_status($this->request->data['customer_id']);
									$this->response['message'] = __('Sales was saved 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);
									}else{
										//Edit entry
										
										/**** Audit START ****/
											if(!empty($AuditData)){
												$AuditSaleData['Sale'] = $AuditData['Sale'];

												$this->loadModel('Audit');
												$this->Audit->saveDeletedData($AuditData['Order']['id'], 'Order', $this->user['id'] , serialize($AuditData),'Order Has been updated',STATUS_EDIT , serialize($AuditSaleData));
											}
											
										/**** Audit END ****/
									}
								}
								// Commit the transaction
								$this->Order->getDataSource()->commit();
								
								$this->response['error'] = 0;	
								
							}catch (Exception $e) {
								// Rollback the transaction if anything fails
								$this->Order->getDataSource()->rollback();
								
								$this->response['message'] = __('Something went wrong. Sale was not saved.');
								
								$this->response['error'] = 2;
							}
						}else{
							$this->response['message'] = __('Unable to save. Customer no longer exists in the system.');
								$this->response['error'] = SYNC_NOT_REQUIRED;
						}	
					}
					
				
				}else{
					$this->response['message'] = __('Unable to save. Customer is missing.');
					$this->response['error'] = SYNC_NOT_REQUIRED;
				}
			}
		}
		if(!empty($this->request->data['request_id'])){
			$order_id = empty($order_id)?0:$order_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $order_id);
		}
		echo json_encode($this->response);
		
		exit;
		
	}
	
	
	
	/**
	 * addsale method
	 *
	 */
	public function addsale(){
		
		if ($this->request->data){ 
			
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			
			$data = $stockStatus = array();
			$this->loadModel('Order');
			$this->loadModel('Sale');
			$this->loadModel('Brand');
			
					
			if( empty($this->request->data['sales']) || count($this->request->data['sales']) == 0 )
			{
				$this->response['message'] = __('Something missing, Please check your sale data entry table');
				$this->response['error'] = 2;
			}
			else
			{
				//Add New Customer
				if (!empty($this->request->data['newCustomer'])){
					$customerId = $this->_add_customer($this->request->data['newCustomer']);
					$this->request->data['customer_id'] = $customerId;
				}
				
				if (!empty($this->request->data['customer_id'])){
					$orderData = array('customer_id' => $this->request->data['customer_id'],'order_date'=>$this->request->data['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['sales']), 'total' => $this->request->data['grand_total'], 'via_app' => 1 );
					
				
					if (!empty($this->request->data['latitude'])){
						$orderData['latitude'] = $this->request->data['latitude'];
					}
					
					if (!empty($this->request->data['longitude'])){
						$orderData['longitude'] = $this->request->data['longitude'];
					}
					
					$conditions = array('Order.customer_id' => $this->request->data['customer_id'],'Order.order_date'=>$this->request->data['sale_date'], 'Order.user_id'=>$this->user['id'], 'Order.items'=>count($this->request->data['sales']), 'Order.total' => $this->request->data['grand_total'] );
					
					if (!empty($this->request->data['created'])){
						$orderData['created'] = $this->request->data['created'];
						//$conditions['Order.created'] = $this->request->data['created'];
						
						//$conditions['Order.created >'] = 'INTERVAL 1 MINUTE AND '. $this->request->data['created'];
						//$conditions['Order.created >'] = 'DATE_SUB('.$this->request->data['created'].', INTERVAL 1 MINUTE)';
						//$conditions['Order.created >'] = date("Y-m-d H:i:s", strtotime("-1 minutes", strtotime($this->request->data['created']))); 
						
						// Prevent duplicates within the last 1 minute (including exact matches)
						$conditions['Order.created >='] = date("Y-m-d H:i:s", strtotime("-1 minutes", strtotime($this->request->data['created'])));
						$conditions['Order.created <='] = $this->request->data['created'];
						
					}
					//Check already added				
					
					$is_added = $this->Order->find('count', array('conditions'=>$conditions)); 
					
					/* if($this->request->data['customer_id'] = 270138){
						pr($conditions); pr($is_added);
					} */
					
					if ($is_added > 0 || $this->request->data['customer_id']==0){	
						$this->response['message'] = __('This sales entry already added');
						$this->response['error'] = SYNC_NOT_REQUIRED;
					}else{
						
						$this->loadModel('Customer');
						$customer = $this->Customer->findById($this->request->data['customer_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'] = $orderData['order_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;
							}
						}
						//} 
						
						
						
						$order = $this->Order->save($orderData);
						
						/* $this->loadModel('Customer');
						$this->Customer->id = $this->request->data['customer_id'];
						$depot_id = $this->Customer->field('depot_id'); */
						
						$depot_id = $customer['Customer']['depot_id'];
						
						$order_id = $order['Order']['id'];
						
						
						/*****----- Check if entry is on correct route -----*****/
						$uid = $order['Order']['user_id']; 
						$date = date('Y-m-d', strtotime($order['Order']['order_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->Order->id = $order_id ;
								$this->Order->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 - Sale entry on a day other than the user's day routes.");
									$email->viewVars(array('model' => 'Order', 'data' => $order, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
									$email->template('entry_on_different_route');
									$email->send('entry_on_different_route'); 
								/**** ----------------------------------------------------- ****/
							}
						}
						/*****------------------------------------*****/
						
						foreach ($this->request->data['sales'] as $key => $sale ){
							
							$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$sale['brand_id'])));
							
							$data[] = array(
								'brand_id'=> $sale['brand_id'],
								'brand_group_id' =>$group_id[$sale['brand_id']],
								'order_id'=> $order_id,
								'user_id'=>$this->user['id'], 
								'depot_id'=>$depot_id, 
								'customer_id'=>$this->request->data['customer_id'],
								'sale_date'=>$this->request->data['sale_date'],
								'unit'=>$sale['unit'], 
								'unit_price'=>$sale['unit_price'], 
								'quantity' =>$sale['quantity'], 
								'cal_qty' => @$this->Sale->calQty($sale['brand_id'], $sale['unit'], $sale['quantity']), 
								'amount'=>$sale['amount'],
								'via_app' => 1
							);			
							
						}
						//Free Data
						$this->loadModel('FreeItem');
						$freeData = array();
						if (!empty($this->request->data['freeItems'])){
							
							foreach ($this->request->data['freeItems'] as $key => $freeItem ){
								
								$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$freeItem['brand_id'])));
								
								$unit_price = $this->Brand->getUnitPrice('sale', $freeItem['brand_id'], $freeItem['unit']);
								$amount = $freeItem['quantity'] * $unit_price;
								
								$freeData[] = array(
									'order_id' => $order_id,
									'brand_id' => $freeItem['brand_id'],
									'brand_group_id' =>$group_id[$freeItem['brand_id']],
									'depot_id' => $depot_id, 
									'user_id'=>$this->user['id'], 
									'customer_id'=>$this->request->data['customer_id'],
									'sale_date' => $this->request->data['sale_date'],
									'unit' => $freeItem['unit'],
									'quantity' => $freeItem['quantity'],
									'unit_price'=>$unit_price, 
									'amount'=>$amount,
									'compaign_id' => $freeItem['compaign_id'],
									'cal_qty' => @$this->Sale->calQty($freeItem['brand_id'], $freeItem['unit'], $freeItem['quantity']),
									'via_app' => 1
								);
							 
							}
						}
						if ($data){
							//pr($data);
							$saveItems = @$this->Sale->saveAll($data);
							if(!$saveItems ){
								$this->Order->id = $order_id;
								$this->Order->delete();
							}
							if ($freeData){
								@$this->FreeItem->saveAll($freeData);
							}
							$this->Customer->verify_status($this->request->data['customer_id']);
							$this->response['message'] = __('Sales was saved 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;
				
				}
				
				//get user_id for hrms integration
				/* $this->loadModel('User');
				$uid1 = $this->user['id'];
                                $sale_date=$this->request->data['created'];
				$this->_updateAttendance_salentry($uid1,$sale_date); */
				
				
				
			}
		}
		if(!empty($this->request->data['request_id'])){
			$order_id = empty($order_id)?0:$order_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $order_id);
		}
		echo json_encode($this->response);
		
		exit;
		
	}
	
	/*This function use for HRMS attendance update from apps*/
	
	/* function _updateAttendance_salentry($id,$sdate){
		$this->loadModel('User');
		$eid = $this->User->find('first', array('fields'=> array('employee_id'), 'conditions'=>array('User.id' => $id)));
		$emp_id = $eid['User']['employee_id'];
		//pr($eid);
		$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($sdate));
			$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'=> $sdate, 'in_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
				}
				$this->Attendance->save($data);
			}
			else{

				$this->_updateAttendance_salexit($emp_id,$sdate);
			}
		} 
	}
	function _updateAttendance_salexit($emp_id,$sdate){
		$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($sdate));
		$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'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
					}else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'],'emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
					}
				}else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'], 'out_time' => date('H:i:s',strtotime($sdate)), 'punch_time' => $sdate);
				}
				$this->Attendance->save($data);
			}
	} */
	/**
	 * orderview method
	 * @params : Post var
	 */
	public function orderview(){
		if(empty($this->request->data['order_id'])){
			$this->response['message'] = __('Order id should not be empty');
		}else{
			$data = array();
			$this->loadModel('Order');
			$this->loadModel('Sale');
			$order_id = $this->Order->id = $this->request->data['order_id'];
			$order = $this->Order->read();
			if (!$order){
				$this->response['message'] = __('Invalid Sale');
			}else{			
				$data['order'] = $order;
				$data['sales'] = $this->Sale->find('all', array('conditions'=>array('order_id'=>$order_id)));
				$this->loadModel('FreeItem');
				$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = FreeItem.brand_id'));
				$data['freeItems'] = $this->FreeItem->find('all', array('fields'=>array('FreeItem.*', 'Brand.name'), 'conditions'=>array('order_id'=>$order_id), 'joins'=>$joins));
				$this->response['error'] = 0;
				$this->response['data'] = $data;
			}
			echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
			exit;
		}
	}
	/**
	 * orderdelete action
	 */
	 public function orderdelete(){
		if(empty($this->request->data['order_id'])){
			$this->response['message'] = __('Order id should not be empty');
		}else{
			$id = $this->request->data['order_id'];
			$this->loadModel('Order');
			//$this->loadModel('Sale');
			$this->Order->id = $id;
			$this->Order->bindModel(
            array(
            'belongsTo'=>array(
                'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name', 'role_id'), 'type'=>'inner'),
            )));
        
			$AuditData = $this->Order->read();
			
			
			if ($this->Order->delete()){
				
				/**** Audit START ****/
					if(!empty($AuditData)){
						$AuditSaleData['Sale'] = $AuditData['Sale'];

						$this->loadModel('Audit');
						$this->Audit->saveDeletedData($AuditData['Order']['id'], 'Order', $this->user['id'] , serialize($AuditData),'Order Has been Deleted',STATUS_DELETE , serialize($AuditSaleData));
					}
				/**** Audit END ****/
				
				$this->response['message'] = __('Sale order was deleted');
				$this->response['error'] = 0;
			}else{
				$this->response['message'] = __('Sale order was not deleted');
				$this->response['error'] = 2;
			}
		}
		
		echo json_encode($this->response);
		exit;
	}
	
	
	
	/**
	 * consumersaleOrders method
	 *
	 */
	public function consumersaleOrders(){
		$this->loadModel('ConsumerOrder');
		$this->loadModel('ConsumerSale');
		
		$conditions = array();
		$this->response['error'] = 0;
		
		$this->ConsumerSale->_userRoleCondition($conditions, $this->user, $this->paginate);
		//$this->Sale->_userCondition($conditions, $this->user);
		$this->paginate['order'] = array('ConsumerOrder.order_date' => 'desc', 'ConsumerOrder.created' => 'desc');
		
		//$this->ConsumerOrder->hasMany = array('consumer_sales'=>array('className' => 'ConsumerSale', 'foreignKey' => 'consumer_order_id', 'finderQuery' => 'SELECT consumer_sales.id, consumer_sales.brand_id, consumer_sales.user_id, consumer_sales.consumer_id, consumer_sales.depot_id, consumer_sales.unit, consumer_sales.cal_qty, consumer_sales.unit_price, consumer_sales.quantity, consumer_sales.amount, consumer_sales.sale_date, consumer_sales.consumer_order_id, Brand.name FROM `consumer_sales` AS `consumer_sales` LEFT JOIN `brands` AS `Brand` ON (`consumer_sales`.`brand_id`=`Brand`.`id`) WHERE `consumer_sales`.`consumer_order_id` IN ({$__cakeID__$})'), 'consumerFreeItems'=>array('className' => 'consumerFreeItems', 'foreignKey' => 'consumer_order_id', 'finderQuery' => 'SELECT consumerFreeItems.id, consumerFreeItems.brand_id, consumerFreeItems.order_id, consumerFreeItems.depot_id, consumerFreeItems.unit, consumerFreeItems.cal_qty, consumerFreeItems.quantity, consumerFreeItems.quantity, consumerFreeItems.sale_date, consumerFreeItems.compaign_id, Brand.name FROM `consumer_free_items` AS `consumerFreeItems` LEFT JOIN `brands` AS `Brand` ON (`consumerFreeItems`.`brand_id`=`Brand`.`id`) WHERE `consumerFreeItems`.`consumer_order_id` IN ({$__cakeID__$})'));
	
		
		
		$this->ConsumerOrder->hasMany = array('consumersales'=>array('className' => 'ConsumerSale', 'foreignKey' => 'consumer_order_id', 'finderQuery' => 'SELECT consumersales.id, consumersales.brand_id, consumersales.user_id, consumersales.consumer_id, consumersales.depot_id, consumersales.unit, consumersales.cal_qty, consumersales.unit_price, consumersales.quantity, consumersales.amount, consumersales.sale_date, consumersales.consumer_order_id, Brand.name FROM `consumer_sales` AS `consumersales` LEFT JOIN `brands` AS `Brand` ON (`consumersales`.`brand_id`=`Brand`.`id`) WHERE `consumersales`.`consumer_order_id` IN ({$__cakeID__$})'), 'freeItems'=>array('className' => 'consumerFreeItems', 'foreignKey' => 'consumer_order_id', 'finderQuery' => 'SELECT freeItems.id, freeItems.brand_id, freeItems.consumer_order_id, freeItems.depot_id, freeItems.unit, freeItems.cal_qty, freeItems.quantity, freeItems.quantity, freeItems.sale_date, freeItems.compaign_id, Brand.name FROM `consumer_free_items` AS `freeItems` LEFT JOIN `brands` AS `Brand` ON (`freeItems`.`brand_id`=`Brand`.`id`) WHERE `freeItems`.`consumer_order_id` IN ({$__cakeID__$})'));
		
	
		
		$orders = $this->paginate('ConsumerOrder', $conditions); //pr($orders); die();
		
		$i = ($this->params->params['paging']['ConsumerOrder']['page'] - 1) * $this->params->params['paging']['ConsumerOrder']['limit'];			
		if ($orders){
			foreach ($orders as $key => $order){
				$orders[$key]['sno'] = ++$i;
			}
		}
		
		$this->response['data'] = $orders;
		
		$paging = array();
		//pr($this->params->params['paging']);
		$paging['page'] = $this->params->params['paging']['ConsumerOrder']['page'];
		$paging['current'] = $this->params->params['paging']['ConsumerOrder']['current'];
		$paging['count'] = $this->params->params['paging']['ConsumerOrder']['count'];
		$paging['pageCount'] = $this->params->params['paging']['ConsumerOrder']['pageCount'];
		$paging['limit'] = $this->params->params['paging']['ConsumerOrder']['limit'];
		
		if (!empty($this->params->params['paging']['ConsumerOrder']['prevPage'])){
			$paging['prev'] = Router::url(array('controller'=>'salesapp', 'action'=>'consumersaleOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['ConsumerOrder']['page'] - 1), 'ext'=>'json'), true);
		}
		if (!empty($this->params->params['paging']['ConsumerOrder']['nextPage'])){
			$paging['next'] = Router::url(array('controller'=>'salesapp', 'action'=>'consumersaleOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['ConsumerOrder']['page'] + 1), 'ext'=>'json'), true);
		}
	
		$this->response['paging'] = $paging;
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	
	
	/**
	 * addconsumersale method
	 *
	 */
	public function addconsumersale(){
		
	//$this->request->data['jsonString'] = '{"token":"20102645355d8c57dc04e670.53328854","created":"2019-09-12 15:32:55","request_id":"352423060686324::20190912153255","consumer_id":"23","consumer_name":"test consumer","sale_date":"2019-9-12","grand_total":"170.0","consumersales":[{"brand_id":"1","unit":"Pack","unit_price":"170.0","quantity":"1.0","amount":"170.0"}],"freeItems":[]}'; 
	
	//$this->request->data['jsonString'] = '{"token":"20102645355d8c57dc04e670.53328854","created":"2019-09-26 11:47:30","request_id":"352423060686324::20190926114730","consumer_id":"23","consumer_name":"test consumer","sale_date":"2019-9-26","grand_total":"1400.0","consumersales":[{"brand_id":"3","unit":"Roll","unit_price":"1400.0","quantity":"1.0","amount":"1400.0"}],"freeItems":[{"brand_id":"3","unit":"Pack","quantity":"1.0","compaign_id":"5"}]}'; 
		
		if ($this->request->data){ 
			
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			
			
			$data = $stockStatus = array();
			$this->loadModel('ConsumerOrder');
			$this->loadModel('ConsumerSale');
			$this->loadModel('Brand');
			
			
			
			if( empty($this->request->data['consumersales']) || count($this->request->data['consumersales']) == 0 )
			{
				$this->response['message'] = __('Something missing, Please check your sale data entry table');
				$this->response['error'] = 2;
			}
			else
			{
				//Add New Customer
				if (!empty($this->request->data['newConsumer'])){
					$consumerId = $this->_add_consumer($this->request->data['newConsumer']);
					$this->request->data['consumer_id'] = $consumerId;
				}
				$orderData = array('consumer_id' => $this->request->data['consumer_id'],'order_date'=>$this->request->data['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['consumersales']), 'total' => $this->request->data['grand_total'], 'via_app' => 1 );  
				
				if (!empty($this->request->data['latitude'])){
						$orderData['latitude'] = $this->request->data['latitude'];
					}
					
					if (!empty($this->request->data['longitude'])){
						$orderData['longitude'] = $this->request->data['longitude'];
					}
				
				$conditions = array('ConsumerOrder.consumer_id' => $this->request->data['consumer_id'],'ConsumerOrder.order_date'=>$this->request->data['sale_date'], 'ConsumerOrder.user_id'=>$this->user['id'], 'ConsumerOrder.items'=>count($this->request->data['consumersales']), 'ConsumerOrder.total' => $this->request->data['grand_total'] ); 
				
				
				if (!empty($this->request->data['created'])){
					$orderData['created'] = $this->request->data['created'];
					$conditions['ConsumerOrder.created'] = $this->request->data['created'];
				}
			
				//Check already added				
				
				$is_added = $this->ConsumerOrder->find('count', array('conditions'=>$conditions)); 
				
				if ($is_added > 0 || $this->request->data['consumer_id']==0){	
					$this->response['message'] = __('This sales entry already added');
					$this->response['error'] = SYNC_NOT_REQUIRED;
				}else{
					$order = $this->ConsumerOrder->save($orderData); //pr($order); 
					
					$this->loadModel('Consumer');
					$this->Consumer->id = $this->request->data['consumer_id'];
					$depot_id = $this->Consumer->field('depot_id');
					
					$order_id = $order['ConsumerOrder']['id'];
					$this->loadModel('Sale');
					foreach ($this->request->data['consumersales'] as $key => $sale ){
						
						$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$sale['brand_id'])));
						
						$data[] = array(
							'brand_id'=> $sale['brand_id'],
							'brand_group_id' =>$group_id[$sale['brand_id']],
							'consumer_order_id'=> $order_id,
							'user_id'=>$this->user['id'], 
							'depot_id'=>$depot_id, 
							'consumer_id'=>$this->request->data['consumer_id'],
							'sale_date'=>$this->request->data['sale_date'],
							'unit'=>$sale['unit'], 
							'unit_price'=>$sale['unit_price'], 
							'quantity' =>$sale['quantity'], 
							'cal_qty' => @$this->Sale->calQty($sale['brand_id'], $sale['unit'], $sale['quantity']), 
							'amount'=>$sale['amount']
						);			
						
					}
					//Free Data
					$this->loadModel('ConsumerFreeItem');
					$freeData = array();
					if (!empty($this->request->data['freeItems'])){
						
						foreach ($this->request->data['freeItems'] as $key => $freeItem ){
							
							$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$freeItem['brand_id'])));
							
							$freeData[] = array(
								'consumer_order_id' => $order_id,
								'brand_id' => $freeItem['brand_id'],
								'brand_group_id' =>$group_id[$freeItem['brand_id']],
								'depot_id' => $depot_id, 
								'sale_date' => $this->request->data['sale_date'],
								'unit' => $freeItem['unit'],
								'quantity' => $freeItem['quantity'],
								'compaign_id' => $freeItem['compaign_id'],
								'cal_qty' => @$this->Sale->calQty($freeItem['brand_id'], $freeItem['unit'], $freeItem['quantity'])
							);
						 
						}
					}
					
					if ($data){
						//pr($data);
						$saveItems = @$this->ConsumerSale->saveAll($data);
						if(!$saveItems ){
							$this->ConsumerOrder->id = $order_id;
							$this->ConsumerOrder->delete();
						}
						if ($freeData){
							@$this->ConsumerFreeItem->saveAll($freeData);
						}
						$this->Consumer->verify_status($this->request->data['consumer_id']);
						$this->response['message'] = __('ConsumerSales was saved 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;
				
				//get user_id for hrms integration
				/* $this->loadModel('User');
				$uid1 = $this->user['id'];
                $sale_date=$this->request->data['created'];
				//$this->_updateAttendance_salentry($uid1,$sale_date); */
				
				
				
			} 
		}
		if(!empty($this->request->data['request_id'])){
			$order_id = empty($order_id)?0:$order_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $order_id);
		}
		echo json_encode($this->response);
		
		exit;
		
	}
	
	
	/**
	 * orderview method
	 * @params : Post var
	 */
	public function consumerorderview(){
		if(empty($this->request->data['consumer_order_id'])){
			$this->response['message'] = __('ConsumerOrder id should not be empty');
		}else{
			$data = array();
			$this->loadModel('ConsumerOrder');
			$this->loadModel('ConsumerSale');
			$order_id = $this->ConsumerOrder->id = $this->request->data['consumer_order_id'];
			$order = $this->ConsumerOrder->read(); //pr($order); die();
			if (!$order){
				$this->response['message'] = __('Invalid ConsumerSale');
			}else{			
				$data['consumerorder'] = $order;
				$data['consumersales'] = $this->ConsumerSale->find('all', array('conditions'=>array('consumer_order_id'=>$order_id)));
				$this->loadModel('ConsumerFreeItem');
				$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = ConsumerFreeItem.brand_id'));
				$data['freeItems'] = $this->ConsumerFreeItem->find('all', array('fields'=>array('ConsumerFreeItem.*', 'Brand.name'), 'conditions'=>array('consumer_order_id'=>$order_id), 'joins'=>$joins)); 
				$this->response['error'] = 0;
				$this->response['data'] = $data;
			}
			echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
			exit;
		}
	}
	
	
	/**
	 * orderdelete action
	 */
	 public function consumerorderdelete(){
		if(empty($this->request->data['consumer_order_id'])){
			$this->response['message'] = __('ConsumerOrder id should not be empty');
		}else{
			$id = $this->request->data['consumer_order_id'];
			$this->loadModel('ConsumerOrder');
			$this->loadModel('ConsumerSale');
			$this->ConsumerOrder->id = $id;
			if ($this->ConsumerOrder->delete()){
				$this->response['message'] = __('ConsumerSale order was deleted');
				$this->response['error'] = 0;
			}else{
				$this->response['message'] = __('ConsumerSale order was not deleted');
				$this->response['error'] = 2;
			}
		}
		
		echo json_encode($this->response);
		exit;
	}
	
	public function distributorSalesOrders(){
		$this->loadModel('RedistributorSale');
		$conditions = array();
		
		// To fetch current month data only
		$conditions['RedistributorSale.sale_date >= '] = date('Y-m-01');
		
		$this->RedistributorSale->_userSalesCondition($conditions, $this->user);
		$this->paginate['order'] = array('RedistributorSale.sale_date' => 'desc', 'RedistributorSale.created' => 'desc');
		
		$this->RedistributorSale->hasMany = array('sales'=>array('className' => 'RedistributorSaleitem', 'foreignKey' => 'redistributor_sale_id', 'finderQuery' => 'SELECT sales.id, sales.brand_id, sales.user_id, sales.redistributor_id, sales.depot_id, sales.unit, sales.cal_qty, sales.unit_price, sales.quantity, sales.amount, sales.sale_date, sales.redistributor_sale_id, Brand.name FROM `redistributor_saleitems` AS `sales` LEFT JOIN `brands` AS `Brand` ON (`sales`.`brand_id`=`Brand`.`id`) WHERE `sales`.`redistributor_sale_id` IN ({$__cakeID__$})'));
		
		//$this->RedistributorSale->hasMany = array('sales'=>array('className' => 'RedistributorSaleitem', 'foreignKey' => 'redistributor_sale_id'));
				
		$rsales = $this->paginate('RedistributorSale', $conditions);
		if($rsales){
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['RedistributorSale']['page'] - 1) * $this->params->params['paging']['RedistributorSale']['limit'];	
			
			foreach ($rsales as $key => $rsale){
				$rsales[$key]['sno'] = ++$i;
			}
		
			$this->response['data'] = $rsales;
			$paging = array();
			$paging['page'] = $this->params->params['paging']['RedistributorSale']['page'];
			$paging['current'] = $this->params->params['paging']['RedistributorSale']['current'];
			$paging['count'] = $this->params->params['paging']['RedistributorSale']['count'];
			$paging['pageCount'] = $this->params->params['paging']['RedistributorSale']['pageCount'];
			
			if (!empty($this->params->params['paging']['RedistributorSale']['prevPage'])){
				$paging['prev'] = Router::url(array('controller'=>'salesapp', 'action'=>'distributorSalesOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['RedistributorSale']['page'] - 1), 'ext'=>'json'), true);
			}
			if (!empty($this->params->params['paging']['RedistributorSale']['nextPage'])){
				
				$paging['next'] = Router::url(array('controller'=>'salesapp', 'action'=>'distributorSalesOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['RedistributorSale']['page'] + 1), 'ext'=>'json'), true);
			}
		
			$this->response['paging'] = $paging;
			
		}else{
			$this->response['message'] = __('Data not found');
			$this->response['error'] = 2;
		}
		echo json_encode($this->response);
		exit;
		
	}
	
	
	
	
	
	/**
	 * rdsaleview method
	 * 
	 */
	public function rdsaleview(){
		$this->loadModel('RedistributorSale');
		$this->loadModel('RedistributorSaleitem');
		if(empty($this->request->data['rdsale_id'])){
			$this->response['message'] = __('Redistributor Sale id should not be empty');
			$this->response['error'] = 2;
		}else{
			$data = array();
			$id = $this->RedistributorSale->id = $this->request->data['rdsale_id'];
			$this->RedistributorSale->id = $id;
			$rdsale = $this->RedistributorSale->read();
			if ($rdsale){
				$joins1 = array(array('table'=>'brands', 'alias' => 'Brand', 'type'=>'inner', 'conditions' => 'Brand.id = RedistributorSaleitem.brand_id'));
				
				$sales = $this->RedistributorSaleitem->find('all', array('conditions' => array('redistributor_sale_id'=>$id),'fields'=>array('RedistributorSaleitem.*', 'Brand.name'), 'joins'=>$joins1 ));
				$this->loadModel('RdFreeItem');
				$joins = array(array('table'=>'brands', 'alias' => 'Brand', 'type'=>'inner', 'conditions' => 'Brand.id = RdFreeItem.brand_id'));
				$freeItems = $this->RdFreeItem->find('all', array('fields'=>array('RdFreeItem.*', 'Brand.name'), 'conditions'=>array('redistributor_sale_id' => $id), 'joins'=>$joins));
				$this->response['error'] = 0;
				$data = compact('rdsale', 'sales', 'freeItems');
				$this->response['data'] = $data;
				
			}else{
				$this->response['message'] = __('Redistributor Sale data not found');
				$this->response['error'] = 2;
			}
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	/**
	 * rdsaleview method
	 * 
	 */
	
	
	public function rdsaledelete(){
		if(empty($this->request->data['rdsale_id'])){
			$this->response['message'] = __('Redistributor Sale id should not be empty');
		}else{
			$this->loadModel('RedistributorSale');
			
			$this->RedistributorSale->bindModel(
            array(
            'belongsTo'=>array(
                'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name', 'role_id'), 'type'=>'inner'),
            )));
			
			$this->RedistributorSale->id = $this->request->data['rdsale_id'];
						
			
			if (!$this->RedistributorSale->exists()) {
				$this->response['message'] = __('Invalid Redistributor Sale');
				$this->response['error'] = 2;
			}
			
			
			$AuditData = $this->RedistributorSale->read();
			
			
			if ($this->RedistributorSale->delete()) {
				
				/**** Audit START ****/
					if(!empty($AuditData)){
						$AuditSaleData['RsSale'] = $AuditData['RedistributorSaleitem'];

						$this->loadModel('Audit');
						$this->Audit->saveDeletedData($AuditData['RedistributorSale']['id'], 'RedistributorSale', $this->user['id'] , serialize($AuditData),'RedistributorSale Has been Deleted',STATUS_DELETE , serialize($AuditSaleData));
					}
				/**** Audit END ****/
				
				$this->response['error'] = 0;
				$this->response['message'] = __('Redistributor Sale was deleted successfully');
			}else{
				$this->response['message'] = __('Redistributor Sale was not deleted');
				$this->response['error'] = 2;
			}
		}
		echo json_encode($this->response);
		exit;
	}
	
	
	public function updaterdsale(){  
		$this->loadModel('RedistributorSale');
		$this->loadModel('RedistributorSaleitem');
		$this->loadModel('RdFreeItem');
		$this->loadModel('Sale');
		$this->loadModel('Brand'); 
			
		if ($this->request->data){
			
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
						
			$data = $stockStatus = array();
			
			if ( empty($this->request->data['sales']) || count($this->request->data['sales']) == 0)
			{
				$this->response['message'] = __('Something missing, Please check your sale data entry table');
				$this->response['error'] = 2;
			}
			else
			{
				
				if (!empty($this->request->data['newCustomer'])){
					$customerId = $this->_add_customer($this->request->data['newCustomer']);
					$this->request->data['customer_id'] = $customerId;
				}
				
				
				if (!empty($this->request->data['customer_id'])){
					
					$orderData = array('redistributor_id' => $this->request->data['redistributor_id'], 'customer_id' => $this->request->data['customer_id'], 'sale_date'=>$this->request->data['sale_date'], 'items'=>count($this->request->data['sales']), 'total' => $this->request->data['grand_total']);
					
					if(!empty($this->request->data['redistributor_sale_id'])){
						$orderData['id'] = $this->request->data['id'] = $this->request->data['redistributor_sale_id'];
						$orderData['app_modified'] = 1;
						
						$this->RedistributorSale->id = $this->request->data['id'];
						
						$exists = $this->RedistributorSale->exists();

						if (!$exists) {

							$this->response['message'] = __('Rsale no longer exists in the system.');
							$this->response['error'] = SYNC_NOT_REQUIRED;

							echo json_encode($this->response);
							exit;
						}
						
						$this->RedistributorSale->bindModel(
						array(
						'belongsTo'=>array(
							'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name', 'role_id'), 'type'=>'inner'),
						)));					
						$AuditData = $this->RedistributorSale->read();
						
					}else{
						$orderData['user_id'] = $this->user['id'];
						$orderData['via_app'] = 1;
						
						if (!empty($this->request->data['latitude'])){
							$orderData['latitude'] = $this->request->data['latitude'];
						}
						
						if (!empty($this->request->data['longitude'])){
							$orderData['longitude'] = $this->request->data['longitude'];
						}
					}
					
					
					$is_added = 0;
					
					if(empty($this->request->data['id'])){
						
						/** ---------------------------------------------------------
						 * Generate normalized sales signature from request
						 * --------------------------------------------------------- */

						$salesData = $this->request->data['sales'];

						$tmp = array();

						foreach ($salesData as $s) {

							$tmp[] = $s['brand_id'] . ':' . $s['unit'] . ':' . number_format($s['quantity'], QTY_DECIMALS, '.', '');
						}

						sort($tmp);

						$salesSignature = md5(implode('|', $tmp));
						
						
						/** ---------------------------------------------------------
						 * Duplicate check conditions
						 * --------------------------------------------------------- */	
						 
						$conditions = array('RedistributorSale.redistributor_id' => $this->request->data['redistributor_id'], 'RedistributorSale.customer_id' => $this->request->data['customer_id'], 'RedistributorSale.sale_date'=>$this->request->data['sale_date'], 'RedistributorSale.user_id'=>$this->user['id'], 'RedistributorSale.items'=>count($this->request->data['sales']), 'RedistributorSale.total' => $this->request->data['grand_total'] );
						
						if (!empty($this->request->data['created'])){
							
							$orderData['created'] = $this->request->data['created'];
							
							
							$created = $this->request->data['created'];
							
							if (date('Y-m-d', strtotime($created)) == date('Y-m-d')) {
								// SAME DAY → use 2 minute duplicate protection
								// Prevent duplicates within the last 2 minute (including exact matches)
								$conditions['RedistributorSale.created >='] = date("Y-m-d H:i:s", strtotime("-2 minutes", strtotime($created)));
								$conditions['RedistributorSale.created <='] = $created;

							} else {
								// DIFFERENT DAY
								if (strtotime($created) >= strtotime('-15 days')) {
									// LAST 15 DAYS → → use FULL DAY match instead of 2 minute window
									$conditions['DATE(RedistributorSale.created)'] = date('Y-m-d', strtotime($created));

								} else {
									// OLDER THAN 15 DAYS → fallback to order_date
									$conditions['RedistributorSale.sale_date'] = $this->request->data['sale_date'];
								}
							}
						}
						
						/** ---------------------------------------------------------
						 * STEP 1:
						 * Find possible matching orders only
						 * --------------------------------------------------------- */

						$possibleOrders = $this->RedistributorSale->find('list', array('fields' => array('RedistributorSale.id'),
							'conditions' => $conditions,'recursive' => -1));


						/** ---------------------------------------------------------
						 * STEP 2:
						 * Compare sales signatures
						 * --------------------------------------------------------- */

						if (!empty($possibleOrders)) {

							$salesRows = $this->RedistributorSaleitem->find('all', array(
								'conditions' => array('RedistributorSaleitem.redistributor_sale_id' => array_values($possibleOrders)),
								'fields' => array('RedistributorSaleitem.redistributor_sale_id','RedistributorSaleitem.brand_id','RedistributorSaleitem.unit','RedistributorSaleitem.quantity'
								),
								'order' => array('RedistributorSaleitem.id'),
								'recursive' => -1
							));


							/** ---------------------------------------------------------
							 * Group sales rows by redistributor_sale_id
							 * --------------------------------------------------------- */

							$grouped = array();
							if(!empty($salesRows)){
								foreach ($salesRows as $row) {

									$oid = $row['RedistributorSaleitem']['redistributor_sale_id'];

									$grouped[$oid][] =
										$row['RedistributorSaleitem']['brand_id'] . ':' . $row['RedistributorSaleitem']['unit'] . ':' . number_format($row['RedistributorSaleitem']['quantity'], QTY_DECIMALS, '.', '');
								}
							}
								


							/** ---------------------------------------------------------
							 * Compare signatures
							 * --------------------------------------------------------- */

							foreach ($grouped as $oid => $items) {

								sort($items);

								$dbSignature = md5(implode('|', $items));

								if ($dbSignature === $salesSignature) {

									$is_added = 1;
									break;
								}
							}
						}
						
						//$is_added = $this->RedistributorSale->find('count', array('conditions'=>$conditions)); 
					}
					
					
					if ($is_added > 0 && empty($this->request->data['id']) ){	
						$this->response['message'] = __('This redistribution sales entry already added');
						$this->response['error'] = SYNC_NOT_REQUIRED;
					}else{
						
						$this->loadModel('Customer');
						$customer = $this->Customer->findById($this->request->data['customer_id']);
						
						if(!empty($customer)){
							// Start transaction
							$this->RedistributorSale->getDataSource()->begin();
							try {
								//ONLY FOR ADD		 
								if(empty($this->request->data['redistributor_sale_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'] = $orderData['sale_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;
										}
									}
									//}  
								}
								
								$order = $this->RedistributorSale->save($orderData); //pr($order ); //die();
								
								/* $this->loadModel('Customer');
								$this->Customer->id = $this->request->data['customer_id'];
								$depot_id = $this->Customer->field('depot_id'); */
								
								$depot_id = $customer['Customer']['depot_id'];
								
								$order_id = $order['RedistributorSale']['id'];
																
								$created = $order['RedistributorSale']['created'];
								
								//pr($order_id);
								
								//ONLY FOR ADD		 
								if(empty($this->request->data['redistributor_sale_id'])){
									/*****----- Check if entry is on correct route -----*****/
									$uid = $order['RedistributorSale']['user_id']; 
									$date = date('Y-m-d', strtotime($order['RedistributorSale']['sale_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->RedistributorSale->id = $order_id ;
											$this->RedistributorSale->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 - Redistributor Sale entry on a day other than the user's day routes.");
												$email->viewVars(array('model' => 'RedistributorSale', 'data' => $order, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
												$email->template('entry_on_different_route');
												$email->send('entry_on_different_route'); 
											/**** ----------------------------------------------------- ****/
										}
									}
									/*****------------------------------------*****/
									
									$via_app = 1;
								}else{
									$this->RedistributorSale->id = $order_id;
									//$via_app = $this->RedistributorSale->field('via_app');
									
									$order = $this->RedistributorSale->find('first', array(
										'fields' => array('RedistributorSale.via_app', 'RedistributorSale.created'),
										'conditions' => array('RedistributorSale.id' => $order_id),
										'recursive' => -1
									));

									$via_app = $order['RedistributorSale']['via_app'];
									$created = $order['RedistributorSale']['created'];
					
									$this->RedistributorSaleitem->deleteAll(array('redistributor_sale_id'=>$order_id), false);
									$this->RdFreeItem->deleteAll(array('redistributor_sale_id'=>$order_id), false);
								}
								
								
								//pr($this->request->data['sales']); //die();
								
								foreach ($this->request->data['sales'] as $key => $sale ){ 
									
									//Check  brand model is loaded
								$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$sale['brand_id']))); //pr($group_id); //die();
								
									
									$data[] = array(
										'brand_id'=> $sale['brand_id'],
										'brand_group_id' =>$group_id[$sale['brand_id']],
										'redistributor_sale_id'=> $order_id,
										'redistributor_id' => $this->request->data['redistributor_id'],
										'user_id' => $this->user['id'], 
										'depot_id' => $depot_id, 
										'customer_id' => $this->request->data['customer_id'],
										'sale_date'=>$this->request->data['sale_date'],
										'unit'=> $sale['unit'], 
										'unit_price'=>$sale['unit_price'], 
										'quantity' =>$sale['quantity'], 
										'cal_qty' => @$this->Sale->calQty($sale['brand_id'], $sale['unit'], $sale['quantity']), 
										'amount'=>$sale['amount'],
										'via_app' => $via_app,
										'created' => $created
									);
								}
								//Free Data
								
								$freeData = array();
								if (!empty($this->request->data['freeItem'])){
									
									foreach ($this->request->data['freeItem'] as $key => $freeItem ){
										//Check  brand model is loaded
								$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$freeItem['brand_id'])));
								

										$freeData[] = array(
											'redistributor_sale_id' => $order_id,
											'brand_id' => $freeItem['brand_id'],
											'brand_group_id' =>$group_id[$freeItem['brand_id']],
											'depot_id' => $depot_id, 
											'sale_date' => $this->request->data['sale_date'],
											'unit' => $freeItem['unit'],
											'quantity' => $freeItem['quantity'],
											'compaign_id' => $freeItem['compaign_id'],
											'cal_qty' => $this->Sale->calQty($freeItem['brand_id'], $freeItem['unit'], $freeItem['quantity']),
											'via_app' => $via_app,
											'created' => $created
										);
									}
								}
								
								
								if ($data){ //pr($data); //die();
									$saveItems = @$this->RedistributorSaleitem->saveAll($data);
									if(!$saveItems ){
										$this->RedistributorSale->id = $order_id;
										$this->RedistributorSale->delete();
									}
									
									if (!empty($freeData)){
										$this->RdFreeItem->saveAll($freeData);
									}
									$this->Customer->verify_status($this->request->data['customer_id']);
									$this->response['message'] = __('Redistributor Sales was saved 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);
									}else{
										//Edit entry
										
										/**** Audit START ****/
											if(!empty($AuditData)){
												$AuditSaleData['RsSale'] = $AuditData['RedistributorSaleitem'];

												$this->loadModel('Audit');
												$this->Audit->saveDeletedData($AuditData['RedistributorSale']['id'], 'RedistributorSale', $this->user['id'] , serialize($AuditData),'RedistributorSale Has been updated',STATUS_EDIT , serialize($AuditSaleData));
											}
										/**** Audit END ****/
									}
								}
								// Commit the transaction
								$this->RedistributorSale->getDataSource()->commit();
								
								$this->response['error'] = 0;
								
							}catch (Exception $e) {
								// Rollback the transaction if anything fails
								$this->RedistributorSale->getDataSource()->rollback();
								
								 // Log the actual error message (optional but recommended)
									CakeLog::write('error', 'Redistributor Sale Error: ' . $e->getMessage());

								// Optionally add stack trace (helpful for debugging)
									CakeLog::write('error', $e->getTraceAsString());
								
								$this->response['message'] = __('Something went wrong. Redistributor Sale was not saved.');
								
								$this->response['error'] = 2;
							}
						}else{
							$this->response['message'] = __('Unable to save. Customer no longer exists in the system.');
								$this->response['error'] = SYNC_NOT_REQUIRED;
						}	
					} 						                
				}else{
					$this->response['message'] = __('Unable to save. Customer is missing.');
					$this->response['error'] = SYNC_NOT_REQUIRED;
				}
			}
		}
		
		if(!empty($this->request->data['request_id'])){
			$order_id = empty($order_id)?0:$order_id;
			
			$this->loadModel('Service');
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $order_id);
		}
		//pr($this->response);
		echo json_encode($this->response);
		exit;
	}
	
	
	public function addrdsale(){  
		$this->loadModel('RedistributorSale');
		$this->loadModel('Sale');
		$this->loadModel('Brand'); 
			
		
			
		/* if($this->request->data['customer_id'] == 291286){
				$this->request->data['jsonString'] = '{"token":"2144787865cf4f5c96b381.26374075","created":"2019-11-29 12:40:11","request_id":"352423060686324::20191129124011","customer_id":"291286","customer_name":"Test Mumbai Test","redistributor_id":"96","sale_date":"2019-11-29","latitude":"19.1232337","longitude":"72.8620191","grand_total":"180.0","sales":[{"brand_id":"1","unit":"Pack","unit_price":"180.0","quantity":"1","amount":"180.0"}],"freeItem":[]}';
			
			$this->request->data = json_decode($this->request->data['jsonString'], true );  
			}  */
			
			 
			
			
		if ($this->request->data){
						
			$data = $stockStatus = array();
			
			if ( empty($this->request->data['sales']) || count($this->request->data['sales']) == 0)
			{
				$this->response['message'] = __('Something missing, Please check your sale data entry table');
				$this->response['error'] = 2;
			}
			else
			{
				
				if (!empty($this->request->data['newCustomer'])){
					$customerId = $this->_add_customer($this->request->data['newCustomer']);
					$this->request->data['customer_id'] = $customerId;
				}
				
				
				if (!empty($this->request->data['customer_id'])){
					$orderData = array('redistributor_id' => $this->request->data['redistributor_id'], 'customer_id' => $this->request->data['customer_id'], 'sale_date'=>$this->request->data['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['sales']), 'total' => $this->request->data['grand_total'], 'via_app' => 1 );
					
					
					if (!empty($this->request->data['latitude'])){
						$orderData['latitude'] = $this->request->data['latitude'];
					}
					
					if (!empty($this->request->data['longitude'])){
						$orderData['longitude'] = $this->request->data['longitude'];
					}
					
					$conditions = array('RedistributorSale.redistributor_id' => $this->request->data['redistributor_id'], 'RedistributorSale.customer_id' => $this->request->data['customer_id'], 'RedistributorSale.sale_date'=>$this->request->data['sale_date'], 'RedistributorSale.user_id'=>$this->user['id'], 'RedistributorSale.items'=>count($this->request->data['sales']), 'RedistributorSale.total' => $this->request->data['grand_total'] );
					
					if (!empty($this->request->data['created'])){
						$orderData['created'] = $this->request->data['created'];
						$conditions['RedistributorSale.created'] = $this->request->data['created'];
					}
					
					$is_added = $this->RedistributorSale->find('count', array('conditions'=>$conditions)); 
					
					if ($is_added > 0 || $this->request->data['customer_id']==0 ){	
						$this->response['message'] = __('This redistribution sales entry already added');
						$this->response['error'] = SYNC_NOT_REQUIRED;
					}else{
						$this->loadModel('Customer');
						$customer = $this->Customer->findById($this->request->data['customer_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'] = $orderData['sale_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;
							}
						}
						//}  
						
						$order = $this->RedistributorSale->save($orderData); //pr($order ); //die();
						
						/* $this->loadModel('Customer');
						$this->Customer->id = $this->request->data['customer_id'];
						$depot_id = $this->Customer->field('depot_id'); */
						
						$depot_id = $customer['Customer']['depot_id'];
						
						$order_id = $order['RedistributorSale']['id'];
						//pr($order_id);
						
						/*****----- Check if entry is on correct route -----*****/
						$uid = $order['RedistributorSale']['user_id']; 
						$date = date('Y-m-d', strtotime($order['RedistributorSale']['sale_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->RedistributorSale->id = $order_id ;
								$this->RedistributorSale->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 - Redistributor Sale entry on a day other than the user's day routes.");
									$email->viewVars(array('model' => 'RedistributorSale', 'data' => $order, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
									$email->template('entry_on_different_route');
									$email->send('entry_on_different_route'); 
								/**** ----------------------------------------------------- ****/
							}
						}
						/*****------------------------------------*****/
						
						
						
						//pr($this->request->data['sales']); //die();
						
						foreach ($this->request->data['sales'] as $key => $sale ){ 
							
							//Check  brand model is loaded
						$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$sale['brand_id']))); //pr($group_id); //die();
						
							
							$data[] = array(
								'brand_id'=> $sale['brand_id'],
								'brand_group_id' =>$group_id[$sale['brand_id']],
								'redistributor_sale_id'=> $order_id,
								'redistributor_id' => $this->request->data['redistributor_id'],
								'user_id' => $this->user['id'], 
								'depot_id' => $depot_id, 
								'customer_id' => $this->request->data['customer_id'],
								'sale_date'=>$this->request->data['sale_date'],
								'unit'=> $sale['unit'], 
								'unit_price'=>$sale['unit_price'], 
								'quantity' =>$sale['quantity'], 
								'cal_qty' => @$this->Sale->calQty($sale['brand_id'], $sale['unit'], $sale['quantity']), 
								'amount'=>$sale['amount'],
								'via_app' => 1
							);
						}
						//Free Data
						$this->loadModel('RedistributorSaleitem');
						$this->loadModel('RdFreeItem');
						$freeData = array();
						if (!empty($this->request->data['freeItem'])){
							
							foreach ($this->request->data['freeItem'] as $key => $freeItem ){
								//Check  brand model is loaded
						$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$freeItem['brand_id'])));
						

								$freeData[] = array(
									'redistributor_sale_id' => $order_id,
									'brand_id' => $freeItem['brand_id'],
									'brand_group_id' =>$group_id[$freeItem['brand_id']],
									'depot_id' => $depot_id, 
									'sale_date' => $this->request->data['sale_date'],
									'unit' => $freeItem['unit'],
									'quantity' => $freeItem['quantity'],
									'compaign_id' => $freeItem['compaign_id'],
									'cal_qty' => $this->Sale->calQty($freeItem['brand_id'], $freeItem['unit'], $freeItem['quantity']),
									'via_app' => 1
								);
							}
						}
						
						
						if ($data){ //pr($data); //die();
							@$this->RedistributorSaleitem->saveAll($data);
							if (!empty($freeData)){
								$this->RdFreeItem->saveAll($freeData);
							}
							$this->Customer->verify_status($this->request->data['customer_id']);
							$this->response['message'] = __('Redistributor Sales was saved 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; 
                          //get user_id  and sale_date and it is use for attendance
					/* $this->loadModel('User');
					$uid1 = $this->user['id'];
					$sale_date=$this->request->data['created'];
					$this->_updateAttendance_rdsalentry($uid1,$sale_date);  */
				
				}
			}
		}
		
		if(!empty($this->request->data['request_id'])){
			$order_id = empty($order_id)?0:$order_id;
			
			$this->loadModel('Service');
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $order_id);
		}
		//pr($this->response);
		echo json_encode($this->response);
		exit;
	}
	
	
	public function consumerdistributorSalesOrders(){
		$this->loadModel('ConsumerRedistributionOrder');
		$conditions = array();
		
		$this->ConsumerRedistributionOrder->_userSalesCondition($conditions, $this->user);
		$this->paginate['order'] = array('ConsumerRedistributionOrder.sale_date' => 'desc', 'ConsumerRedistributionOrder.created' => 'desc');
		
		$this->ConsumerRedistributionOrder->hasMany = array('sales'=>array('className' => 'ConsumerRedistributionSale', 'foreignKey' => 'consumer_redistribution_order_id', 'finderQuery' => 'SELECT sales.id, sales.brand_id, sales.user_id, sales.redistributor_id, sales.depot_id, sales.unit, sales.cal_qty, sales.unit_price, sales.quantity, sales.amount, sales.sale_date, sales.consumer_redistribution_order_id, Brand.name FROM `consumer_redistribution_sales` AS `sales` LEFT JOIN `brands` AS `Brand` ON (`sales`.`brand_id`=`Brand`.`id`) WHERE `sales`.`consumer_redistribution_order_id` IN ({$__cakeID__$})'));
		
		

		//$this->RedistributorSale->hasMany = array('sales'=>array('className' => 'RedistributorSaleitem', 'foreignKey' => 'redistributor_sale_id'));
				
		$rsales = $this->paginate('ConsumerRedistributionOrder', $conditions);
		if($rsales){
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['ConsumerRedistributionOrder']['page'] - 1) * $this->params->params['paging']['ConsumerRedistributionOrder']['limit'];	
			
			foreach ($rsales as $key => $rsale){
				$rsales[$key]['sno'] = ++$i;
			}
		
			$this->response['data'] = $rsales;
			$paging = array();
			$paging['page'] = $this->params->params['paging']['ConsumerRedistributionOrder']['page'];
			$paging['current'] = $this->params->params['paging']['ConsumerRedistributionOrder']['current'];
			$paging['count'] = $this->params->params['paging']['ConsumerRedistributionOrder']['count'];
			$paging['pageCount'] = $this->params->params['paging']['ConsumerRedistributionOrder']['pageCount'];
			
			if (!empty($this->params->params['paging']['ConsumerRedistributionOrder']['prevPage'])){
				$paging['prev'] = Router::url(array('controller'=>'salesapp', 'action'=>'consumerdistributorSalesOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['ConsumerRedistributionOrder']['page'] - 1), 'ext'=>'json'), true);
			}
			if (!empty($this->params->params['paging']['ConsumerRedistributionOrder']['nextPage'])){
				
				$paging['next'] = Router::url(array('controller'=>'salesapp', 'action'=>'consumerdistributorSalesOrders', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['RedistributorSale']['page'] + 1), 'ext'=>'json'), true);
			}
		
			$this->response['paging'] = $paging;
			
		}else{
			$this->response['message'] = __('Data not found');
			$this->response['error'] = 2;
		}
		echo json_encode($this->response);
		exit;
		
	} 
	
	public function addconsumerrdsale(){  
		$this->loadModel('ConsumerRedistributionOrder');
		$this->loadModel('Sale');
		$this->loadModel('Brand'); 
			
		
			
		/* if($this->request->data['customer_id'] == 291286){
				$this->request->data['jsonString'] = '{"token":"12564987105de0c471148582.77717470","created":"2019-11-29 12:40:11","request_id":"352423060686324::20191129124011","customer_id":"291286","customer_name":"Test Mumbai Test","redistributor_id":"96","sale_date":"2019-11-29","latitude":"19.1232337","longitude":"72.8620191","grand_total":"180.0","sales":[{"brand_id":"1","unit":"Pack","unit_price":"180.0","quantity":"1","amount":"180.0"}],"freeItem":[]}';
			
			$this->request->data = json_decode($this->request->data['jsonString'], true );  
			}  */
			
			 
			
			
		if ($this->request->data){
						
			$data = $stockStatus = array();
			
			if ( empty($this->request->data['sales']) || count($this->request->data['sales']) == 0)
			{
				$this->response['message'] = __('Something missing, Please check your sale data entry table');
				$this->response['error'] = 2;
			}
			else
			{
				
				if (!empty($this->request->data['newConsumer'])){
					$customerId = $this->_add_consumer($this->request->data['newConsumer']);
					$this->request->data['consumer_id'] = $consumerId;
				}
				
				$orderData = array('redistributor_id' => $this->request->data['redistributor_id'], 'consumer_id' => $this->request->data['consumer_id'], 'order_date'=>$this->request->data['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['sales']), 'total' => $this->request->data['grand_total'], 'via_app' => 1); 
				
				if (!empty($this->request->data['latitude'])){
					$orderData['latitude'] = $this->request->data['latitude'];
				}
				
				if (!empty($this->request->data['longitude'])){
					$orderData['longitude'] = $this->request->data['longitude'];
				}
				
				$conditions = array('ConsumerRedistributionOrder.redistributor_id' => $this->request->data['redistributor_id'], 'ConsumerRedistributionOrder.consumer_id' => $this->request->data['consumer_id'], 'ConsumerRedistributionOrder.order_date'=>$this->request->data['sale_date'], 'ConsumerRedistributionOrder.user_id'=>$this->user['id'], 'ConsumerRedistributionOrder.items'=>count($this->request->data['sales']), 'ConsumerRedistributionOrder.total' => $this->request->data['grand_total'] ); //pr(	$conditions);
				
				if (!empty($this->request->data['created'])){
					$orderData['created'] = $this->request->data['created'];
					$conditions['ConsumerRedistributionOrder.created'] = $this->request->data['created'];
				}
				
				$is_added = $this->ConsumerRedistributionOrder->find('count', array('conditions'=>$conditions)); 
				
				if ($is_added > 0 || $this->request->data['consumer_id']==0 ){	
					$this->response['message'] = __('This consumer redistribution sales entry already added');
					$this->response['error'] = SYNC_NOT_REQUIRED;
				}else{
					$this->loadModel('Consumer');
					$consumer = $this->Consumer->findById($this->request->data['consumer_id']); //pr($consumer );
					
					/* $this->response['verifiedCode'] = 0;
			
					//verify customer by RM & marketing manager & Division Manager
					//if($this->user['role_id'] == 3 || $this->user['role_id'] == 2 || $this->user['role_id'] == 13){
					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'];						
							$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;
						}
					} */
					//}  
					
					$order = $this->ConsumerRedistributionOrder->save($orderData); //pr($order); //die();
					
					/* $this->loadModel('Customer');
					$this->Customer->id = $this->request->data['customer_id'];
					$depot_id = $this->Customer->field('depot_id'); */
					
					$depot_id = $consumer['Consumer']['depot_id'];
					
					$order_id = $order['ConsumerRedistributionOrder']['id']; 
					
					//pr($this->request->data); die();
					
					foreach ($this->request->data['sales'] as $key => $sale ){ 
						
						//Check  brand model is loaded
					$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$sale['brand_id']))); //pr($group_id); die();
					
						
						$data[] = array(
							'brand_id'=> $sale['brand_id'],
							'brand_group_id' =>$group_id[$sale['brand_id']],
							'consumer_redistribution_order_id'=> $order_id,
							'redistributor_id' => $this->request->data['redistributor_id'],
							'user_id' => $this->user['id'], 
							'depot_id' => $depot_id, 
							'consumer_id' => $this->request->data['consumer_id'],
							'sale_date'=>$this->request->data['sale_date'],
							'unit'=> $sale['unit'], 
							'unit_price'=>$sale['unit_price'], 
							'quantity' =>$sale['quantity'], 
							'cal_qty' => @$this->Sale->calQty($sale['brand_id'], $sale['unit'], $sale['quantity']), 
							'amount'=>$sale['amount']
						);
					}
					//Free Data
					$this->loadModel('ConsumerRedistributionSale');
					/* $this->loadModel('RdFreeItem');
					$freeData = array();
					if (!empty($this->request->data['freeItem'])){
						
						foreach ($this->request->data['freeItem'] as $key => $freeItem ){
							//Check  brand model is loaded
					$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$freeItem['brand_id'])));
					

							$freeData[] = array(
								'redistributor_sale_id' => $order_id,
								'brand_id' => $freeItem['brand_id'],
								'brand_group_id' =>$group_id[$freeItem['brand_id']],
								'depot_id' => $depot_id, 
								'sale_date' => $this->request->data['sale_date'],
								'unit' => $freeItem['unit'],
								'quantity' => $freeItem['quantity'],
								'compaign_id' => $freeItem['compaign_id'],
								'cal_qty' => $this->Sale->calQty($freeItem['brand_id'], $freeItem['unit'], $freeItem['quantity'])
							);
						}
					} */
					
					
					if ($data){ //pr($data); die();
						@$this->ConsumerRedistributionSale->saveAll($data);
						/* if (!empty($freeData)){
							$this->RdFreeItem->saveAll($freeData);
						} */
						$this->Consumer->verify_status($this->request->data['consumer_id']);
						$this->response['message'] = __('Consumer Redistributor Sales was saved 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; 
                          //get user_id  and sale_date and it is use for attendance
				/* $this->loadModel('User');
				$uid1 = $this->user['id'];
				$sale_date=$this->request->data['created'];
				$this->_updateAttendance_rdsalentry($uid1,$sale_date);  */
				
				
			}
		}
		
		if(!empty($this->request->data['request_id'])){
			$order_id = empty($order_id)?0:$order_id;
			
			$this->loadModel('Service');
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $order_id);
		}
		//pr($this->response);
		echo json_encode($this->response);
		exit;
	}
	
	/**
	 * Consumer rdsaleview method
	 * 
	 */
	public function consumerrdsaleview(){
		$this->loadModel('ConsumerRedistributionOrder');
		$this->loadModel('ConsumerRedistributionSale');
		if(empty($this->request->data['rdsale_id'])){
			$this->response['message'] = __('Consumer Redistributor Sale id should not be empty');
			$this->response['error'] = 2;
		}else{
			$data = array();
			$id = $this->ConsumerRedistributionOrder->id = $this->request->data['rdsale_id'];
			$this->ConsumerRedistributionOrder->id = $id;
			$rdsale = $this->ConsumerRedistributionOrder->read(); 
			if ($rdsale){
				
				$data['rdsale'] = $rdsale;
				$data['sales'] = $this->ConsumerRedistributionSale->find('all', array('conditions'=>array('consumer_redistribution_order_id'=>$id)));
				
				
				/* $joins1 = array(array('table'=>'brands', 'alias' => 'Brand', 'type'=>'left', 'conditions' => 'Brand.id = ConsumerRedistributionSale.brand_id')); 
				
				$sales = $this->ConsumerRedistributionSale->find('all', array('conditions' => array('consumer_redistribution_order_id'=>$id),'fields'=>array('ConsumerRedistributionSale.*', 'Brand.name'), 'joins'=>$joins1  )); 
				 $this->loadModel('RdFreeItem');
				$joins = array(array('table'=>'brands', 'alias' => 'Brand', 'type'=>'inner', 'conditions' => 'Brand.id = RdFreeItem.brand_id'));
				$freeItems = $this->RdFreeItem->find('all', array('fields'=>array('RdFreeItem.*', 'Brand.name'), 'conditions'=>array('redistributor_sale_id' => $id), 'joins'=>$joins)); */
				$this->response['error'] = 0;
				//$data = compact('rdsale', 'sales', 'freeItems');
				
				$this->response['data'] = $data;
				
			}else{
				$this->response['message'] = __('Redistributor Sale data not found');
				$this->response['error'] = 2;
			}
		}
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
	
	public function consumerrdsaledelete(){
		if(empty($this->request->data['rdsale_id'])){
			$this->response['message'] = __('Consuemr Redistributor Sale id should not be empty');
		}else{
			$this->loadModel('ConsumerRedistributionOrder');
			$this->ConsumerRedistributionOrder->id = $this->request->data['rdsale_id'];
			if (!$this->ConsumerRedistributionOrder->exists()) {
				$this->response['message'] = __('Invalid Consumer Redistributor Sale');
				$this->response['error'] = 2;
			}
			
			if ($this->ConsumerRedistributionOrder->delete()) {
				$this->response['error'] = 0;
				$this->response['message'] = __('Consumer Redistributor Sale was deleted successfully');
			}else{
				$this->response['message'] = __('Consumer Redistributor Sale was not deleted');
				$this->response['error'] = 2;
			}
		}
		echo json_encode($this->response);
		exit;
	}
	
	
	/*This function use for HRMS attendance update from apps*/
	
	/* function _updateAttendance_rdsalentry($id,$sdate){
		$this->loadModel('User');
		$eid = $this->User->find('first', array('fields'=> array('employee_id'), 'conditions'=>array('User.id' => $id)));
		$emp_id = $eid['User']['employee_id'];
		//pr($eid); die();
		$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($sdate));
		$data = array(); 
		$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date))); //pr($attendance); //die();
		if(empty($attendance) ){
			if($attendance['Attendance']['in_time'] == ''){
				$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $sdate, 'in_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
			}
			$this->Attendance->save($data);
		}
		else{

			$this->_updateAttendance_rdsalexit($emp_id,$sdate);
		}
		 
	}
	function _updateAttendance_rdsalexit($emp_id,$sdate){
		$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($sdate));
		$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'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
				}else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'], 'out_time' => date('H:i:s',strtotime($sdate)), 'punch_time' => $sdate);
				}
				$this->Attendance->save($data);
			}
	} */
	/*
	 * Action : incentives 
	 * 
	 */
	public function incentives(){
		$conditions = array();
		$this->loadModel('Incentive');		
		
		// To fetch current month data only
		$conditions['Incentive.incentive_date >= '] = date('Y-m-01'); 
		
		$this->Incentive->_incentiveConditions($conditions, $this->user);
		$this->paginate['order'] = array('Incentive.created'=>'desc', 'Incentive.incentive_date'=>'desc');
		$incentives = $this->paginate('Incentive', $conditions);
		
		if($incentives){
			$this->response['error'] = 0;
			$i = ($this->params->params['paging']['Incentive']['page'] - 1) * $this->params->params['paging']['Incentive']['limit'];	
			
			foreach ($incentives as $key => $incentive){
				$incentives[$key]['sno'] = ++$i;
			}
			$this->response['data'] = $incentives;
		}else{
			$this->response['message'] = __('Data not found');
			$this->response['error'] = 2;
		}
		$paging = array();
		$paging['page'] = $this->params->params['paging']['Incentive']['page'];
		$paging['current'] = $this->params->params['paging']['Incentive']['current'];
		$paging['count'] = $this->params->params['paging']['Incentive']['count'];
		$paging['pageCount'] = $this->params->params['paging']['Incentive']['pageCount'];
		
		if (!empty($this->params->params['paging']['Incentive']['prevPage'])){
			$paging['prev'] = Router::url(array('controller'=>'salesapp', 'action'=>'incentives', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Incentive']['page'] - 1), 'ext'=>'json'), true);
		}
		if (!empty($this->params->params['paging']['Incentive']['nextPage'])){
			
			$paging['next'] = Router::url(array('controller'=>'salesapp', 'action'=>'incentives', '?'=>array('token'=>$this->token, 'page'=>$this->params->params['paging']['Incentive']['page'] + 1), 'ext'=>'json'), true);
		}
	
		$this->response['paging'] = $paging;
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;		
	}
	
	/**
     * deleteCustomerVisit method
     *
     * @param string $id
     * @return void
     */
    public function deleteIncentive() {
		$this->loadModel('Incentive');
        if (!$this->request->is('post')) {
            $this->response['message'] = __('Invalid request');
        }
		$incentive = array();
		if(empty($this->request->data['incentive_id'])){
			$this->response['message'] = __('Incentive id should not be empty');
		}else{
			$id = $this->Incentive->id = $this->request->data['incentive_id'];
			$incentive = $this->Incentive->read();
		}
       if (!$incentive) {
             $this->response['message'] =  __('Invalid Incentive');
        }
		
        if ($this->Incentive->delete()) {
			
			/**** Audit START ****/
				$this->loadModel('Audit');
				$this->Audit->saveDeletedData($incentive['Incentive']['id'], 'Incentive', $this->user['id'] , serialize($incentive),'Incentive Has been Deleted',STATUS_DELETE);
			/**** Audit END ****/
			
			$this->response['message'] = __('Incentive was deleted successfully');
			$this->response['error'] = 0;
        }else{
			$this->response['message'] = __('Incentive was not deleted');
			$this->response['error'] = 2;
		}
		echo json_encode($this->response);
		exit;
    }
	/**
     * updatevisit method
     *
     * @param string $id
     * @return void
     */
	function updateIncentive(){
		if ($this->request->data){
			$this->loadModel('Incentive');
			$this->loadModel('Sale');
			if (!empty($this->request->data['jsonString'])){
				$this->request->data = json_decode($this->request->data['jsonString'], true );
			}
			

			$is_added =0;
			
			if (!empty($this->request->data['newCustomer'])){
				$customerId = $this->_add_customer($this->request->data['newCustomer']);
				$this->request->data['customer_id'] = $customerId;
			}
			
			if(!empty($this->request->data['customer_id'])){
												
				$this->request->data['cal_qty'] = @$this->Sale->calQty($this->request->data['brand_id'], $this->request->data['unit'], $this->request->data['quantity']);				
				
				if(!empty($this->request->data['incentive_id'])){
					$this->request->data['id'] = $this->request->data['incentive_id'];
					//unset($this->request->data['user_id']);
					$this->request->data['app_modified'] = 1;
					
					$this->Incentive->id = $this->request->data['id'];
					$AuditData = $this->Incentive->read();
				}else{
					$this->request->data['user_id'] = $this->user['id'];
					$this->request->data['via_app'] = 1;
					
					$conditions = array('Incentive.customer_id' => $this->request->data['customer_id'], 'Incentive.user_id'=>$this->user['id'], 'Incentive.incentive_date' => $this->request->data['incentive_date'], 'Incentive.incentive_type' => $this->request->data['incentive_type'], 'Incentive.cal_qty' => $this->request->data['cal_qty'] );
					
					
					
					if(!empty($this->request->data['created'])){
						$conditions['Incentive.created'] = $this->request->data['created'];
					}else{
						//created should not be empty in Add entry
						$this->response['error'] = SYNC_NOT_REQUIRED;
						$this->response['message'] = __('Created date is required for adding an entry.');
						echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
						exit;
					}
				
					//Check already added			
					$is_added = $this->Incentive->find('count', array('conditions'=>$conditions));
				
				}
				
				
				if ($is_added > 0 && empty($this->request->data['id'])){	
					$this->response['message'] = __('This incentive entry already added');
					$this->response['error'] = SYNC_NOT_REQUIRED;
				}else{
						$this->loadModel('Customer');
						
						$customer = $this->Customer->findById($this->request->data['customer_id']);
						
						if(!empty($customer)){
							//ONLY FOR ADD		
							if(empty($this->request->data['incentive_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'] = $this->request->data['incentive_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;
										}
									}
									//} 
									
									$depot_id = $customer['Customer']['depot_id'];
							
									if(empty($depot_id)){
										$depot_id = $this->user['depot_id'];
									}
									$this->request->data['depot_id'] = $depot_id;
							}
							
							/* $this->Customer->id = $this->request->data['customer_id'];
							$depot_id = $this->Customer->field('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']]; 
								
								$brand_id = $this->request->data['brand_id'];
								$unit =  $this->request->data['unit'];
							
								$unit_price = $this->Brand->getUnitPrice('sale', $brand_id, $unit);	
								$amount = $this->request->data['quantity'] * $unit_price;	
								
								$this->request->data['unit_price'] = $unit_price;
								$this->request->data['amount'] = $amount;
							}
							
							
							
							$incentive = $this->Incentive->save($this->request->data);
							$incentive_id = $incentive['Incentive']['id'];
							
							//ONLY FOR ADD		
							if(empty($this->request->data['incentive_id'])){
								/*****----- Check if entry is on correct route -----*****/
								$uid = $incentive['Incentive']['user_id']; 
								$date = date('Y-m-d', strtotime($incentive['Incentive']['incentive_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->Incentive->id = $incentive_id;
										$this->Incentive->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 - Incentive entry on a day other than the user's day routes.");
											$email->viewVars(array('model' => 'Incentive', 'data' => $incentive, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
											$email->template('entry_on_different_route');
											$email->send('entry_on_different_route'); 
										/**** ----------------------------------------------------- ****/
									}
								}
								/*****------------------------------------*****/
							}else{
								//Edit entry
								
								/**** Audit START ****/
									if(!empty($AuditData)){
										$this->loadModel('Audit');
										$this->Audit->saveDeletedData($AuditData['Incentive']['id'], 'Incentive', $this->user['id'] , serialize($AuditData),'Incentive Has been updated',STATUS_EDIT);
									}
								/**** Audit END ****/
							}

							
							$this->response['message'] = __('Last Record was save successfully');
							$this->response['error'] = 0;
					}else{
						$this->response['message'] = __('Unable to save. Customer no longer exists in the system.');
							$this->response['error'] = SYNC_NOT_REQUIRED;
					}		
				}
				
				
			}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']) ){
			$incentive_id = empty($incentive_id)?0:$incentive_id;
			$this->Service->saveRequestLogs($this->request->data['request_id'], $this->response, $this->request->url, $this->response['error'], $this->user['id'], $incentive_id);
		}
		
		echo json_encode($this->response, JSON_ERROR_CTRL_CHAR);
		exit;
	}
	
/**
 * getVisit method
 * 
 * @param: post params
 * @return void
 */
	function getIncentive(){
		if(empty($this->request->data['incentive_id'])){
			$this->response['message'] = __('Incentive id should not be empty');
		}else{		
			$this->loadModel('Incentive');
			$this->Incentive->id = $this->request->data['incentive_id'];
			$incentive = $this->Incentive->read();
			
			if ($incentive){
				$this->response['data'] = $incentive;
				$this->response['error'] = 0;
			}else{
				$this->response['message'] = __('Invalid Incentive');
			}
		}
		echo json_encode($this->response);
		exit;
	}
	
	
	function _add_customer($data){
		$this->loadModel('Customer');
		
		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 ($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;
		}
	}
	
	
	function _add_consumer($data){
		$this->loadModel('Consumer');
		
		if ($data){
			
			$is_exists = 0;
			if (!empty($data['phone']) ){
				$data['phone'] = trim($data['phone']);
				$conditions = array('Consumer.phone'=>$data['phone']);	
				if (!empty($data['email'])){
					$conditions['LOWER(Consumer.email)'] = strtolower($data['email']);
				}
				$conditions['Consumer.status'] = ACTIVE;
				$consumer = $this->Consumer->find('first', array('conditions'=>$conditions));
				
			}
			
			
			if ($consumer){
				$consumer_id = $consumer['Consumer']['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'];
				$consumer = $this->Consumer->save($data);
				
				if (!empty($data['id'])){
					$consumer_id = $data['id'];
				}else{
					$consumer_id = $consumer['Consumer']['id'];
				}
				if (!empty( $data['assignToOption'])){
					$userIds = $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'=>$data['user_id']));
					}
					@$this->ConsumerAssign->saveAll($assignData);
				}
				$consumer_id = $consumer['Consumer']['id'];				
				
			}
			return $consumer_id;
		}
	}
		
}