<?php
App::uses('AppController', 'Controller');
class WarehouseController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
	public function index(){
	//	$this->gradPermission(2);
		$conditions = array();
		if (!empty($this->request->query['q']) ){
			$conditions['Warehouse.title LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Warehouse.state_id'] = $this->request->query['st'];
		}
		if(!empty($this->request->query['dv']) && empty($this->request->query['rg'])){
            $division_id = $this->request->query['dv'];
            $divisionRegion = ClassRegistry::init('DivisionsRegion');
            $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' =>$this->request->query['dv'])));
            $conditions['Warehouse.region_id IN'] = $rIds;
        }else{
            $division_id = 0;
        }
        if (!empty($this->request->query['rg']) ){
            $conditions['Warehouse.region_id'] = $this->request->query['rg'];
        }
		$order = $this->paginate['Warehouse.order'] = array('Warehouse.title' => 'asc');
		$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();		
			$warehouses = $this->Warehouse->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		} else {
		     $warehouses = $this->paginate('Warehouse', $conditions);
	    }
		$this->set('warehouses', $warehouses);
		$this->loadModel('Division');
		$this->loadModel('State');
		$this->loadModel('Region');
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$divisions = $this->Division->getList();
        $regions = $this->Region->getList($division_id);
		$this->set(compact('offset','states', 'divisions','regions'));
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'Warehouse');
			$this->render('export_warehouse','export_xls');
		}
	}
	public function add(){
	//	$this->gradPermission(2);
		if ($this->request->data){
			$is_exists = $this->Warehouse->find('count', array('conditions'=>array('LOWER(Warehouse.title)'=>strtolower($this->request->data['Warehouse']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Warehouse']['title']));
			}else{
				if($this->request->data['opening_stocks']){
					$this->request->data['Warehouse']['opening_stocks'] = serialize($this->request->data['opening_stocks']);
				}
				$this->Warehouse->save($this->request->data);
				$this->Session->setFlash(__('Werehouse was added sucessfully'));
				$this->redirect('/warehouse');
			}
		}
		
		$this->loadModel('State');
		$this->loadModel('Region');
		$this->loadModel('Brand');
		$this->loadModel('BrandGroup');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		$brand_groups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$this->set(compact('states', 'regions', 'brands', 'brand_groups'));
		$this->set('var', $states);
	}
	
	public function edit($id=0){
		$this->loadModel('Audit');
		$userData = $this->Warehouse->read(null, $id);
	$this->roleBasePermission(array(SUPPORT));
	//$set_var=$this->gradPermission(2);
		if ($this->request->data){
			$is_exists = $this->Warehouse->find('count', array('conditions'=>array('LOWER(Warehouse.title)'=>strtolower($this->request->data['Warehouse']['title']), 'Warehouse.id !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Warehouse']['title']));
			}else{
				if($this->request->data['opening_stocks']){
					$this->request->data['Warehouse']['opening_stocks'] = serialize($this->request->data['opening_stocks']);
				}
				$this->Warehouse->save($this->request->data);
				$this->Audit->saveDeletedData($userData['Warehouse']['id'], 'Warehouse', $this->Auth->user('id') , serialize($userData),'Warehouse Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Warehouse was updated sucessfully'));
				$this->redirect('/warehouse');
			}
		}
		if (!empty($id)){
			$this->Warehouse->id = $id;
			$this->request->data = $this->Warehouse->read();
			if ($this->request->data['Warehouse']['opening_stocks']){
				$this->request->data['opening_stocks'] = unserialize($this->request->data['Warehouse']['opening_stocks']);
			}
		}
		$this->loadModel('State');
		$this->loadModel('Region');
		$this->loadModel('Brand');
		$this->loadModel('BrandGroup');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		$brand_groups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$this->set(compact('states', 'regions','brands', 'brand_groups'));
		//if($set_var){
		$this->render('add');
		//}
		
	}
	public function delete($id=0){
		if(!$id){
			$this->redirect('/warehouse');
		}
		$this->Warehouse->id = $id;
		$warehouse = $this->Warehouse->read();

		$data = array();
		$data['serialize'] = serialize($warehouse);
		$data['model_id'] = $warehouse['Warehouse']['id'];
		$this->Warehouse->delete();
		$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Warehouse', $this->Auth->user('id') , $data['serialize'],'Warehouse Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Warehouse was deleted sucessfully'));
		$this->redirect(array('action'=>'index'));
	}
	
	public function view ($id){
		$this->Warehouse->id = $id;
		//$this->Warehouse->hasOne = array('User'=>array('className'=>'User', 'foreignKey'=>'depot_id', 'conditions'=>array('User.role_id'=>4), 'fields'=>array('id', 'first_name', 'last_name')));
		$warehouse = $this->Warehouse->read();
		if(!$warehouse){
			throw new NotFoundException(__('Invalid warehouse'));
		}
		$this->loadModel('CurrentStock');
		
		$stocks = $this->CurrentStock->getStockStatus('Warehouse', $id);
		$this->set(compact('warehouse', 'stocks'));
	}
	
	/*
	 * Action : incentives 
	 * 
	 */
	public function incentives(){
		//$this->gradPermission(2);
		$conditions = array();
		$this->loadModel('WarehouseIncentive');
		$this->WarehouseIncentive->belongsTo = array(
						'Distributor' => array('className' => 'Distributor', 'foreignKey' => 'distributor_id', 'fields' => array('id', 'title'), 'type'=>'inner'), 
						'Brand' => array('className' => 'Brand', 'foreignKey' => 'brand_id', 'fields' => array('id', 'name'), 'type'=>'left'),
						'Warehouse' => array('className' => 'Warehouse', 'foreignKey' => 'warehouse_id', 'fields' => array('id', 'title'), 'type'=>'left'),
					);
		if (!empty($this->request->query['br']) ){
			$conditions['WarehouseIncentive.brand_id'] = $this->request->query['br'];
		}
		if (!empty($this->request->query['ds']) ){
			$conditions['WarehouseIncentive.distributor_id'] = $this->request->query['ds'];
		}
		if (!empty($this->request->query['wh']) ){
			$conditions['WarehouseIncentive.warehouse_id'] = $this->request->query['wh'];
		}
		
		$order=$this->paginate['order'] = array('WarehouseIncentive.incentive_date'=>'asc');

		$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->WarehouseIncentive->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		} else {
		   $incentives = $this->paginate('WarehouseIncentive', $conditions);
		}
		$this->set('incentives', $incentives);
		$this->_incentiveOptions();
		$this->set(compact('offset'));
		if(isset($this->request->query['export'])){   
			$this->set('filename', 'Warehouse_Incentive');
			$this->render('export_warehouseincentives','export_xls');
		}
	}
	
	/*
	 * Action : incentives 
	 * 
	 */
	public function add_incentives(){
	//	$set_var=$this->gradPermission(2);
		$this->loadModel('WarehouseIncentive');
		$this->loadModel('Sale');
		if ($this->request->data){
			$this->request->data['WarehouseIncentive']['user_id'] = $this->user['id'];
			
			$this->request->data['WarehouseIncentive']['cal_qty'] = $this->Sale->calQty($this->request->data['WarehouseIncentive']['brand_id'], $this->request->data['WarehouseIncentive']['unit'], $this->request->data['WarehouseIncentive']['quantity']);
			
			if (!empty($this->request->data['WarehouseIncentive']['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['WarehouseIncentive']['brand_id']))); 
				$this->request->data['WarehouseIncentive']['brand_group_id'] = $group_id[$this->request->data['WarehouseIncentive']['brand_id']]; 
			}
			
			$this->WarehouseIncentive->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'));
		//if($set_var){
			$this->render('update_insentives');
		//}
	}
	/*
	 * Action : update_incentives 
	 * 
	 */
	public function updateIncentive($id){
		$this->loadModel('Audit');		
		$this->roleBasePermission(array(SUPPORT));
		//$set_var=$this->gradPermission(2);
		
		$this->loadModel('WarehouseIncentive');
		$this->loadModel('Sale');
        $this->WarehouseIncentive->id = $id;
		$insentive = $this->WarehouseIncentive->read();
		$userData = $this->WarehouseIncentive->read(null, $id);
        if (!$insentive) {
            throw new NotFoundException(__('Invalid Incentive'));
        }else  if ($this->request->data){
			//$this->request->data['Incentive']['user_id'] = $this->user['id'];
			$this->request->data['WarehouseIncentive']['cal_qty'] = $this->Sale->calQty($this->request->data['WarehouseIncentive']['brand_id'], $this->request->data['WarehouseIncentive']['unit'], $this->request->data['WarehouseIncentive']['quantity']);
			
			if (!empty($this->request->data['WarehouseIncentive']['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['WarehouseIncentive']['brand_id']))); 
				$this->request->data['WarehouseIncentive']['brand_group_id'] = $group_id[$this->request->data['WarehouseIncentive']['brand_id']]; 
			}
			
			$this->WarehouseIncentive->save($this->request->data);
			$this->Audit->saveDeletedData($userData['WarehouseIncentive']['id'], 'WarehouseIncentive', $this->Auth->user('id') , serialize($userData),'Warehouse Incentive Has been updated', STATUS_EDIT);
			$this->Session->setFlash(__('Incentive updated succesfully'));
			
			
			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'));
		//if($set_var){
		$this->render('update_insentives');
		//}
	}
	public function deleteIncentive($id){
		//$this->gradPermission(2);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('WarehouseIncentive');
		$this->WarehouseIncentive->id = $id;
        if (!$this->WarehouseIncentive->exists()) {
            throw new NotFoundException(__('Invalid incentive'));
        }
		$insentive = $this->WarehouseIncentive->read();
		$data = array();
		$data['serialize'] = serialize($insentive);//pr($data['serialize']);die();
		$data['model_id'] = $insentive['WarehouseIncentive']['id'];
        if ($this->WarehouseIncentive->delete()) {
			$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'WarehouseIncentive', $this->Auth->user('id') , $data['serialize'],'Warehouse 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 deleteAllWarehouseIncentive(){
		
		//$this->gradPermission(2);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('WarehouseIncentive');
		        		
        if(!empty($this->request->data['deleteAllValue'])){
			$this->WarehouseIncentive->deleteAll(array('WarehouseIncentive.id'=>explode(",", $this->request->data['deleteAllValue'])) );
            $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 _incentiveOptions(){
		$this->loadModel('Distributor');
		$this->loadModel('Brand');
		
		
		$distributors = $this->Distributor->getList();
		$warehouses = $this->Warehouse->getList();
		$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 = expence_types();
		$this->set( compact('distributors','brands', 'brandList','expence_types', 'warehouses') );
	}
	
	
 }