<?php
App::uses('AppController', 'Controller');
class ConsumersController extends AppController {	
	var $components = array('FileUpload' => array(
							'allow_non_image_files' => false
						),'Option');
/**
 * Controller name
 *
 * @var string
 */
	public function index(){
		
		/* $this->loadModel('RedistributorSaleitem');
		$result = $this->RedistributorSaleitem->query(" SELECT redistributor_saleitems.`id` FROM `redistributor_saleitems` left join redistributor_sales on redistributor_saleitems.`redistributor_sale_id` = redistributor_sales.id WHERE redistributor_sales.id is NULL"); //pr($result);
		
		foreach($result as $r){
			$ids[] = $r['redistributor_saleitems']['id'];
		} pr(count($ids)); pr($ids); */
		
		/* $this->loadModel('Audit');
		
		$audits = $this->Audit->find('all', array('conditions'=> array('Model'=> 'ConsumerOrder','deleted_content LIKE'=>'%s:8:"depot_id";s:2:"30"%'),'order'=>array('delete_date'=>'desc'))); pr($audits);  */
		

		
		$conditions = array('Consumer.status !=' => DELETED);
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['Consumer.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['Consumer.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Consumer.state_id'] = $this->request->query['st'];
		}
		if ( !empty($this->request->query['dv'])){
            $conditions['Consumer.division_id'] = $this->request->query['dv'];
        }
		if (!empty($this->request->query['rg']) ){
			$conditions['Consumer.region_id'] = $this->request->query['rg'];
		}
		if (!empty($this->request->query['dp']) ){
			$conditions['Consumer.depot_id'] = $this->request->query['dp'];
		}
		if (!empty($this->request->query['rt']) ){
			$conditions['Consumer.route_id'] = $this->request->query['rt'];
		}
		if (!empty($this->request->query['usr']) ){
			$conditions['Consumer.user_id'] = $this->request->query['usr'];
		}
		
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Consumer.created BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Consumer.created >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Consumer.created <= '] = $this->request->query['to'];
		}
		
		//$this->Customer->_userCondition($conditions, $this->user);
		$this->Consumer->_userRoleCondition($conditions, $this->user, $this->paginate);
		$joins =  array();
		$joins = isset($this->paginate['joins'])?$this->paginate['joins']:array();
		$order=$this->paginate['order'] = array('Consumer.first_name'=>'asc', 'Consumer.last_name'=>'asc','Consumer.amount' => 'desc');

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

		 $Opdata =  array();

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

		$this->loadModel('User');

		$users = $this->User->usersListByRole($this->user);

		$this->set(compact('users'));
		
		$this->_selectOptions();
		if(isset($this->request->query['export'])){
			$this->set('filename', 'consumers');
			$this->render('export_consumer','export_xls');
		}
	}
	
	
	
	public function add(){
		$this->loadModel('User');
		if ($this->request->data){
			//pr($this->request->data); die();
			$is_exists = $this->Consumer->find('count', array('conditions'=>array('Consumer.phone'=>$this->request->data['Consumer']['phone']) )); 
			
			if ($is_exists > 0){
				$this->Session->setFlash(__('This phone number already associated with other Consumer'));
			}else{
				$image_ok = true;
			
				if (!empty($this->request->data['Consumer']['image']['name'])){
					if ($this->FileUpload->upload($this->request->data['Consumer'],'image')) {
						$this->request->data['Consumer']['file_id'] = $this->FileUpload->fileId;
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					$this->request->data['Consumer']['user_id'] = $this->Auth->user('id');
					if(empty($this->request->data['Consumer']['division_id']) && !empty($this->user['division_id']) ){
                        $this->request->data['Consumer']['division_id'] = $this->user['division_id'];
                    }
					if(empty($this->request->data['Consumer']['region_id']) && !empty($this->user['region_id']) ){
						$this->request->data['Consumer']['region_id'] = $this->user['region_id'];
					}
					if(empty($this->request->data['Consumer']['depot_id']) && !empty($this->user['depot_id']) ){
						$this->request->data['Consumer']['depot_id'] = $this->user['depot_id'];
					}
					$consumer = $this->Consumer->save($this->request->data);
					$consumer_id = $consumer['Consumer']['id'];
					if (!empty($this->request->data['Consumer']['user_ids'])){
						$userIds = $this->request->data['Consumer']['user_ids'];
						$this->loadModel('ConsumerAssign');
						$this->ConsumerAssign->primaryKey = null;
						$assignData = array();
						foreach($userIds as $uid){
							$assignData[] = array('consumer_id'=>$consumer_id, 'user_id'=>$uid, 'assign_by'=>$this->request->data['Consumer']['user_id']);
						}
						@$this->ConsumerAssign->saveAll($assignData);
					}
					$this->Session->setFlash(__('Consumer was added sucessfully'));
					$this->redirect(array('action'=>'index'));
				}
			}
		}
		$users = $this->User->usersListByRole($this->user);

		$this->set(compact('users'));
		$this->request->data['Consumer']['user_ids'] = array();
		$this->_selectOptions();
	}
	
	public function edit($id=0){
		$this->loadModel('User');
		$this->loadModel('Audit');
		$roledata=array(SUPPORT);
		$this->roleBasePermission($roledata);
		$userData = $this->Consumer->read(null, $id);
		if(!$id){
			$this->redirect('/consumers');
		}
		if ($this->request->data){ //pr($this->request->data); die();
			$is_exists = $this->Consumer->find('count', array('conditions'=>array('Consumer.phone'=>$this->request->data['Consumer']['phone'], 'Consumer.id !='=>$id)));
			
			if ($is_exists > 0){
				$this->Session->setFlash(__('This phone number already associated with other Consumer'));
			}else{
				$image_ok = true;
			
				if (!empty($this->request->data['Consumer']['image']['name'])){
					if ($this->FileUpload->upload($this->request->data['Consumer'],'image')) {
						$this->request->data['Consumer']['file_id'] = $uploaded_file_id = $this->FileUpload->fileId;
						if ($this->request->data['Consumer']['oldFile_id']){
							$this->FileUpload->removeFileId($this->request->data['Consumer']['oldFile_id']);
						}
					} else {
						$image_ok = false;
					}
				}
				if ($image_ok){
					//$this->request->data['Customer']['user_id'] = $this->Auth->user('id');
					if (!empty($this->request->data['Consumer']['oldFile_id']) && $this->request->data['Consumer']['remove_img'] == "1"){
						$this->FileUpload->removeFileId($this->request->data['Consumer']['oldFile_id']);
						if(!isset($uploaded_file_id)){
							$this->request->data['Consumer']['file_id'] = 0;
						}
					}
					$this->Consumer->save($this->request->data);
					
					$this->loadModel('ConsumerAssign');
					$this->ConsumerAssign->primaryKey = null;
					$this->ConsumerAssign->deleteAll(array('consumer_id'=>$id), false);
					
					if (!empty($this->request->data['Consumer']['user_ids'])){
						$userIds = $this->request->data['Consumer']['user_ids'];
						$assignData = array();
						foreach($userIds as $uid){
							$assignData[] = array('consumer_id'=>$id, 'user_id'=>$uid, 'assign_by'=>$this->Auth->user('d') );
						}
						//pr($assignData);
						@$this->ConsumerAssign->saveAll($assignData);
					}
					$this->Audit->saveDeletedData($userData['Consumer']['id'], 'Consumer', $this->Auth->user('id') , serialize($userData),'Consumer Has been updated', STATUS_EDIT);
					$this->Session->setFlash(__('Consumer was updated sucessfully'));
					$this->redirect(array('action'=>'index'));
				}
				
			}
		}else{
		
			$this->Consumer->id = $id;
			$this->request->data = $this->Consumer->read();
			$this->request->data['Consumer']['user_ids'] = array();
			$this->loadModel('ConsumerAssign');
			$this->ConsumerAssign->primaryKey = null;
			$assigned = $this->ConsumerAssign->find('all', array('conditions'=>array('consumer_id'=>$id)));
			if ($assigned){
				foreach($assigned as $assign){
					$this->request->data['Consumer']['user_ids'][] = $assign['ConsumerAssign']['user_id'];
				}
			}
		} 
		$users = $this->User->usersListByRole($this->user);
		
		$this->set(compact('users'));
		$this->_selectOptions();
		$this->render('add');
	}
	
	/**
     * view method
     *
     * @param string $id
     * @return void
     */
	 
	public function view($id = null){
		$this->Consumer->id = $id;
        if (!$this->Consumer->exists()) {
            throw new NotFoundException(__('Invalid Consumer'));
        }
		$belongsTo = array(		
			'Route' => array('className' => 'Route', 'foreignKey' => 'route_id', 'fields' => array('id', 'title'), 'type'=>'left'));
		$this->Consumer->belongsTo = array_merge($this->Consumer->belongsTo, $belongsTo);
        $this->set('consumer', $this->Consumer->read(null, $id));
	}
	
	/**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Consumer->id = $id;
		$Consumer = $this->Consumer->read();
        if (!$Consumer) {
            throw new NotFoundException(__('Invalid Consumer'));
        }
		$data = array();
		$data['serialize'] = serialize($Consumer);
		$data['model_id'] = $Consumer['Consumer']['id'];
        if ($this->Consumer->delete()) {
			$this->loadModel('Audit');
			if ($Consumer['Consumer']['file_id']){
				$this->FileUpload->removeFileId($Consumer['Consumer']['file_id']);
			}
			$this->Audit->saveDeletedData($data['model_id'], 'Consumer', $this->Auth->user('id') , $data['serialize'],'Consumer Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Consumer was deleted successfully'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Consumer was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

	
	function _selectOptions(){
		$Opdata = isset($this->request->data['Consumer'] ) ? $this->request->data['Consumer']  : array();
		$this->Option->Options($Opdata, $this->user);
	}
	
	
	public function sales($opr='', $id=0){
	   
	    
	    switch($opr){
	        case 'add';
	            $this->_add_sale();
			break;
			
			case 'edit':
				$this->_edit_sale($id);
			break;
			
			case 'delete':
				$this->_delete_sale($id);
			break;
			
			case 'view':
			
				$this->loadModel('ConsumerOrder');
				$this->loadModel('ConsumerSale');
				
				$this->ConsumerOrder->id = $id;
				//$this->ConsumerOrder->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
				
				$order = $this->ConsumerOrder->read();
				
				if (!$order) {
					throw new NotFoundException(__('Invalid Sale'));
				}
				$sales = $this->ConsumerSale->find('all', array('conditions'=>array('consumer_order_id'=>$id)));
				$this->loadModel('ConsumerFreeItem');
				$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = ConsumerFreeItem.brand_id'));
				$freeItems = $this->ConsumerFreeItem->find('all', array('fields'=>array('ConsumerFreeItem.*', 'Brand.name'), 'conditions'=>array('consumer_order_id'=>$id), 'joins'=>$joins));
				$this->set(compact('order', 'sales', 'freeItems'));
				
				$this->render('view_sale');
			break;
			
			default:
				
				$this->loadModel('ConsumerOrder');
			
				$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('ConsumerOrder.order_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));				
				} elseif (!empty($this->request->query['from'])){
					$conditions['ConsumerOrder.order_date >= '] = $this->request->query['from'];
				} elseif (!empty($this->request->query['to'])){
					$conditions['ConsumerOrder.order_date <= '] = $this->request->query['to'];
				}
				
				if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
					$conditions[] = array('ConsumerOrder.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('ConsumerOrder.id');
					
					$this->paginate['joins'] = array(array('table'=>'consumer_sales', 'alias'=>'ConsumerSale', 'conditions'=>'ConsumerOrder.id=ConsumerSale.consumer_order_id'));
                    if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                        $conditions[] = 'ConsumerSale.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[] = 'ConsumerSale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
					} 
					if (!empty($this->request->query['dp'])){
						$conditions['ConsumerSale.depot_id'] = $this->request->query['dp'];
					}
				}
				if (isset($this->request->query['sts']) && $this->request->query['sts']!='' ){
					$conditions['ConsumerOrder.status'] = $this->request->query['sts'];
				}

				if (isset($this->request->query['r']) && $this->request->query['r']!='' ){
					$conditions['User.role_id'] = $this->request->query['r'];
				}
			
				$this->loadModel('ConsumerSale');
				
				$this->ConsumerSale->_userRoleCondition($conditions, $this->user, $this->paginate);
				$sorder=$this->paginate['order'] = array('ConsumerOrder.created' => 'desc', 'ConsumerOrder.order_date' => 'desc');
				$order=$this->paginate['order'] = array('ConsumerOrder.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->ConsumerOrder->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('ConsumerOrder', $conditions);
				}

	//pr($orders);
                $this->loadModel('Division');
			$this->loadModel('Depot');
			$this->loadModel('Region');
            $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);
			
			$this->loadModel('Role');
			$this->user = $this->Auth->user();
			$roles = $this->Role->getList($this->user);  //pr($roles); 
			
			$this->set(compact('depots','divisions','regions','exporders','orders','offset','roles'));
			
			if(isset($this->request->query['export'])){   
				$this->set('filename', 'Sales');
				$this->render('export_saleorder','export_xls');
			}
				
			break;
	    }
	    
		
	}
	
	public function _add_sale(){
		
		if ($this->request->data){ //pr($this->request->data); die();
			$data = $stockStatus = array();
			$this->loadModel('ConsumerOrder');
			$this->loadModel('ConsumerSale');
			
			$this->_updateAttendance_salentry();
			if(empty($this->request->data['ConsumerSale']['sale_date'])){
				$this->request->data['ConsumerSale']['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('consumer_id' => $this->request->data['ConsumerSale']['consumer_id'],'order_date'=>$this->request->data['ConsumerSale']['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $this->request->data['grand_total'] );
				$order = $this->ConsumerOrder->save($orderData);
				
				$this->loadModel('Consumer');
				$this->loadModel('Brand');
				
				$this->Consumer->id = $this->request->data['ConsumerSale']['consumer_id'];
				$depot_id = $this->Consumer->field('depot_id');
				//$this->Consumer->verify_status($this->request->data['ConsumerSale']['consumer_id']);
				$order_id = $order['ConsumerOrder']['id'];
				
				$this->loadModel('Sale');
				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)));
					
					$stockStatus[$val]['entity_id'] = $depot_id;
					$stockStatus[$val]['entity'] = 'Depot';
					$stockStatus[$val]['brand_group_id'] = $group_id[$val];
					
					$data[] = array(
						'brand_id'=> $val,
						'brand_group_id' =>$group_id[$val],
						'consumer_order_id'=> $order_id,
						'user_id'=>$this->user['id'], 
						'depot_id'=>$depot_id, 
						'consumer_id'=>$this->request->data['ConsumerSale']['consumer_id'],
						'sale_date'=>$this->request->data['ConsumerSale']['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('ConsumerFreeItem');
				$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)));
						
						$stockStatus[$val]['brand_group_id'] = $group_id[$val];
						
						$freeData[] = array(
							'consumer_order_id' => $order_id,
							'brand_id' => $val,
							'brand_group_id' =>$group_id[$val],
							'depot_id'=>$depot_id, 
							'sale_date' => $this->request->data['ConsumerSale']['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['freeItem']['quantity'][$key];
					}
				} //pr($stockStatus);
				if ($data){ //pr($data);
					$this->ConsumerSale->saveAll($data);
					if ($freeData){
						$this->ConsumerFreeItem->saveAll($freeData);
					}
				
					$this->Sale->updateStockStatus($stockStatus);
					$this->Session->setFlash(__('Sales was saved successfully'));
					$this->redirect(array('action'=>'sales'));
					
				}
			}
		}
		
		$this->_options();
		
		$this->render('add_sale');
	}
	
	
	public function _edit_sale($id=0){  
		if ($this->request->data){ //pr($this->request->data); die();
			
			if(!empty($this->request->data['ConsumerSale']['oldSaleVal'])){
				$oldSaleVal = unserialize($this->request->data['ConsumerSale']['oldSaleVal']);
			}
			
			$data = $stockStatus = array();
			$this->loadModel('ConsumerOrder');
			$this->ConsumerOrder->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{
				
				$this->loadModel('ConsumerSale');
				$this->loadModel('Sale');
				
				//get the total price from Order table
				$order_total = $this->ConsumerOrder->find('all', array('conditions'=>array('ConsumerOrder.id'=>$id)));
				$total_grnd = $order_total[0]['ConsumerOrder']['total'];
				if(empty($this->request->data['grand_total'])){
					$gtotal = $total_grnd;
				}else{
					$gtotal = $this->request->data['grand_total'];
				}
				
				$orderData = array('id'=>$id,'consumer_id' => $this->request->data['ConsumerSale']['consumer_id'],'order_date'=>$this->request->data['ConsumerSale']['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $gtotal);
				$order = $this->ConsumerOrder->save($orderData);
				$this->Consumer->id = $this->request->data['ConsumerSale']['consumer_id'];
				$depot_id = $this->Consumer->field('depot_id');
				//$this->Consumer->verify_status($this->request->data['ConsumerSale']['consumer_id']);
				$order_id = $order['ConsumerOrder']['id'];
				
				$this->ConsumerSale->deleteAll(array('consumer_order_id'=>$id), false);
				
				foreach ($this->request->data['brand_id'] as $key => $val ){
					
					$this->loadModel('Brand');
					
					$group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
					
					$stockStatus[$val]['entity_id'] = $depot_id;
					$stockStatus[$val]['entity'] = 'Depot';
					$stockStatus[$val]['brand_group_id'] = $group_id[$val];
				
					$data[] = array(
						'brand_id'=> $val,
						'brand_group_id' =>$group_id[$val],
						'consumer_order_id'=> $order_id,
						'user_id'=>$this->user['id'], 
						'depot_id'=>$depot_id, 
						'consumer_id'=>$this->request->data['ConsumerSale']['consumer_id'],
						'sale_date'=>$this->request->data['ConsumerSale']['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];
					/* if(empty($oldSaleVal[$val][$unit])){
						//@$stockStatus[$val][$unit] += $this->request->data['qty'][$key];
					}else{
						if($oldSaleVal[$val][$unit] != $stockStatus[$val][$unit]){
							
						}
					} */
					
					
				}
				//Free Data
				$this->loadModel('ConsumerFreeItem');
				$freeData = $stockStatus1 = array();
				if (!empty($this->request->data['freeItem'])){
					
					$this->ConsumerFreeItem->deleteAll(array('consumer_order_id'=>$id), false);
					
					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(
							'consumer_order_id' => $order_id,
							'brand_id' => $val,
							'brand_group_id' =>$group_id[$val],
							'depot_id'=>$depot_id,
							'consumer_id'=>$this->request->data['ConsumerSale']['consumer_id'],
							'sale_date' =>$this->request->data['ConsumerSale']['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['freeItem']['quantity'][$key];
					}
				}
				if (!empty($data)){//pr($data);die();
					$this->ConsumerSale->saveAll($data);
					if ($freeData){
						$this->ConsumerFreeItem->saveAll($freeData);
					}
					//pr($stockStatus);
					foreach($oldSaleVal as $brand_id => $param){
						foreach($param as $unit=>$qty){
							if($oldSaleVal[$brand_id][$unit] == $stockStatus[$brand_id][strtolower($unit)]){
								$stockStatus[$brand_id][strtolower($unit)] = 0;
							}/* elseif($oldSaleVal[$brand_id][$unit] < $stockStatus[$brand_id][$unit]){
								$stockStatus[$brand_id][$unit] = $stockStatus[$brand_id][$unit] - $oldSaleVal[$brand_id][$unit];
							}elseif($oldSaleVal[$brand_id][$unit] > $stockStatus[$brand_id][$unit]){
								$stockStatus[$brand_id][$unit] = $stockStatus[$brand_id][$unit] - $oldSaleVal[$brand_id][$unit];
							} */
							else{
								$stockStatus[$brand_id][strtolower($unit)] = $stockStatus[$brand_id][strtolower($unit)] - $oldSaleVal[$brand_id][$unit];
							}
						}
					}
					//pr($stockStatus);
					$this->Sale->updateStockStatus($stockStatus);
					$this->Session->setFlash(__('Sales was updated successfully'));
					$this->redirect(array('action'=>'sales'));
					$this->set(compact('orders', 'regions', 'depots','sales'));
				}
			}
		
		}else{
			if(!empty($id)){
				$this->loadModel('ConsumerOrder');
				
				
					$this->ConsumerOrder->id = $id;
					$this->ConsumerOrder->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
					
					$order = $this->ConsumerOrder->read(); //pr($order);
					
					if (!$order) {
						throw new NotFoundException(__('Invalid Sale'));
					}
			}
		}			
		$this->set(compact('order'));
		$this->_options();
		
		$this->render('edit_sale');
	}
	
	public function _delete_sale($id=0){  
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('ConsumerOrder');
        $this->ConsumerOrder->id = $id;
		$order = $this->ConsumerOrder->read(); //pr($order);
        if (!$order) {
            throw new NotFoundException(__('Invalid Order'));
        }
		
		$data = array();
		$data['serialize'] = serialize($order);
		$data['model_id'] = $order['ConsumerOrder']['id'];
        if ($this->ConsumerOrder->delete()) {
			$stockStatus = array();
			
			
			foreach($order['ConsumerSale'] as $sale){
				$stockStatus[$sale['brand_id']]['entity_id'] = $sale['depot_id'];
				$stockStatus[$sale['brand_id']]['entity'] = 'Depot';
				
				@$stockStatus[$sale['brand_id']][strtolower($sale['unit'])] -= $sale['quantity'];
			}
			if(!empty($order['ConsumerFreeItem'])){
				foreach($order['ConsumerFreeItem'] as $freeItem){
					@$stockStatus[$freeItem['brand_id']][strtolower($freeItem['unit'])] -= $freeItem['quantity'];
				}
			}
			//pr($stockStatus);
			if($stockStatus){
				$this->loadModel('Sale');
				$this->Sale->updateStockStatus($stockStatus);
			}
			
			$this->loadModel('Audit');			
			$this->Audit->saveDeletedData($data['model_id'], 'ConsumerOrder', $this->Auth->user('id') , $data['serialize'],'Consumer Order Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Consumer Sale was deleted successfully'));
            $this->redirect(array('action' => 'sales')); 
        }
        $this->Session->setFlash(__('Sale was not deleted'));
        $this->redirect(array('action' => 'sales'));
		
	}
	
	
	public function deleteAllConsumerOrders(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			
			$this->loadModel('ConsumerOrder');
			$this->loadModel('Audit');
			$this->loadModel('Sale');
			
			$ids = explode(",", $this->request->data['deleteAllValue']);
			
			foreach($ids as $id){
				$this->ConsumerOrder->id = $id;
				$order = $this->ConsumerOrder->read();
				
				$data = array();
				$data['serialize'] = serialize($order);
				$data['model_id'] = $order['ConsumerOrder']['id'];
				if ($this->ConsumerOrder->delete()) {
					$stockStatus = array();
								
					foreach($order['ConsumerSale'] as $sale){
						$stockStatus[$sale['brand_id']]['entity_id'] = $sale['depot_id'];
						$stockStatus[$sale['brand_id']]['entity'] = 'Depot';
						
						@$stockStatus[$sale['brand_id']][strtolower($sale['unit'])] -= $sale['quantity'];
					}
					if(!empty($order['ConsumerFreeItem'])){
						foreach($order['ConsumerFreeItem'] as $freeItem){
							@$stockStatus[$freeItem['brand_id']][strtolower($freeItem['unit'])] -= $freeItem['quantity'];
						}
					}
					//pr($stockStatus);
					if($stockStatus){
						$this->loadModel('Sale');
						$this->Sale->updateStockStatus($stockStatus);
					}
					
					$this->loadModel('Audit');			
					$this->Audit->saveDeletedData($data['model_id'], 'ConsumerOrder', $this->Auth->user('id') , $data['serialize'],'Consumer Order Has been Deleted',STATUS_DELETE);
				}
			}
			
			
			$this->Session->setFlash(__('All selected sales was deleted successfully') );
			$this->redirect(array('action'=>'sales'));
		}
		exit;
	}
	
	function _options(){
		$this->loadModel('Depot');	
		$this->loadModel('Redistributor');				
		
		$this->user = $this->Auth->user(); 
		
		$consumers = $this->Consumer->consumerListByRole($this->user);
		
		$redistributors = $this->Redistributor->redistributorListByRole($this->user);
		
		switch($this->user['Role']['grade']){
			case 1:
			case 2:
				$depots = $this->Depot->find('list', array('fields'=>array('id','title'),'order'=>array('title'=>'asc')));
			break;
			
			case 3:
				$depots = $this->Depot->find('list', array('fields'=>array('id','title'),'conditions' => array('region_id' =>$this->user['region_id']), 'order'=>array('title'=>'asc')));
			break;			
		}
		
		$this->loadModel('Brand');
		
		$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('depots','consumers','brands', 'brandList','brankdsObj','compaignArray','redistributors'));
	}
	
	public function getConsumers(){
		$result = $consumers = $redistributors = array();
		$eoption = array("0"=>__('Select Consumer'));
		$roption = array("0"=>__('Select Redistributor'));
		if (!empty($this->request->data['depot'])){
			
			$consumers = $this->Consumer->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot'], 'status'=>ACTIVE), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc')));
			
			if(!empty($this->request->data['rsale'])){
				$this->loadModel('Redistributor');
				$redistributors = $this->Redistributor->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot'], 'status'=>ACTIVE), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc')));
			}
		}

		$result['consumers'] = $eoption + $consumers;
		$result['redistributors'] = $roption + $redistributors;
		echo json_encode($result);
		exit;
	}
	
	
	function consumerCompaigns(){
		
		$this->loadModel('Compaign');
		
		$conditions = array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date");

		//$this->request->data['cId'] =1;
		if( !empty($this->request->data['cId']) ){
			$this->Consumer->id = $this->request->data['cId'];
			$consumer = $this->Consumer->read();
			if ($consumer){
				$conditions[] = "Compaign.id IN (SELECT compaign_id FROM compaigns_depots WHERE depot_id = ".$consumer['Consumer']['depot_id'].")";
			}
		}
		$this->Compaign->unbindModel(array('hasAndBelongsToMany' => array('Depot', 'Region')));
		
		$compaigns = $this->Compaign->find('all', array('conditions' => $conditions));
		$compaignArray = array();
		
		if($compaigns){
			foreach($compaigns as $compaign){
				$brandId = $compaign['Compaign']['brand_id'];
				$compaignArray[$brandId][] = $compaign['Compaign'];
			}
		}
		$this->set(compact('compaigns', 'compaignArray', 'consumer'));
	}
	
	
	public function redistribution_sales($opr='', $id=0){
	   
	    
	   switch($opr){
	        case 'add';
	            $this->_add_redistribution_sale();
			break;
			
			case 'edit':
				$this->_edit_redistribution_sale($id);
			break;
			
			case 'delete':
				$this->_delete_redistribution_sale($id);
			break;
			
			case 'view':
			
				$this->loadModel('ConsumerRedistributionOrder');
				$this->loadModel('ConsumerRedistributionSale');
				
				$this->ConsumerRedistributionOrder->id = $id;
				//$this->ConsumerOrder->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
				
				$order = $this->ConsumerRedistributionOrder->read();
				
				if (!$order) {
					throw new NotFoundException(__('Invalid Sale'));
				}
				$sales = $this->ConsumerRedistributionSale->find('all', array('conditions'=>array('consumer_redistribution_order_id'=>$id)));
				/* $this->loadModel('ConsumerFreeItem');
				$joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = ConsumerFreeItem.brand_id'));
				$freeItems = $this->ConsumerFreeItem->find('all', array('fields'=>array('ConsumerFreeItem.*', 'Brand.name'), 'conditions'=>array('consumer_order_id'=>$id), 'joins'=>$joins)); */
				$this->set(compact('order', 'sales', 'freeItems'));
				
				$this->render('view_redistribution_sale');
			break;
			
			default:
				
			$this->loadModel('ConsumerRedistributionOrder');
			
				$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('ConsumerRedistributionOrder.order_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));				
				} elseif (!empty($this->request->query['from'])){
					$conditions['ConsumerRedistributionOrder.order_date >= '] = $this->request->query['from'];
				} elseif (!empty($this->request->query['to'])){
					$conditions['ConsumerRedistributionOrder.order_date <= '] = $this->request->query['to'];
				}
				
				if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
					$conditions[] = array('ConsumerRedistributionOrder.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('ConsumerRedistributionOrder.id');
					
					$this->paginate['joins'] = array(array('table'=>'consumer_redistribution_sales', 'alias'=>'ConsumerRedistributionSale', 'conditions'=>'ConsumerRedistributionOrder.id=ConsumerRedistributionSale.consumer_redistribution_order_id'));
                    if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                        $conditions[] = 'ConsumerRedistributionSale.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[] = 'ConsumerRedistributionSale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
					} 
					if (!empty($this->request->query['dp'])){
						$conditions['ConsumerRedistributionSale.depot_id'] = $this->request->query['dp'];
					}
				}
				if (isset($this->request->query['sts']) && $this->request->query['sts']!='' ){
					$conditions['ConsumerRedistributionOrder.status'] = $this->request->query['sts'];
				}

				if (isset($this->request->query['r']) && $this->request->query['r']!='' ){
					$conditions['User.role_id'] = $this->request->query['r'];
				}
			
				$this->loadModel('ConsumerRedistributionSale');
				
				$this->ConsumerRedistributionSale->_userRoleCondition($conditions, $this->user, $this->paginate);
				$sorder=$this->paginate['order'] = array('ConsumerRedistributionOrder.created' => 'desc', 'ConsumerRedistributionOrder.order_date' => 'desc');
				$order=$this->paginate['order'] = array('ConsumerRedistributionOrder.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->ConsumerRedistributionOrder->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('ConsumerRedistributionOrder', $conditions);
				}

	//pr($orders);
			
			$this->loadModel('Division');
			$this->loadModel('Depot');
			$this->loadModel('Region');
            $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);
			
			$this->loadModel('Role');
			$this->user = $this->Auth->user();
			$roles = $this->Role->getList($this->user);  //pr($roles); 
			
			$this->set(compact('divisions', 'depots','regions','exporders','orders','offset','roles'));
			
			if(isset($this->request->query['export'])){   
				$this->set('filename', 'Consumer Redistribution Sales');
				$this->render('export_redistributionsaleorder','export_xls');
			}
				
			break;
	    }
	    
		
	}
	
	public function _add_redistribution_sale(){
		$this->loadModel('ConsumerRedistributionOrder');
		$this->loadModel('ConsumerRedistributionSale');
		$this->loadModel('Sale');
		$this->loadModel('Brand');
		
		if ($this->request->data){ //pr($this->request->data); die();
			$data = $stockStatus = array();
			
			//$this->_updateAttendance_salentry();
			
			$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
			{	
				if(empty($this->request->data['ConsumerRedistributionSale']['order_date'])){
					$this->request->data['ConsumerRedistributionSale']['order_date'] = date('Y-m-d H:i:s');
				}
				
				$orderData = array('redistributor_id' => $this->request->data['ConsumerRedistributionSale']['redistributor_id'], 'consumer_id' => $this->request->data['ConsumerRedistributionSale']['consumer_id'], 'order_date'=>$this->request->data['ConsumerRedistributionSale']['order_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $this->request->data['grand_total'] );
				
				$order = $this->ConsumerRedistributionOrder->save($orderData);
				
				$this->loadModel('Consumer');
				$this->Consumer->id = $this->request->data['ConsumerRedistributionSale']['consumer_id'];
				$depot_id = $this->Consumer->field('depot_id');
				//$this->Consumer->verify_status($this->request->data['ConsumerRedistributionSale']['consumer_id']);
				$order_id = $order['ConsumerRedistributionOrder']['id'];
				
				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)));
					
					$stockStatus[$val]['entity_id'] = $depot_id;
					$stockStatus[$val]['entity'] = 'Depot';
					$stockStatus[$val]['brand_group_id'] = $group_id[$val];
					
					$data[] = array(
						'brand_id'=> $val,
						'brand_group_id' =>$group_id[$val],
						'consumer_redistribution_order_id'=> $order_id,
						'redistributor_id' => $this->request->data['ConsumerRedistributionSale']['redistributor_id'],
						'user_id'=>$this->user['id'], 
						'depot_id'=>$depot_id, 
						'consumer_id'=>$this->request->data['ConsumerRedistributionSale']['consumer_id'],
						'sale_date'=>$this->request->data['ConsumerRedistributionSale']['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('ConsumerFreeItem');
				$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)));
						
						$stockStatus[$val]['brand_group_id'] = $group_id[$val];
						
						$freeData[] = array(
							'consumer_order_id' => $order_id,
							'brand_id' => $val,
							'brand_group_id' =>$group_id[$val],
							'depot_id'=>$depot_id, 
							'sale_date' => $this->request->data['ConsumerSale']['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['freeItem']['quantity'][$key];
					}
				} //pr($stockStatus); */
				if ($data){
					$this->ConsumerRedistributionSale->saveAll($data);
					/* if ($freeData){
						$this->RdFreeItem->saveAll($freeData);
					} */
				
					$this->Sale->updateStockStatus($stockStatus);
					$this->Session->setFlash(__('Consumer Redistributor Sales was saved successfully'));
					$this->redirect(array('action'=>'redistribution_sales'));
					
				}
			}
		}
		
		$this->_options();
		
		$this->render('add_redistribution_sale');
		
	}
	
	
	public function _edit_redistribution_sale($id=0){  
		if ($this->request->data){ //pr($this->request->data); die();
			
			if(!empty($this->request->data['ConsumerRedistributionSale']['oldSaleVal'])){
				$oldSaleVal = unserialize($this->request->data['ConsumerRedistributionSale']['oldSaleVal']);
			}
			
			$data = $stockStatus = array();
			$this->loadModel('ConsumerRedistributionOrder');
			$this->ConsumerRedistributionOrder->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{
				
				$this->loadModel('ConsumerRedistributionSale');
				$this->loadModel('Sale');
				
				//get the total price from Order table
				$order_total = $this->ConsumerRedistributionOrder->find('all', array('conditions'=>array('ConsumerRedistributionOrder.id'=>$id)));
				$total_grnd = $order_total[0]['ConsumerRedistributionOrder']['total'];
				if(empty($this->request->data['grand_total'])){
					$gtotal = $total_grnd;
				}else{
					$gtotal = $this->request->data['grand_total'];
				}
				
				//$this->ConsumerOrder->delete($id);
				
			
				$orderData = array('id'=>$id, 'redistributor_id' => $this->request->data['ConsumerRedistributionSale']['redistributor_id'],'consumer_id' => $this->request->data['ConsumerRedistributionSale']['consumer_id'],'order_date'=>$this->request->data['ConsumerRedistributionSale']['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $gtotal);
				$order = $this->ConsumerRedistributionOrder->save($orderData);
				$this->Consumer->id = $this->request->data['ConsumerRedistributionSale']['consumer_id'];
				$depot_id = $this->Consumer->field('depot_id');
				//$this->Consumer->verify_status($this->request->data['ConsumerSale']['consumer_id']);
				$order_id = $order['ConsumerRedistributionOrder']['id'];
				
				$this->ConsumerRedistributionSale->deleteAll(array('consumer_redistribution_order_id'=>$id), false);
				
				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)));
					
					$stockStatus[$val]['entity_id'] = $depot_id;
					$stockStatus[$val]['entity'] = 'Depot';
					$stockStatus[$val]['brand_group_id'] = $group_id[$val];
				
					$data[] = array(
						'brand_id'=> $val,
						'brand_group_id' =>$group_id[$val],
						'consumer_redistribution_order_id'=> $order_id,
						'redistributor_id' => $this->request->data['ConsumerRedistributionSale']['redistributor_id'],
						'user_id'=>$this->user['id'], 
						'depot_id'=>$depot_id, 
						'consumer_id'=>$this->request->data['ConsumerRedistributionSale']['consumer_id'],
						'sale_date'=>$this->request->data['ConsumerRedistributionSale']['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]),
						'amount'=>$this->request->data['amount'][$key]
					);
					
					$unit = strtolower($this->request->data['unit'][$key]);
					@$stockStatus[$val][$unit] += $this->request->data['qty'][$key];
					/* if(empty($oldSaleVal[$val][$unit])){
						//@$stockStatus[$val][$unit] += $this->request->data['qty'][$key];
					}else{
						if($oldSaleVal[$val][$unit] != $stockStatus[$val][$unit]){
							
						}
					} */
					
					
				}
				//Free Data
				
				$freeData = $stockStatus1 = array();
				/* $this->loadModel('ConsumerFreeItem');
				if (!empty($this->request->data['freeItem'])){
					
					$this->ConsumerFreeItem->deleteAll(array('consumer_order_id'=>$id), false);
					
					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(
							'consumer_order_id' => $order_id,
							'brand_id' => $val,
							'brand_group_id' =>$group_id[$val],
							'depot_id'=>$depot_id,
							'consumer_id'=>$this->request->data['ConsumerSale']['consumer_id'],
							'sale_date' =>$this->request->data['ConsumerSale']['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['freeItem']['quantity'][$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->ConsumerRedistributionSale->saveAll($data);
					/* if ($freeData){
						$this->ConsumerFreeItem->saveAll($freeData);
					} */
					//pr($stockStatus);
					foreach($oldSaleVal as $brand_id => $param){
						foreach($param as $unit=>$qty){
							if($oldSaleVal[$brand_id][$unit] == $stockStatus[$brand_id][strtolower($unit)]){
								$stockStatus[$brand_id][strtolower($unit)] = 0;
							}/* elseif($oldSaleVal[$brand_id][$unit] < $stockStatus[$brand_id][$unit]){
								$stockStatus[$brand_id][$unit] = $stockStatus[$brand_id][$unit] - $oldSaleVal[$brand_id][$unit];
							}elseif($oldSaleVal[$brand_id][$unit] > $stockStatus[$brand_id][$unit]){
								$stockStatus[$brand_id][$unit] = $stockStatus[$brand_id][$unit] - $oldSaleVal[$brand_id][$unit];
							} */
							else{
								$stockStatus[$brand_id][strtolower($unit)] = $stockStatus[$brand_id][strtolower($unit)] - $oldSaleVal[$brand_id][$unit];
							}
						}
					}
					//pr($stockStatus);
					$this->Sale->updateStockStatus($stockStatus);
					//$this->Sale->updateStockStatus($stockStatus1 , $sale = true);
					$this->Session->setFlash(__('Sales was updated successfully'));
					$this->redirect(array('action'=>'redistribution_sales'));
					$this->set(compact('orders', 'regions', 'depots','sales'));
				}
			}
		
		}else{
			if(!empty($id)){
				$this->loadModel('ConsumerRedistributionOrder');
				$this->loadModel('Redistributor');
				$this->loadModel('Consumer');
				
				
					$this->ConsumerRedistributionOrder->id = $id;
					$this->ConsumerRedistributionOrder->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
					
					$order = $this->ConsumerRedistributionOrder->read(); //pr($order);
					
					if (!$order) {
						throw new NotFoundException(__('Invalid Sale'));
					}
					
					$this->_options();
					
					$depotId = $order['ConsumerRedistributionSale'][0]['depot_id'];
					
					$redistributors = $this->Redistributor->find('list', array('fields'=>array('id', 'name'), 'conditions'=>array('Redistributor.depot_id'=>$depotId )));
					
					$consumers = $this->Consumer->find('list', array('fields'=>array('id', 'name'), 'conditions'=>array('Consumer.depot_id'=>$depotId )));
					
					$this->set(compact('order', 'redistributors', 'consumers'));
										
			}
		}			
		
		
		
		
		
		$this->render('edit_redistribution_sale');
	}
	
	
	public function _delete_redistribution_sale($id=0){  
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('ConsumerRedistributionOrder');
        $this->ConsumerRedistributionOrder->id = $id;
		$order = $this->ConsumerRedistributionOrder->read(); //pr($order);
        if (!$order) {
            throw new NotFoundException(__('Invalid Order'));
        }
		
		$data = array();
		$data['serialize'] = serialize($order);
		$data['model_id'] = $order['ConsumerRedistributionOrder']['id'];
        if ($this->ConsumerRedistributionOrder->delete()) {
			$stockStatus = array();
			
			
			foreach($order['ConsumerRedistributionSale'] as $sale){
				$stockStatus[$sale['brand_id']]['entity_id'] = $sale['depot_id'];
				$stockStatus[$sale['brand_id']]['entity'] = 'Depot';
				
				@$stockStatus[$sale['brand_id']][strtolower($sale['unit'])] -= $sale['quantity'];
			}
			/* if(!empty($order['ConsumerFreeItem'])){
				foreach($order['ConsumerFreeItem'] as $freeItem){
					@$stockStatus[$freeItem['brand_id']][strtolower($freeItem['unit'])] -= $freeItem['quantity'];
				}
			} */
			//pr($stockStatus);
			if($stockStatus){
				$this->loadModel('Sale');
				$this->Sale->updateStockStatus($stockStatus);
			}
			
			$this->loadModel('Audit');			
			$this->Audit->saveDeletedData($data['model_id'], 'ConsumerRedistributionOrder', $this->Auth->user('id') , $data['serialize'],'Consumer Redistribution Order Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Consumer Sale was deleted successfully'));
            $this->redirect(array('action' => 'redistribution_sales')); 
        }
        $this->Session->setFlash(__('Sale was not deleted'));
        $this->redirect(array('action' => 'redistribution_sales'));
		
	}
	
	
	public function deleteAllConsumerRedistributionOrders(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			
			$this->loadModel('ConsumerRedistributionOrder');
			$this->loadModel('Audit');
			$this->loadModel('Sale');
			
			$ids = explode(",", $this->request->data['deleteAllValue']);
			
			foreach($ids as $id){
				$this->ConsumerRedistributionOrder->id = $id;
				$order = $this->ConsumerRedistributionOrder->read();
				
				$data = array();
				$data['serialize'] = serialize($order);
				$data['model_id'] = $order['ConsumerRedistributionOrder']['id'];
				if ($this->ConsumerRedistributionOrder->delete()) {
					$stockStatus = array();
								
					foreach($order['ConsumerRedistributionSale'] as $sale){
						$stockStatus[$sale['brand_id']]['entity_id'] = $sale['depot_id'];
						$stockStatus[$sale['brand_id']]['entity'] = 'Depot';
						
						@$stockStatus[$sale['brand_id']][strtolower($sale['unit'])] -= $sale['quantity'];
					}
					/* if(!empty($order['ConsumerFreeItem'])){
						foreach($order['ConsumerFreeItem'] as $freeItem){
							@$stockStatus[$freeItem['brand_id']][strtolower($freeItem['unit'])] -= $freeItem['quantity'];
						}
					} */
					//pr($stockStatus);
					if($stockStatus){
						$this->loadModel('Sale');
						$this->Sale->updateStockStatus($stockStatus);
					}
					
					$this->loadModel('Audit');			
					$this->Audit->saveDeletedData($data['model_id'], 'ConsumerRedistributionOrder', $this->Auth->user('id') , $data['serialize'],'Consumer Redistribution Order Has been Deleted',STATUS_DELETE);
				}
			}
			
			/* $this->Order->deleteAll(array('Order.id'=>explode(",", $this->request->data['deleteAllValue'])) ); */
			$this->Session->setFlash(__('All selected consumer redistribution sales was deleted successfully') );
			$this->redirect(array('action'=>'redistribution_sales'));
		}
		exit;
	}
	
	
	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);
			}
	}
	
	public function sale_report(){
		
		$this->loadModel('ConsumerSale');
		
		$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(" ", Consumer.first_name, Consumer.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[] = 'ConsumerSale.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[] = 'ConsumerSale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
            if (!empty($this->request->query['dp'])){
                $conditions['ConsumerSale.depot_id'] = $this->request->query['dp'];
            }

        }
//		if ( !empty($this->request->query['dp'])){
//			$conditions['ConsumerSale.depot_id'] = $this->request->query['dp'];
//		}
		if ( !empty($this->request->query['brd'])){
			$conditions['ConsumerSale.brand_id'] = $this->request->query['brd'];
		}
		if ( !empty($this->request->query['unt'])){
			$conditions['ConsumerSale.unit'] = $this->request->query['unt'];
		}
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('ConsumerSale.sale_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));
			
		}elseif (!empty($this->request->query['from'])){
			$conditions['ConsumerSale.sale_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['ConsumerSale.sale_date <= '] = $this->request->query['to'];
		}
		if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
			$conditions['ConsumerSale.status'] = $this->request->query['sts'];
		}
		//$order = $this->paginate['order'] = array('Sale.sale_date' => 'desc');
		$order = $this->paginate['order'] = array('ConsumerSale.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->ConsumerSale->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		}else{
			$sales = $this->paginate('ConsumerSale', $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', 'ConsumerSales');
			$this->render('export_consumersales_report','export_xls');
		}/*  else {
			$this->render('index');
		} */
	}
	
	
	function _salesRoleConditions(&$conditions){
		switch($this->user['Role']['grade']){
			case 3:
				$conditions[] = 'ConsumerSale.user_id IN (SELECT id FROM users WHERE region_id = '.$this->user['region_id'].')';
			break;
			case 4:
				$conditions[] = 'ConsumerSale.user_id IN (SELECT id FROM users WHERE depot_id = '.$this->user['depot_id'].')';
			break;
			case 5:
				$conditions['OR'] = array('ConsumerSale.user_id'=> $this->user['id'], 'ConsumerSale.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = '.$this->user['id'].')');
			case 6:
				$conditions['ConsumerSale.user_id'] = $this->user['id'];
			break;			
			default:
			break;
		}
	}
	
	
	public function redistribution_sale_report(){
		//$this->gradPermission(4);
		$conditions = array();
		$this->loadModel('ConsumerRedistributionOrder');
		$this->loadModel('ConsumerRedistributionSale');
		
		/* $this->RedistributorSaleitem->belongsTo = array(
			'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'), 
			'Brand' => array('className' => 'Brand', 'foreignKey' => 'brand_id', 'type'=>'inner'), 
			'Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('id', 'title','region_id'), 'type'=>'left'),
			'Customer' => array('className' => 'Customer', 'foreignKey' => 'customer_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
			'Redistributor' => array('className' => 'Redistributor', 'foreignKey' => 'redistributor_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
		); */
		
		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(" ", Consumer.first_name, Consumer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['concat_ws(" ", Redistributor.first_name, Redistributor.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
		}
        $division_id = $region_id = '0';
        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']) ) {
                $division_id = $this->request->query['dv'];
                $conditions[] = 'ConsumerRedistributionSale.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']) ){
                $region_id = $this->request->query['rg'];
                $conditions[] = 'ConsumerRedistributionSale.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
            if (!empty($this->request->query['dp'])){
                $conditions['ConsumerRedistributionSale.depot_id'] = $this->request->query['dp'];
            }

        }
//		if ( !empty($this->request->query['dp'])){
//			$conditions['ConsumerRedistributionSale.depot_id'] = $this->request->query['dp'];
//		}
		if ( !empty($this->request->query['brd'])){
			$conditions['ConsumerRedistributionSale.brand_id'] = $this->request->query['brd'];
		}
		if ( !empty($this->request->query['unt'])){
			$conditions['ConsumerRedistributionSale.unit'] = $this->request->query['unt'];
		}
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('ConsumerRedistributionSale.sale_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));
			
		}elseif (!empty($this->request->query['from'])){
			$conditions['ConsumerRedistributionSale.sale_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['ConsumerRedistributionSale.sale_date <= '] = $this->request->query['to'];
		}
		if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
			$conditions['ConsumerRedistributionSale.status'] = $this->request->query['sts'];
		}
		$order = $this->paginate['order'] = array('ConsumerRedistributionSale.created' => 'desc');
		$this->ConsumerRedistributionOrder->_userSalesCondition($conditions, $this->user);
		$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();		
			$sales = $this->ConsumerRedistributionSale->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		}else{
	  	   $sales = $this->paginate('ConsumerRedistributionSale', $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('conditions'=>array('status'=>ACTIVE), 'fields'=>array('id','name')));
		
		//$redistributors = $this->Redistributor->redistributorListByRole($this->user);
		$this->set(compact('offset','divisions','regions','depots', 'brands'));

		if(isset($this->request->query['export'])){			
			$this->set('filename', 'ConsumerRedistributorSale');
			$this->render('export_redistributor_report','export_xls');
		} 
	}
	
 }
