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

/**
 * Controller name
 *
 * @var string
 */var $components = array('Option');
	public function index(){
		$this->reports();
	}
	public function reports(){
		
		$conditions = array();
		
		if (!empty($this->request->query['q'])){
			$conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
            if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                $conditions[] = 'Sale.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
            }
            if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
                $conditions[] = 'Sale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
            if (!empty($this->request->query['dp'])){
                $conditions['Sale.depot_id'] = $this->request->query['dp'];
            }

        }
		if ( !empty($this->request->query['brd'])){
			$conditions['Sale.brand_id'] = $this->request->query['brd'];
		}
		if ( !empty($this->request->query['unt'])){
			$conditions['Sale.unit'] = $this->request->query['unt'];
		}
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Sale.sale_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));
			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Sale.sale_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Sale.sale_date <= '] = $this->request->query['to'];
		}
		if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
			$conditions['Sale.status'] = $this->request->query['sts'];
		}
		//$order = $this->paginate['order'] = array('Sale.sale_date' => 'desc');
		$order = $this->paginate['order'] = array('Sale.id' => 'desc');
		$this->_salesRoleConditions($conditions);

		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		if(isset($this->request->query['export'])){
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();			
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}
				
			$sales = $this->Sale->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		}else{
			$sales = $this->paginate('Sale', $conditions);
		}
		$this->set('sales', $sales);
		
		$this->loadModel('Division');
        $this->loadModel('Region');
		$this->loadModel('Depot');
		$this->loadModel('Brand');
		
		$divisions = $this->Division->getList();
        $division_id = !empty($this->request->query['dv']) ? $this->request->query['dv'] : '0';
        $regions = $this->Region->getList($division_id);
        $region_id = !empty($this->request->query['rg']) ? $this->request->query['rg'] : '0';
		$depots = $this->Depot->getList($region_id);
		$brands = $this->Brand->find('list', array('fields'=>array('id','name')));
		$this->set(compact('offset','divisions','regions','depots', 'brands'));

		if(isset($this->request->query['export'])){
			$this->set('filename', 'Sales');
			$this->render('export_sales','export_xls');
		} else {
			$this->render('index');
		}
	}
	public function add(){
		
		if ($this->request->data){
			$this->loadModel('Brand');
			$data = $stockStatus = array();
			$this->loadModel('Order');
			//$this->_updateAttendance_salentry();
			if(empty($this->request->data['Sale']['sale_date'])){
				$this->request->data['Sale']['sale_date'] = date('Y-m-d H:i:s');
			}
			$totalBrands = count( $this->request->data['brand_id'] );
			if( ($totalBrands != count(array_filter($this->request->data['unit']))) || empty($this->request->data['unit_price']) || ($totalBrands != count(array_filter($this->request->data['unit_price']))) || ($totalBrands != count(array_filter($this->request->data['qty']))) )
			{
				$this->Session->setFlash(__('Something missing, Please check your sale data entry table'));
			}
			else
			{
				$orderData = array('customer_id' => $this->request->data['Sale']['customer_id'],'order_date'=>$this->request->data['Sale']['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $this->request->data['grand_total'] );
				$order = $this->Order->save($orderData);
				
				$uid1 = $this->user['id'];
				$order_date=$order['Order']['created'];
				$this->_updateAttendance_salentry($uid1,$order_date);
				
				$this->loadModel('Customer');
				$this->Customer->id = $this->request->data['Sale']['customer_id'];
				$depot_id = $this->Customer->field('depot_id');
				$this->Customer->verify_status($this->request->data['Sale']['customer_id']);
				$order_id = $order['Order']['id'];
				
				
				foreach ($this->request->data['brand_id'] as $key => $val ){
					$stockStatus[$val]['entity_id'] = $depot_id;
					$stockStatus[$val]['entity'] = 'Depot';
					
					//Check  brand model is loaded
					$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
					
					$data[] = array(
						'brand_id'=> $val,
						'brand_group_id' =>$group_id[$val],
						'order_id'=> $order_id,
						'user_id'=>$this->user['id'], 
						'depot_id'=>$depot_id, 
						'customer_id'=>$this->request->data['Sale']['customer_id'],
						'sale_date'=>$this->request->data['Sale']['sale_date'],
						'unit'=>$this->request->data['unit'][$key], 
						'unit_price'=>$this->request->data['unit_price'][$key], 
						'quantity' =>$this->request->data['qty'][$key], 
						'cal_qty' => $this->Sale->calQty($val, $this->request->data['unit'][$key], $this->request->data['qty'][$key]), 
						'amount'=>$this->request->data['amount'][$key]
					);
					$unit = strtolower($this->request->data['unit'][$key]);
					@$stockStatus[$val][$unit] += $this->request->data['qty'][$key];
				}
				//Free Data
				$this->loadModel('FreeItem');
				$freeData = array();
				if (!empty($this->request->data['freeItem'])){
					
					foreach ($this->request->data['freeItem']['brand_id'] as $key => $val ){
						$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
						
						$freeData[] = array(
							'order_id' => $order_id,
							'brand_id' => $val,
							'brand_group_id' =>$group_id[$val],
							'depot_id'=>$depot_id, 
							'sale_date' => $this->request->data['Sale']['sale_date'],
							'unit' => $this->request->data['freeItem']['unit'][$key],
							'quantity' => $this->request->data['freeItem']['quantity'][$key],
							'compaign_id' => $this->request->data['freeItem']['compaign_id'][$key],
							'cal_qty' => $this->Sale->calQty($val, $this->request->data['freeItem']['unit'][$key], $this->request->data['freeItem']['quantity'][$key])
						);
						$unit = strtolower($this->request->data['freeItem']['unit'][$key]);
						@$stockStatus[$val][$unit] += $this->request->data['quantity'][$key];
					}
				}
				if ($data){
					$this->Sale->saveAll($data);
					if ($freeData){
						$this->FreeItem->saveAll($freeData);
					}
				
					$this->Sale->updateStockStatus($stockStatus);
					$this->Session->setFlash(__('Sales was saved successfully'));
					$this->redirect(array('action'=>'saleOrders'));
					
				}
			}
		}
		
		$Opdata = isset($this->request->data['User'] ) ? $this->request->data['User']  : array();  
		$this->Option->Options($Opdata, $this->user);
		
		$this->_options();
		
	}
	
	public function edit($id){
		$this->Sale->id = $id;
        if (!$this->Sale->exists()) {
            throw new NotFoundException(__('Invalid Sale'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
			$data = array();
			$this->loadModel('Brand');
			
			foreach ($this->request->data['brand_id'] as $key => $val ){
				//Check  brand model is loaded
					$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
					
				$data[] = array(
					'id'=>$this->request->data['Sale']['id'],
					'brand_id'=> $val,
					'brand_group_id' =>$group_id[$val],
					'user_id'=>$this->user['id'], 
					'depot_id'=>$this->user['depot_id'], 
					'customer_id'=>$this->request->data['Sale']['customer_id'],
					'sale_date'=>$this->request->data['Sale']['sale_date'],
					'unit'=>$this->request->data['unit'][$key], 
					'unit_price'=>$this->request->data['unit_price'][$key], 
					'quantity' =>$this->request->data['qty'][$key], 
					'cal_qty' => $this->Sale->calQty($val, $this->request->data['unit'][$key], $this->request->data['qty'][$key]),
					'amount'=>$this->request->data['amount'][$key]
				);
			}
			
			if ($data){
				$this->Sale->saveAll($data);
				$this->Session->setFlash(__('Sales was updated successfully'));
				$this->redirect(array('action'=>'index'));
			}
		}else {
            $this->request->data = $this->Sale->read(null, $id);
			$this->_options();
        }
	}
	function _options(){
		$this->loadModel('Customer');
		$this->loadModel('Brand');
		$customers = $this->Customer->customerListByRole($this->user);
		
		$brands = $this->Brand->find('all', array('conditions'=>array('status'=>ACTIVE)));
		$brandList = array();
		$brandsObj = array();
		foreach ($brands as $brand ){
			$brandList[$brand['Brand']['id']] = $brand['Brand']['name'];
			$brankdsObj['b'.$brand['Brand']['id'].'b'] = array('Case' => $brand['Brand']['case_price'], 'Roll' => $brand['Brand']['roll_price'],'Pack' => $brand['Brand']['pack_price'], '2Pack' => $brand['Brand']['2pack_price']);
		}
		//Get All active compaign
		$this->loadModel('Compaign');
		$compaigns = $this->Compaign->find('all', array('conditions'=>array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date")));
		$compaignArray = array();
		if($compaigns){
		
			foreach($compaigns as $compaign){
				$cId = $compaign['Compaign']['id'];
				$compaignArray[$cId] = $compaign['Compaign'];
			}
		}
		
		$this->set( compact('customers','brands', 'brandList','brankdsObj','compaignArray'));
	}
	public function delete($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Sale->id = $id;
        if (!$this->Sale->exists()) {
            throw new NotFoundException(__('Invalid Sale'));
        }
		
        if ($this->Sale->delete()) {
		
            $this->Session->setFlash(__('Sale was deleted successfully'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Sale was not deleted'));
        $this->redirect(array('action' => 'index'));
	}
	/**
	 * saleOrders method
	 *
	 */
	public function saleOrders(){ 
	    $this->loadModel('Order');
		
		/* $this->loadModel('Sale');
		$this->Sale->unbindModel(
        array('belongsTo' => array('User', 'Brand','Depot','Customer'))
    );
		$sl = $this->Sale->find('all'); pr($sl); */
		
		$conditions = array();
		
		if (!empty($this->request->query['q'])){
			$conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Order.order_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));
			
		} elseif (!empty($this->request->query['from'])){
			$conditions['Order.order_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Order.order_date <= '] = $this->request->query['to'];
		}
		if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
	$conditions[] = array('Order.modified BETWEEN ? AND ?' => array($this->request->query['mfrom'], $this->request->query['mto']));
} 
		$joins =  array();
		if (!empty($this->request->query['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
			$order=$this->paginate['group'] = array('Order.id');
			$this->paginate['joins'] = array(array('table'=>'sales', 'alias'=>'Sale', 'conditions'=>'Order.id=Sale.order_id'));
			if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                $conditions[] = 'Sale.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
            }
			if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
				$conditions[] = 'Sale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
			} 
			if (!empty($this->request->query['dp'])){
				$conditions['Sale.depot_id'] = $this->request->query['dp'];
			}
		}
		if (isset($this->request->query['sts']) && $this->request->query['sts']!='' ){
			$conditions['Order.status'] = $this->request->query['sts'];
		}	
		
		if (isset($this->request->query['r']) && $this->request->query['r']!='' ){
			$conditions['User.role_id'] = $this->request->query['r'];
		}
		
		//$this->Sale->_userCondition($conditions, $this->user);
		$this->Sale->_userRoleCondition($conditions, $this->user, $this->paginate);
		$sorder=$this->paginate['order'] = array('Order.created' => 'desc', 'Order.order_date' => 'desc');
		//$order=$this->paginate['order'] = array('Order.id' => 'desc');
		$joins = isset($this->paginate['joins'])?$this->paginate['joins']:array(); 
		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		
		$totalAmount = $this->Order->find('all', array('fields'=>array('SUM(Order.total) AS totalAmount'), 'conditions'=>$conditions,'joins'=>$joins));
		
		if(isset($this->request->query['export'])){
			$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();			
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}
			$exporders = $this->Order->find('all', array('conditions'=>$conditions, 'order'=>$sorder,'joins'=>$joins, 'limit'=>'10000', 'offset'=>$offset ));		
			//$exporders = $this->Order->find('all',array('conditions'=>$conditions,'order'=>$sorder,'joins'=>$joins,'limit' => 1000));	
		} else {
			$orders = $this->paginate('Order', $conditions);
		} //pr($orders);
		
		
		$this->loadModel('Division');
		$this->loadModel('Depot');
		$this->loadModel('Region');
		$divisions = $this->Division->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		$regions = $this->Region->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		$region_id = !empty($this->user['region_id'])?$this->user['region_id']:0;
		$depots = $this->Depot->getList($region_id);
		
		$this->loadModel('Role');
		$this->user = $this->Auth->user();
		$roles = $this->Role->getList($this->user);  //pr($roles); 
		
		$this->set(compact('depots','divisions','regions','exporders','orders','totalAmount','offset','roles'));
        if(isset($this->request->query['export'])){   
			$this->set('filename', 'Sales');
			$this->render('export_saleorder','export_xls');
		}
	/*	$this->loadModel('Order');
		
		$conditions = array();
		
		if (!empty($this->request->query['q'])){
			$conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['usr']) ){
			$conditions['Order.user_id'] = $this->request->query['usr'];
		}
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Order.order_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));
			
		} elseif (!empty($this->request->query['from'])){
			$conditions['Order.order_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Order.order_date <= '] = $this->request->query['to'];
		}
		if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
			$conditions[] = array('Order.modified BETWEEN ? AND ?' => array($this->request->query['mfrom'], $this->request->query['mto']));
		} 
		$joins =  array();
		if (!empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
			$order=$this->paginate['group'] = array('Order.id');
			$this->paginate['joins'] = array(array('table'=>'sales', 'alias'=>'Sale', 'conditions'=>'Order.id=Sale.order_id'));	
			if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
				$conditions[] = 'Sale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
			} 
			if (!empty($this->request->query['dp'])){
				$conditions['Sale.depot_id'] = $this->request->query['dp'];
			}
		}
		if (isset($this->request->query['sts']) && $this->request->query['sts']!='' ){
			$conditions['Order.status'] = $this->request->query['sts'];
		}			
		//$this->Sale->_userCondition($conditions, $this->user);
		$this->Sale->_userRoleCondition($conditions, $this->user, $this->paginate);
		$sorder=$this->paginate['order'] = array('Order.created' => 'desc', 'Order.order_date' => 'desc');
		$order=$this->paginate['order'] = array('Order.id' => 'desc');
		$querystring = $this->request->query;
		$this->set(compact('querystring'));
	
	if(isset($this->request->query['export'])){ 
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();			
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}
			$exporders = $this->Order->find('all',array('conditions'=>$conditions,'order'=>$sorder,'joins'=>$joins, 'limit'=>10000, 'offset'=>$offset));				
		} else {
			$orders = $this->paginate('Order', $conditions);
		}
		
		$this->loadModel('Depot');
		$this->loadModel('Region');
		$regions = $this->Region->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		$depots = $this->Depot->getList();
		
		$this->set(compact('depots','regions','exporders','orders','offset'));
        if(isset($this->request->query['export'])){ 
			$this->set('filename', 'Sales');
			$this->render('export_saleorder','export_xls');
		}*/
		
	}
	

	/**
	 * saleOrders method
	 * 
	 */
	public function orderview($id){
		$this->loadModel('Order');
		$this->Order->id = $id;
		$this->Order->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
		
		$order = $this->Order->read(); 
		
		if (!$order) {
            throw new NotFoundException(__('Invalid Sale'));
        }
		$sales = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
		$this->loadModel('FreeItem');
		$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = FreeItem.brand_id'));
		$freeItems = $this->FreeItem->find('all', array('fields'=>array('FreeItem.*', 'Brand.name'), 'conditions'=>array('order_id'=>$id), 'joins'=>$joins));
		$this->set(compact('order', 'sales', 'freeItems'));
	}
	/**
	 * orderdelete action
	 */
	 public function orderdelete($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('Order');
		$this->loadModel('Audit');
        $this->Order->id = $id;
		$orderData = $this->Order->read();
        $this->Order->unBindModelAll();
		$order = $this->Order->read();
        if (!$order) {
            throw new NotFoundException(__('Invalid Order'));
        }
		//$this->loadModel('Customer');
		//$this->Customer->id = $order['Order']['customer_id'];
		//$depot_id = $this->Customer->field('depot_id');
		//$sales = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
		
		$saleData = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
		$this->Sale->unBindModelAll();
		$data = array();
		$sales['Sale'] = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
		$data['Sale'] = serialize($sales);
		//$this->loadModel('FreeItem');
		//$stockStatus = array();
		
	
		if ($this->Order->delete()){
			//if ($stockStatus){
			//	$this->Sale->updateStockStatus($stockStatus);
			//}
			
			
			$this->loadModel('FreeItem');
			$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = FreeItem.brand_id'));
			$freeItems = $this->FreeItem->find('all', array('fields'=>array('FreeItem.*', 'Brand.name'), 'conditions'=>array('order_id'=>$id), 'joins'=>$joins)); 
			
			/** EMAIL when DELETE Sale **/
				
				$email = new CakeEmail('smtp');				
				$email->from(array('support@drupway.com'=> 'Y3 Support'));
				$email->to(array('drupwaycrm@gmail.com'));
				$email->emailFormat('html');
				$email->subject('Y3 - Sale Delete for Customer Id - '. $order['Order']['customer_id']);
				$email->viewVars(array('order' => $orderData, 'sales'=> $saleData, 'freeItems'=> $freeItems, 'deletedby'=>$this->Auth->user('username')));
				$email->template('sale_delete');
				$email->send('sale_delete'); 
				

			/**** ----------------------------------------------------- ****/	
			
			
			
			$this->Audit->saveDeletedData($order['Order']['id'], 'Order', $this->Auth->user('id') , serialize($order),'Order Has been Deleted',STATUS_DELETE , $data['Sale']);
			$this->loadModel('Customer');
			$this->Customer->verify_status($order['Order']['customer_id']);
			$this->Session->setFlash(__('Sale order was deleted'));
			$this->redirect(array('action' => 'saleOrders'));
		}
	}
	
	public function deleteAllOrders(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		$this->loadModel('Order');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Order->deleteAll(array('Order.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected sales was deleted successfully') );
			$this->redirect(array('action'=>'saleOrders'));
		}
		exit;
	}
	/*
	 * Action : incentives 
	 * 
	 */
	public function incentives(){
		$conditions = array();
		$this->loadModel('Incentive');
		
		if (!empty($this->request->query['br']) ){
			$conditions['Incentive.brand_id'] = $this->request->query['br'];
		}
		if (!empty($this->request->query['ct']) ){
			$conditions['Incentive.customer_id'] = $this->request->query['ct'];
		}
		if (!empty($this->request->query['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
            if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                $conditions[] = 'Incentive.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
            }
            if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
                $conditions[] = 'Incentive.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
            if (!empty($this->request->query['dp'])){
                $conditions['Incentive.depot_id'] = $this->request->query['dp'];
            }

        }
		
		if (!empty($this->request->query['it']) ){
			$conditions['Incentive.incentive_type'] = $this->request->query['it'];
		} 
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){

			$conditions[] = array('Incentive.incentive_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			

		}elseif (!empty($this->request->query['from'])){

			$conditions['Incentive.incentive_date >= '] = $this->request->query['from'];

		} elseif (!empty($this->request->query['to'])){

			$conditions['Incentive.incentive_date <= '] = $this->request->query['to'];

		}
		
		if (isset($this->request->query['sts']) && $this->request->query['sts']!=''){
			$conditions['Incentive.status'] = $this->request->query['sts'];
		}
		
		if (isset($this->request->query['r']) && $this->request->query['r']!=''){
			$conditions['User.role_id'] = $this->request->query['r'];
		}
		$this->Incentive->_incentiveConditions($conditions, $this->user);
		$order=$this->paginate['order'] = array('Incentive.created'=>'desc','Incentive.incentive_date'=>'desc');

		$querystring = $this->request->query;	
		$this->set(compact('querystring'));
		if(isset($this->request->query['export'])){  
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}
				
			$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();		
			$incentives = $this->Incentive->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		} else {
		    $incentives = $this->paginate('Incentive', $conditions);
		}
		$this->set('incentives', $incentives);
		
		$this->loadModel('Role');
		$this->user = $this->Auth->user();
		$roles = $this->Role->getList($this->user);  //pr($roles); 
		
		$this->set(compact('offset', 'roles'));
		$this->_incentiveOptions();
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'Incentive');
			$this->render('export_incentive','export_xls');
		}
	}
	
	/*
	 * Action : incentives 
	 * 
	 */
	public function add_incentives(){
		$this->loadModel('Incentive');
		
		if ($this->request->data){
		//pr($this->request->data);
		//die();
			$this->request->data['Incentive']['user_id'] = $this->user['id'];
			$this->request->data['Incentive']['cal_qty'] = $this->Sale->calQty($this->request->data['Incentive']['brand_id'], $this->request->data['Incentive']['unit'], $this->request->data['Incentive']['quantity']);
			
			//Get customer's depot_id
			$this->loadModel('Customer');
			$this->Customer->id = $this->request->data['Incentive']['customer_id'];
			$this->request->data['Incentive']['depot_id'] = $this->Customer->field('depot_id');
			
			if (!empty($this->request->data['Incentive']['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['Incentive']['brand_id']))); 
				$this->request->data['Incentive']['brand_group_id'] = $group_id[$this->request->data['Incentive']['brand_id']]; 
			}
			
			$this->Incentive->save($this->request->data);
			$this->Session->setFlash(__('Incentive added succesfully'));
			
			if (isset($this->request->data['addmore'])){
				$this->redirect(array('action'=>'add_incentives'));
			}else{
				$this->redirect(array('action'=>'incentives'));
			}
		}
		
		$this->_incentiveOptions();
		$this->set('title', __('Add Incentive'));
		$this->render('update_insentives');
	}
	/*
	 * Action : update_incentives 
	 * 
	 */
	public function updateIncentive($id){ 
		$this->loadModel('Audit');
		$this->roleBasePermission(array(SUPPORT));
		$this->loadModel('Incentive');
        $this->Incentive->id = $id;
		$userData = $this->Incentive->read(null, $id);
		$insentive = $this->Incentive->read();
        if (!$insentive) {
            throw new NotFoundException(__('Invalid incentive'));
        }else if ($this->request->data){
			//$this->request->data['Incentive']['user_id'] = $this->user['id'];
			$this->request->data['Incentive']['cal_qty'] = $this->Sale->calQty($this->request->data['Incentive']['brand_id'], $this->request->data['Incentive']['unit'], $this->request->data['Incentive']['quantity']);
			
			if (!empty($this->request->data['Incentive']['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['Incentive']['brand_id']))); 
				$this->request->data['Incentive']['brand_group_id'] = $group_id[$this->request->data['Incentive']['brand_id']]; 
			}
			
			$this->Incentive->save($this->request->data);
			$this->Audit->saveDeletedData($userData['Incentive']['id'], 'Incentive', $this->Auth->user('id') , serialize($userData),'Incentive Has been updated', STATUS_EDIT);
			$this->Session->setFlash(__('Incentive updated succesfully'));
			//$this->Sale->updateInsentiveStock($this->request->data);
			
			if (isset($this->request->data['addmore'])){
				$this->redirect(array('action'=>'add_incentives'));
			}else{
				$this->redirect(array('action'=>'incentives'));
			}
		}else{
			$this->request->data = $insentive;
		}
		
		$this->_incentiveOptions();
		$this->set('title', __('Update Incentive'));
		$this->render('update_insentives');
	}
	public function deleteIncentive($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('Incentive');
		$this->Incentive->id = $id;
        if (!$this->Incentive->exists()) {
            throw new NotFoundException(__('Invalid incentive'));
        }
		$incentive = $this->Incentive->read();

		$data = array();
		$data['serialize'] = serialize($incentive);
		$data['model_id'] = $incentive['Incentive']['id'];
        if ($this->Incentive->delete()) {
			$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Incentive', $this->Auth->user('id') , $data['serialize'],'Incentive Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Incentive was deleted successfully'));
            $this->redirect(array('action' => 'incentives'));
        }
        $this->Session->setFlash(__('Incentive was not deleted'));
        $this->redirect(array('action' => 'incentives'));
	}
	
	public function deleteAllIncentives(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('Incentive');
		
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Incentive->deleteAll(array('Incentive.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected incentives was deleted successfully') );
			$this->redirect(array('action'=>'incentives'));
		}
		exit;
		
	}
	public function viewIncentive($id=0){
		$conditions = array();
		$this->loadModel('Incentive');
		$this->Incentive->id = $id;
		$this->Incentive->belongsTo['Depot'] = array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('title'), 'type'=>'left');
		$this->Incentive->belongsTo['Brand'] = array('className' => 'Brand', 'foreignKey' => 'brand_id', 'fields' => array('name'), 'type'=>'left');
		$this->Incentive->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
		$incentive = $this->Incentive->read();
		if (!$incentive){
			throw new NotFoundException(__('Invalid incentive'));
		}
		
		$this->set('incentive', $incentive);
	}
	public function _incentiveOptions(){
		$this->loadModel('Customer');
		$this->loadModel('Brand');
		//$this->loadModel('Depot');
		
		$customers = $this->Customer->customerListByRole($this->user);
		//$depots = $this->Depot->getList();
		$Opdata = isset($this->request->data['User'] ) ? $this->request->data['User']  : array(); 
		$this->Option->Options($Opdata, $this->user);
		$brands = $this->Brand->find('all');
		$brandList = array();
		$brandsObj = array();
		
		foreach ($brands as $brand ){
			$brandList[$brand['Brand']['id']] = $brand['Brand']['name'];
			$brankdsObj['b'.$brand['Brand']['id'].'b'] = array('Case' => $brand['Brand']['case_price'], 'Roll' => $brand['Brand']['roll_price'],'Pack' => $brand['Brand']['pack_price']);
		}
		
		$expence_types = incentive_type(); 	
		$this->set( compact('customers','brands', 'brandList','expence_types', 'depots') );
	}
	
	
	function _salesRoleConditions(&$conditions){
		switch($this->user['Role']['grade']){
			case 3:
				$conditions[] = 'Sale.user_id IN (SELECT id FROM users WHERE region_id = '.$this->user['region_id'].')';
			break;
			case 4:
				$conditions[] = 'Sale.user_id IN (SELECT id FROM users WHERE depot_id = '.$this->user['depot_id'].')';
			break;
			case 5:
				$conditions['OR'] = array('Sale.user_id'=> $this->user['id'], 'Sale.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = '.$this->user['id'].')');
			case 6:
				$conditions['Sale.user_id'] = $this->user['id'];
			break;			
			default:
			break;
		}
	}
	
	//For sale edit
	public function orderedit($id=0){
		if ($this->request->data){
			
			$data = $stockStatus = array();
			$this->loadModel('Order');
			$this->Order->id = $id;
			$totalBrands = count( $this->request->data['brand_id'] );
			
			if(($totalBrands != count(array_filter($this->request->data['unit']))) || ($totalBrands != count(array_filter($this->request->data['qty']))))
			{				
				$this->Session->setFlash(__('Something missing, Please check your sale data entry table'));
			}
			else{
				//get the total price from Order table
				$this->loadModel('Order');
				$order_total = $this->Order->find('all', array('conditions'=>array('Order.id'=>$id)));
				$total_grnd = $order_total[0]['Order']['total'];
				if(empty($this->request->data['grand_total'])){
					$gtotal = $total_grnd;
				}else{
					$gtotal = $this->request->data['grand_total'];
				}
				
				$this->Order->delete($id);
			
				$orderData = array('customer_id' => $this->request->data['Sale']['customer_id'],'order_date'=>$this->request->data['Sale']['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $gtotal);
				$order = $this->Order->save($orderData);
				$this->loadModel('Customer');
				$this->Customer->id = $this->request->data['Sale']['customer_id'];
				$depot_id = $this->Customer->field('depot_id');
				$this->Customer->verify_status($this->request->data['Sale']['customer_id']);
				$order_id = $order['Order']['id'];
				foreach ($this->request->data['brand_id'] as $key => $val ){
					$stockStatus[$val]= array('depot_id' => $depot_id,'unit_id' => $this->request->data['unit'][$key] ,'qty' => $this->request->data['qty'][$key]);//pr($stockStatus);
				    
					// unit_price from brand table
					if($this->request->data['unit'][$key] == 'Case'){
					  $sunit = 'case_price' ;
					}else if($this->request->data['unit'][$key] == 'Roll'){
					   $sunit = 'roll_price' ;
					}
					else{
					   $sunit = 'pack_price' ;  
					}
					$this->loadModel('Brand');
					$brand_unit = $this->Brand->find('first', array('conditions'=>array('Brand.id'=>$val)));
					//pr($brand_unit['Brand'][$sunit]);
					
					$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
				
					$data[] = array(
						'brand_id'=> $val,
						'brand_group_id' =>$group_id[$val],
						'order_id'=> $order_id,
						'user_id'=>$this->user['id'], 
						'depot_id'=>$depot_id, 
						'customer_id'=>$this->request->data['Sale']['customer_id'],
						'sale_date'=>$this->request->data['Sale']['sale_date'],
						'unit'=>$this->request->data['unit'][$key], 
						//'unit_price'=>$this->request->data['unit_price'][$key], 
						'unit_price'=>$brand_unit['Brand'][$sunit], 
						'quantity' =>$this->request->data['qty'][$key], 
						'cal_qty' => $this->Sale->calQty($val, $this->request->data['unit'][$key], $this->request->data['qty'][$key]), 
						'amount'=>($this->request->data['qty'][$key]*$brand_unit['Brand'][$sunit]),
					);
					
					$unit = strtolower($this->request->data['unit'][$key]);
					
				}
				//Free Data
				$this->loadModel('FreeItem');
				$freeData = $stockStatus1 = array();
				if (!empty($this->request->data['freeItem'])){
					
					foreach ($this->request->data['freeItem']['brand_id'] as $key => $val ){
						$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
						
						$freeData[] = array(
							'order_id' => $order_id,
							'brand_id' => $val,
							'brand_group_id' =>$group_id[$val],
							'depot_id'=>$depot_id,
							'customer_id'=>$this->request->data['Sale']['customer_id'],
							'sale_date' =>$this->request->data['Sale']['sale_date'],
							'unit' => $this->request->data['freeItem']['unit'][$key],
							'quantity' => $this->request->data['freeItem']['quantity'][$key],
							'compaign_id' => $this->request->data['freeItem']['compaign_id'][$key],
							'cal_qty' => $this->Sale->calQty($val, $this->request->data['freeItem']['unit'][$key], $this->request->data['freeItem']['quantity'][$key])
						);
						$unit = strtolower($this->request->data['freeItem']['unit'][$key]);
						$stockStatus1[$val]= array('depot_id' => $depot_id,'unit_id' => $this->request->data['unit'][$key] ,'qty' => $this->request->data['qty'][$key]);
					}
				}
				if (!empty($data)){//pr($data);die();
					$this->Sale->saveAll($data);
					if ($freeData){
						$this->FreeItem->saveAll($freeData);
					}
					$this->Sale->updateStockStatus($stockStatus1 , $sale = true);
					$this->Session->setFlash(__('Sales was updated successfully'));
					$this->redirect(array('action'=>'saleOrders'));
					//$sales = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
					$this->set(compact('orders', 'regions', 'depots','sales'));
				}
			}
		
		}else{
			if(!empty($id)){
				$this->loadModel('Order');
					$this->Order->id = $id;
					$this->Order->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
					
					$order = $this->Order->read();
					
					if (!$order) {
						throw new NotFoundException(__('Invalid Sale'));
					}
					$sales = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
					$this->loadModel('FreeItem');
					$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = FreeItem.brand_id'));
					$freeItems = $this->FreeItem->find('all', array('fields'=>array('FreeItem.*', 'Brand.name'), 'conditions'=>array('order_id'=>$id), 'joins'=>$joins));
			}
		}			
		$this->set(compact('order', 'sales', 'freeItems'));
		$this->_options();

	} 
	/* function _updateAttendance_salentry(){
		$this->loadModel('Attendance');
		
		$date = date('Y-m-d');
		$data = array();
		$emp_id = $this->Auth->user('employee_id');
		
		if(!empty($emp_id)){
			$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
			
			if(empty($attendance) ){
				if($attendance['Attendance']['in_time'] == ''){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> date('Y-m-d H:i:s'), 'in_time'=> date('H:i:s'), 'date'=>$date);
				}
				$this->Attendance->save($data);
			}
			else{

				$this->_updateAttendance_salexit();
			}
		} 
	}
	function _updateAttendance_salexit(){
		$this->loadModel('Attendance');
		
		$date = date('Y-m-d');
		$data = array();
		$emp_id = $this->Auth->user('employee_id');
		$attendance = $this->Attendance->find('first', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
		$cnt = $this->Attendance->find('count', array('conditions'=>array('emp_id'=>$emp_id, 'date'=>$date)));
		
			if($attendance){
				if($attendance['Attendance']['out_time'] == ''){
                    if($cnt < 2){
					$data['Attendance'] = array('emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
                    }else{
                    $data['Attendance'] = array('id' =>$attendance['Attendance']['id'],'emp_id'=>$emp_id, 'is_present' =>1,'punch_time'=> $sdate, 'out_time'=> date('H:i:s',strtotime($sdate)), 'date'=>$date);
                    }
                }else{
					$data['Attendance'] = array('id' =>$attendance['Attendance']['id'], 'out_time' => date('H:i:s'), 'punch_time' => date('Y-m-d H:i:s'));
				}
				$this->Attendance->save($data);
			}
	} */
	
	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');
		
		$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);
			}
	}
	
 }
 
