<?php
App::uses('AppController', 'Controller');
class StocksController extends AppController {
/**
 * Controller Warehouse
 *
 * @var string
 */
 
 	/**
     * index method
     * @params : $data (array)
     * @return none
     */
	public function index(){
		//$this->gradPermission(2);
		$conditions = array(); //array('Stock.status !=' => DELETED);;
		
		/* if ( !empty($this->request->query['br'])){
			$conditions['Stock.brand_id'] = $this->request->query['br'];
		} */
		if ( !empty($this->request->query['br'])){
			$conditions['Stock.brand_group_id'] = $this->request->query['br'];
		}
		if ( !empty($this->request->query['pt'])){
			$conditions['Stock.pack_type'] = $this->request->query['pt'];
		}
		if ( !empty($this->request->query['srg'])){
			if(!empty($this->request->query['st'])){
			    if($this->request->query['st'] == 'Depot'){
			        $conditions['Depot1.region_id'] = $this->request->query['srg'];
			    }elseif($this->request->query['st'] == 'Warehouse'){
			        $conditions['Warehouse1.region_id'] = $this->request->query['srg'];
			    }
			}
		}
		if ( !empty($this->request->query['drg'])){
		    if(!empty($this->request->query['dt'])){
			    if($this->request->query['dt'] == 'Depot'){
			        $conditions['Depot2.region_id'] = $this->request->query['drg'];
			    }elseif($this->request->query['dt'] == 'Subdepot'){
			        $conditions['Warehouse1.region_id'] = $this->request->query['drg'];
			    }
			}
		}
		if ( !empty($this->request->query['swd'])){
			$conditions['Stock.source_id'] = $this->request->query['swd'];
		}

		if ( !empty($this->request->query['dwd'])){
			$conditions['Stock.destination_id'] = $this->request->query['dwd'];
		}
		if ( !empty($this->request->query['st'])){
			$conditions['Stock.source_entity'] = $this->request->query['st'];
		}
		if ( !empty($this->request->query['dt'])){
			$conditions['Stock.destination_entity'] = $this->request->query['dt'];
		}
		//Dispatch date conditions
		if ( !empty($this->request->query['dfrom']) && !empty($this->request->query['dto'])){
			$conditions[] = array('Stock.dispatch_date BETWEEN ? AND ?' => array($this->request->query['dfrom'], $this->request->query['dto']));
		}elseif (!empty($this->request->query['dfrom'])){
			$conditions['Stock.dispatch_date >= '] = $this->request->query['dfrom'];
		} elseif (!empty($this->request->query['dto'])){
			$conditions['Stock.dispatch_date <= '] = $this->request->query['dto'];
		}

		//Recieved date conditions
		if ( !empty($this->request->query['rfrom']) && !empty($this->request->query['rto'])){
			$conditions[] = array('Stock.stock_date BETWEEN ? AND ?' => array($this->request->query['rfrom'], $this->request->query['rto']));
		}elseif (!empty($this->request->query['rfrom'])){
			$conditions['Stock.stock_date >= '] = $this->request->query['rfrom'];
		} elseif (!empty($this->request->query['rto'])){
			$conditions['Stock.stock_date <= '] = $this->request->query['rto'];
		}

		$order=$this->paginate['order'] = array('Stock.id' => '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();		
			$stocks = $this->Stock->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
  		} else {
		    $stocks = $this->paginate('Stock', $conditions);
		}
	
		$this->set(compact('stocks','offset'));
		$this->_options();

		if(isset($this->request->query['export'])){  
			$this->set('filename', 'Stock');
			$this->render('export_stock','export_xls');
		}
	}
	/**
     * add method
     * 
     * @return none
     */
	public function add(){
	//	$this->gradPermission(2);
		if($this->request->data){
			$this->request->data['Stock']['user_id'] = $this->Auth->user('id');
			$this->request->data['Stock']['cal_qty'] = $this->request->data['Stock']['quantity'];
			
			if (!empty($this->request->data['Stock']['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['Stock']['brand_id']))); 
				$this->request->data['Stock']['brand_group_id'] = $group_id[$this->request->data['Stock']['brand_id']]; 
				}
			if ($this->Stock->save($this->request->data)){
				
				
				
				$sdata = $this->request->data['Stock'];
				
				$this->Stock->updateStockStatus($this->request->data['Stock']);
				$this->Session->setFlash(__('Stock added successfully'));
				if (isset($this->request->data['addmore'])){
					$this->redirect(array('action' => 'add'));
				}else{
					$this->redirect(array('action' => 'index'));
				}
			}
		}
		$this->_options();
	}
	/**
     * edit method
     * @params : $id (int)
     * @return none
     */
	public function edit($id){
		$this->loadModel('Audit');
		$this->roleBasePermission(array(SUPPORT));
		$userData = $this->Stock->read(null, $id);
	//	$this->gradPermission(2);
		$this->Stock->id = $id;
		$stock = $this->Stock->read();
        if ( !$stock ) {
            throw new NotFoundException(__('Invalid request'));
        }
		if($this->request->data){
			$this->request->data['Stock']['user_id'] = $this->Auth->user('id');
			$this->request->data['Stock']['cal_qty'] = $this->request->data['Stock']['quantity'];
			
			if (!empty($this->request->data['Stock']['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['Stock']['brand_id']))); 
				$this->request->data['Stock']['brand_group_id'] = $group_id[$this->request->data['Stock']['brand_id']]; 
				}
				
			if ($this->Stock->save($this->request->data)){
				
				
				$stock['Stock']['quantity'] = $this->request->data['Stock']['quantity'];
				$stock['Stock']['old_qty'] = $this->request->data['Stock']['old_qty'];
				$this->Stock->updateStockStatus($stock['Stock']);
				$this->Audit->saveDeletedData($userData['Stock']['id'], 'Stock', $this->Auth->user('id') , serialize($userData),'Stock Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Stock added successfully'));
				$this->redirect(array('action'=>'index'));
			}
		}
		//else{
			
			//pr($stock);
			$this->request->data = $stock;
			
			if($stock['Stock']['source_entity'] == 'Warehouse'){
				$this->request->data['Stock']['src_region_id'] = $stock['Warehouse1']['region_id'];
			}elseif($stock['Stock']['source_entity'] == 'Depot'){
				$this->request->data['Stock']['src_region_id'] = $stock['Depot1']['region_id'];
			}
			
			if($stock['Stock']['destination_entity'] == 'Warehouse'){
				$this->request->data['Stock']['dest_region_id'] = $stock['Warehouse2']['region_id'];
			}elseif($stock['Stock']['destination_entity'] == 'Depot'){
				$this->request->data['Stock']['dest_region_id'] = $stock['Depot2']['region_id'];
			}
			
			
		//}
		$this->_options();
	}
	
	function _options(){
		$this->loadModel('Region');
		$this->loadModel('Brand');
		$this->loadModel('BrandGroup');
		$brands = $this->Brand->find('list');
		$brand_groups = $this->BrandGroup->find('list');
		$regions = $this->Region->find('list');
		
		$sourceType = array('Factory'=>'Factory', 'Warehouse'=>'Warehouse', 'Depot'=>'Depot', 'Distributor'=>'Distributor');
		$destType = array('Factory'=>'Factory', 'Warehouse'=>'Warehouse', 'Depot'=>'Depot', 'Distributor'=>'Distributor');
		
		$this->set(compact('sourceType', 'destType', 'brands', 'brand_groups', 'regions'));
	}
	/**
     * delete method
     * @params : $id (int)
     * @return none
     */
	public function delete($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Stock->id = $id;
        if (!$this->Stock->exists()) {
            throw new NotFoundException(__('Invalid stock entry'));
        }
		$stock = $this->Stock->read();

		$data = array();
		$data['serialize'] = serialize($stock);//pr($data['serialize']);die();
		$data['model_id'] = $stock['Stock']['id'];
        if ($this->Stock->delete()) {
			$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Stock', $this->Auth->user('id') , $data['serialize'],'Stock Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Stock was deleted successfully'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Stock was not deleted'));
        $this->redirect(array('action' => 'index'));
	}
	
	public function deleteAllStocks(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Stock->deleteAll(array('Stock.id'=>explode(",", $this->request->data['deleteAllValue'])) );
		
			$this->Session->setFlash(__('All selected stock movement was deleted successfully'));
			$this->redirect(array('action' => 'index'));
		}
	}
	
	public function getModelOptions(){  
		$result = array();
		
		/* $this->request->data['reModel'] = 'Depot';
		$this->request->data['division'] = 2; */
		
		
		if (!empty($this->request->data['reModel'])){
			$model = $this->request->data['reModel'];
			$this->loadModel($model);
			$conditions = array();
			if (!empty($this->request->data['region'])){
				$regionId = $this->request->data['region'];
			}else{
				$regionId = 0;
			}
			if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setsel'){
                $emptOpt = $coption = $uoption = array();
            }else {
                $emptOpt = array('0' => __('All %ss', array(strtolower($model))));
				$coption = array("0"=>__('All Customers'));
				$uoption = array("0"=>__('All User'));
            }
			
			
			$modelListOpt = array();
			
			if($model == 'Depot' && $regionId == 0){
				if(!empty($this->request->data['division'])){
					$this->loadModel('DivisionsRegion');
					$rIds = $this->DivisionsRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$this->request->data['division'])));
				
				
					$modelListOpt = $this->Depot->find('list', array('conditions'=>array('region_id'=>$rIds ), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc'))); 
				}else{
					$modelListOpt = $this->Depot->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc'))); 
				}
				
			}else{
				$modelListOpt = $this->$model->getList($regionId);
			}
			
			$modelList = $emptOpt + $modelListOpt;
			if($model == 'Depot' && !empty($this->request->data['route']) ){
				$this->loadModel('Route');
				if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setsel'){
                    $eoption = array();
                }else {
					$eoption = array("0"=>__('All routes'));
				}
				$routes = $this->Route->find('list', array('conditions'=>array('region_id'=>$regionId), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
				$result['routes'] =  $eoption + $routes ;
			}
			if (!empty($this->request->data['getCust'])){
				$this->loadModel('Customer');
				$customers = $this->Customer->find('list', array('conditions'=>array('region_id'=>$this->request->data['region']), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc'))); 
				$result['customers'] = $coption + $customers;	
			}
			
			if (!empty($this->request->data['getUser'])){
				$this->loadModel('User');
				//$users = $this->User->find('list', array('conditions'=>array('region_id'=>$this->request->data['region']), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc'))); 
				
				$this->User->unbindAllModels();				
				$this->User->bindModel(array('belongsTo' => array('Role' => array('className' => 'Role'))));
				
				$userlist = $this->User->find('all', array('fields' => array('User.id', 'User.name', 'Role.name'), 'conditions'=>array('User.status'=>ACTIVE, 'User.region_id'=>$this->request->data['region']), 'order'=>array('User.name'=>'asc')));

				if($userlist){
					foreach($userlist as $user){
						$users[$user['User']['id']] = $user['User']['name'].' ('.$user['Role']['name'].')';
					}
				}
				
				
				$result['users'] = $uoption + $users;	
			}
			
			//pr($modelList);
			$result['label'] = $model;
			$result['options'] = $modelList;
			
		}
		
		$this->set('result', $result);
	}
	
	/**
     * report method
     * @params : $opt (string)
     * @return none
     */
	public function report($opt=''){
		$this->set('opt', ucwords($opt));
		
		if ($opt == 'depots'){
			$this->_depotReport();
		}else if($opt == 'warehouse') {
			$this->_warehouseReport();
		}else{
		}
	}
	
	function _depotReport(){
		$this->loadModel('Depot');
		$this->loadModel('Region');
		
		
		$conditions = array();
		if (!empty($this->request->query['q']) ){
			$conditions['Depot.title LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		
		if (!empty($this->request->query['rg']) ){
			$conditions['Depot.region_id'] = $this->request->query['rg'];
		}
		
		$this->paginate['order'] = array('Depot.title' => 'asc');
		$depots = $this->paginate('Depot', $conditions);
		$depoIds = array();
		$this->Stock->associateCurrentStock($depots, 'Depot');
		$this->set('depots', $depots);
		
		
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$this->set(compact('regions'));
		
		$this->render('depotReport');
	}
	
	function _warehouseReport(){
		$this->loadModel('Warehouse');
		$this->loadModel('Region');
		
		$conditions = array();
		if (!empty($this->request->query['q']) ){
			$conditions['Warehouse.title LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		
		if (!empty($this->request->query['rg']) ){
			$conditions['Warehouse.region_id'] = $this->request->query['rg'];
		}
		
		$this->paginate['order'] = array('Warehouse.title' => 'asc');
		$warehouses = $this->paginate('Warehouse', $conditions);
		$depoIds = array();
		$this->Stock->associateCurrentStock($warehouses, 'Warehouse');
				
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$this->set(compact('warehouses', 'regions'));
		
		$this->render('warehouseReport');
	}
	
	function syncronize($act = ''){
	
	}
	
	function depotStock($depot_id=0){
		$this->loadModel('Depot');
		$this->loadModel('Brand');
		$depots = array();
		$depot = $this->Depot->findById($depot_id);
		$depots[] = $depot;
		$brandAll = $brands = array();
		$brandList = $this->Brand->find('all');
		foreach($brandList as $br){
			$brands[$br['Brand']['id']] = $br['Brand']['name'];
			$brandAll[$br['Brand']['id']] = $br['Brand'];
		}
		$type = 'daily';
		$date = isset($opt)?$opt:date('Y-m-d');
		$strtotime = strtotime($date);
		$prev = date('Y-m-d', strtotime('-1 day', $strtotime) );
		$next = date('Y-m-d', strtotime('+1 day', $strtotime) );
		$current = date('M d, Y', $strtotime);
		
		
		$depotCal = $this->Depot->depotReportCal($depot_id, $date);
		//pr($depotCal);
		$this->Stock->depotStock($depots, compact('type','opt', 'date', 'prev', 'next', 'current', 'strtotime','query'));
		$this->set(compact('depots','depoList', 'brands', 'depotCal', 'brandAll'));
		
		$this->set('depots', $depots);
	}
	
}
