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

/**
 * Controller name
 *
 * @var string
 */
	function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow(array('getLgaOptions'));
	}
	var $components = array('Option');
	public function index(){
	    
		//$this->gradPermission(2);
		$this->Region->belongsTo  = array(
					'LgArea' => array('className' => 'LgArea', 'foreignKey' => 'lg_area_id'),
					'State' => array('className' => 'State', 'foreignKey' => 'state_id'));
		$conditions = array();
		
		if (!empty($this->request->query['q']) ){
			$conditions['Region.title LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Region.state_id'] = $this->request->query['st'];
		}
		$order=$this->paginate['order'] = array('Region.title' => 'asc');
		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		/*if(isset($this->request->query['export'])){   			
			$regions = $this->Region->find('all', array('conditions' =>$conditions,'order'=>$order));
		} else {*/
		    $regions = $this->paginate('Region', $conditions);
		//}
		$this->set('regions', $regions);
		$this->loadModel('State');
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$this->set('states', $states);

		if(isset($this->request->query['export'])){
			$this->set('filename', 'Regions');
			$this->render('export_region','export_xls');
		}
	}
	
	public function add(){
		//$this->roleBasePermission(array(SUPPORT));
		//$this->gradPermission(2);
		if ($this->request->data){
			$is_exists = $this->Region->find('count', array('conditions'=>array('LOWER(title)'=>strtolower($this->request->data['Region']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Region']['title']));
			}else{
				$this->Region->save($this->request->data);
				$this->Session->setFlash(__('Region was added successfully'));
				$this->redirect('/region');
			}
		}
		$Opdata = isset($this->request->data['Region'] ) ? $this->request->data['Region']  : array();
		$this->Option->Options($Opdata, $this->user);
	}
	
	public function edit($id=0){
		$this->loadModel('Audit');
		$userData = $this->Region->read(null, $id);
		//$roledata=array(SUPPORT);
		//$this->roleBasePermission($roledata);
		//$set_var=$this->gradPermission(2);
		
		if ($this->request->data){
			$is_exists = $this->Region->find('count', array('conditions'=>array('LOWER(title)'=>strtolower($this->request->data['Region']['title']), 'id !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Region']['title']));
			}else{				
				$this->Region->save($this->request->data);
				$this->Audit->saveDeletedData($userData['Region']['id'], 'Region', $this->Auth->user('id') , serialize($userData),'Region Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Region was updated successfully'));
				$this->redirect('/region');
			}
		}
		
		if (!empty($id)){
			$this->Region->id = $id;
			$this->request->data = $this->Region->read();
		}
		$Opdata = isset($this->request->data['Region'] ) ? $this->request->data['Region']  : array();
		$this->Option->Options($Opdata, $this->user);
		//if($set_var){
		$this->render('add');
		//}
	}
	
	public function delete($id = 0){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		if(!$id){
			$this->redirect('/region');
		}
		
		$this->Region->id = $id;
		$region = $this->Region->read();
		$data = array();
		$data['serialize'] = serialize($region);
		$data['model_id'] = $region['Region']['id'];
		if($this->Region->delete()){
			$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Region', $this->Auth->user('id') , $data['serialize'],'Region Has been Deleted',STATUS_DELETE);
			$this->Session->setFlash(__('Region was deleted successfully'));
			$this->redirect('/region');
		}
	}
	
	public function regions($opt = '', $id=''){
		switch($opt){
			case 'add':
				$this->_addregion();
			break;
		}
	}
	function _addregion(){
		$this->render('addregion');
	}
	public function depots($opt = '', $id=''){
		//$this->gradPermission(3);
		$this->loadModel('Depot');
		$this->set('title_for_layout', 'Depots :: '.ucwords($opt));
		switch($opt){

			case 'add':
			case 'edit':			
		        //$this->roleBasePermission(array(SUPPORT));
				$this->_adddepot($id);
			break;
			case 'delete':
			//$this->gradPermission(2);
				if (!$this->request->is('post')) {
					throw new MethodNotAllowedException();
				}
				if(!$id){
					$this->redirect('/depots');
				}
				$this->Depot->id = $id;
				$depot = $this->Depot->read();
				$data = array();
				$data['serialize'] = serialize($depot);//pr($data['serialize']);die();
				$data['model_id'] = $depot['Depot']['id'];
				$this->Depot->delete();
				$this->loadModel('Audit');
					$this->Audit->saveDeletedData($data['model_id'], 'Depot', $this->Auth->user('id') , $data['serialize'],'Depot Has been Deleted',STATUS_DELETE);
				$this->Session->setFlash(__('Depot was deleted successfully'));
				$this->redirect('/depots');
			break;
			case 'view':
				$this->_viewDepot($id);
			break;
			default:
				$this->_depotList();
			break;
		}
	}
	function _depotList(){
		$this->loadModel('Depot');
		$this->Depot->belongsTo  = array('State' => array('className' => 'State', 'foreignKey' => 'state_id'), 'Region' => array('className' => 'Region', 'foreignKey' => 'region_id'));
		$conditions = array();
		if (!empty($this->request->query['q']) ){
			$conditions['Depot.title LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Depot.state_id'] = $this->request->query['st'];
		}
		if(!empty($this->request->query['dv'])){
            $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['Depot.region_id IN'] = $rIds;
        }else{
            $division_id = 0;
        }
		if (!empty($this->request->query['rg']) ){
			$conditions['Depot.region_id'] = $this->request->query['rg'];
		}
		$order=$this->paginate['order'] = array('Depot.title' => 'asc');
		$this->_viewRoleCoditions($conditions);

		$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();		
			$depots = $this->Depot->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));

			
		} else {
		    $depots = $this->paginate('Depot', $conditions);
		}
		$this->set('depots', $depots);
		$this->loadModel('State');
		$this->loadModel('Division');
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$divisions = $this->Division->getList();
        $regions = $this->Region->getList();
		$this->set(compact('offset','states', 'divisions','regions'));

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

	function _adddepot($id = 0){
		$this->loadModel('Audit');
		$userData = $this->Depot->read(null, $id);
		//$is_allow=$this->gradPermission(1);
		if ($this->request->data){
			if ($id){
				$conditions = array('LOWER(Depot.title)'=>strtolower($this->request->data['Depot']['title']), 'Depot.id !=' => $id);
				$saveStatus = 'updated';
			}else{
				$conditions = array('LOWER(Depot.title)'=>strtolower($this->request->data['Depot']['title']));
				$saveStatus = 'added';
			}
			$is_exists = $this->Depot->find('count', array('conditions'=>$conditions));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Depot']['title']));
			}else{
				if($id){
					$check = $this->_region_user_customers($this->request->data);
				}else{
					$check = true;
				}
				if($check){
					if(@$this->request->data['data']){
						$this->request->data['Depot']['opening_stocks'] = serialize($this->request->data['data']['opening_stocks']);
						$this->request->data['Depot']['opening_data'] = serialize($this->request->data['data']);
					}
					$this->Depot->save($this->request->data);
					if ($id){
						$conditions = array('LOWER(Depot.title)'=>strtolower($this->request->data['Depot']['title']), 'Depot.id !=' => $id);
						
						$this->Audit->saveDeletedData($userData['Depot']['id'], 'Depot', $this->Auth->user('id') , serialize($userData),'Depot Has been updated', STATUS_EDIT);
					}
					$this->Session->setFlash(__('Depot was %s successfully', $saveStatus));
					$this->redirect('/depots');
				}else{
					$this->set('continue', true);
				}
				
			}
		}else if ($id){
			$this->Depot->id = $id;
			$this->request->data = $this->Depot->read();
			
			if ($this->request->data['Depot']['opening_stocks']){
				$this->request->data['data']['opening_stocks'] = unserialize($this->request->data['Depot']['opening_stocks']);
				
			}
			if ($this->request->data['Depot']['opening_data']){
				$this->request->data['data'] = unserialize($this->request->data['Depot']['opening_data']);
			}
		}
		
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$this->loadModel('State');
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->loadModel('BrandGroup');
		$brandGroups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->set(compact('regions', 'states','brands', 'brandGroups'));
		//if($is_allow){
			$this->render('adddepot');
		//}
	}
	
	function _region_user_customers($data){
		
		if($data['Depot']['region_id'] == $data['Depot']['old_rid'] ){
			return true;
		}else{
			if ( isset($data['cancel']) ){
				$this->redirect(array('controller'=>'region', 'action'=>'depots', 'edit', $data['Depot']['id']));
			} else {
				
				//Get users and customers
				$this->loadModel('User');
				$this->loadModel('Customer');
				$this->User->unbindModelAll();
				$this->Customer->unbindModelAll();
				$users = $this->User->find('all', array('fields'=>array('id', 'first_name', 'last_name'), 'conditions'=>array('User.region_id'=>$data['Depot']['old_rid'], 'User.depot_id'=>$data['Depot']['id'] ) ));
				$customers = $this->Customer->find('all', array('fields'=>array('id', 'first_name', 'last_name'), 'conditions'=>array('Customer.region_id'=>$data['Depot']['old_rid'], 'Customer.depot_id'=>$data['Depot']['id'] ) ));
				if (isset($data['continue'])){
					$this->loadModel('DepotregionUpdatedCustomer');
					$this->loadModel('DepotregionUpdatedUser');
					$this->DepotregionUpdatedCustomer->primaryKey = false;
					$this->DepotregionUpdatedUser->primaryKey = false;
					
					if($users){
						$user_region_map = array();
						foreach($users as $user){
							$user_region_map[] = array('region_id'=>$data['Depot']['old_rid'], 'new_region_id'=>$data['Depot']['region_id'], 'user_id'=>$user['User']['id']);
						}
						@$this->DepotregionUpdatedUser->saveAll($user_region_map);
						$this->User->updateAll(array('User.region_id'=>$data['Depot']['region_id']), array('User.region_id'=>$data['Depot']['old_rid'],'User.depot_id' => $data['Depot']['id']));
					}
					if($customers){
						$customer_region_map = array();
						foreach($customers as $customer){
							$customer_region_map[] = array('region_id'=>$data['Depot']['old_rid'], 'new_region_id'=>$data['Depot']['region_id'], 'customer_id'=>$customer['Customer']['id'] );
						}
						@$this->DepotregionUpdatedCustomer->saveAll($customer_region_map);
						
						$this->Customer->updateAll(array('Customer.region_id'=>$data['Depot']['region_id']), array('Customer.region_id'=>$data['Depot']['old_rid'],'Customer.depot_id' => $data['Depot']['id']));
					}
					
					return true;
				}else{
					$this->set(compact('users', 'customers'));
					return false;
				}
				
			}
		}
	}
	public function stocks() {

	}
	
	public function states(){
		//$this->gradPermission(2);
		$this->loadModel('State');
		$order=$this->paginate['order'] = array('State.state' => '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();		
			$states = $this->State->find('all',array('order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
		} else {
		        $states = $this->paginate('State');
		}
		$this->set('states', $states);
		$this->set(compact('offset'));
       if(isset($this->request->query['export'])){   
       		$this->set('filename', 'States');	 
			$this->render('export_state','export_xls');
		}
	}
	 function export_state() {
		$this->loadModel('State');
		$states =$this->State->find('all', $conditions,array('State.state' => 'asc'));
		$this->set('states', $states);
		$this->set('filename', 'States');
		$this->render('export_state','export_xls');
	}
	
	public function addstate(){ 
	  
		//$this->roleBasePermission(array(SUPPORT));
		//$is_allow = $this->gradPermission(1);
		$this->loadModel('State');
		if ($this->request->data){
			$is_exists = $this->State->find('count', array('conditions'=>array('LOWER(state)'=>strtolower($this->request->data['State']['state']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['State']['state']));
			}else{
				$this->State->save($this->request->data);
				$this->Session->setFlash(__('State was added successfully'));
				$this->redirect('/region/states');
			}
		}
		//if ($is_allow){
			$this->render('updatestate');
		//}
	}
	public function updatestate($state_id){
		$this->loadModel('Audit');
		//$this->roleBasePermission(array(SUPPORT));
		//$this->gradPermission(2);
		if(!$state_id){
			$this->redirect('/region/states');
		}
		$this->loadModel('State');
		if ($this->request->data){
			$is_exists = $this->State->find('count', array('conditions'=>array('LOWER(state)'=>strtolower($this->request->data['State']['state']), 'id !=' => $state_id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['State']['state']));
			}else{
				$userData = $this->State->read(null, $state_id);
				$this->State->save($this->request->data);
				$this->Audit->saveDeletedData($userData['State']['id'], 'State', $this->Auth->user('id') , serialize($userData),'State Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('State was updated successfully'));
				$this->redirect('/region/states');
			}
		}
		$this->State->id = $state_id;
		$this->request->data = $this->State->read();
	}
	
	public function deletestate($state_id){
		//$this->gradPermission(2);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		if(!$state_id){
			$this->redirect('/region/states');
		}
		$this->loadModel('State');
		$this->State->id = $state_id;
		
		$state = $this->State->read();
		$data['serialize'] = serialize($state);
		$data['model_id'] = $state['State']['id'];
		$this->request->data = $this->State->delete();
		$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'State', $this->Auth->user('id') , $data['serialize'],'State Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('State was deleted successfully'));
		$this->redirect('/region/states');
	}
	
	public function lga($op = '', $id = ''){
		//$this->gradPermission(2);
		$this->loadModel('LgArea');
		$this->loadModel('State');
		$states = $this->State->find('list', array('fields'=>array('id', 'state'), 'order'=>array('state'=>'asc')));
		$this->set('states', $states);
		switch ($op){
			case 'add':
			    //$this->roleBasePermission(array(SUPPORT));
				$this->_updateLga();
			break;
			
			case 'edit':
				//$roledata=array(SUPPORT);
				//$this->roleBasePermission($roledata);
				$this->_updateLga($id);
			break;
			
			case 'delete':
				if (!$this->request->is('post')) {
					throw new MethodNotAllowedException();
				}
				$this->_deleteLga($id);
			break;
			
			default:
				$this->LgArea->belongsTo  = array('State' => array('className' => 'State', 'foreignKey' => 'state_id'));
				$conditions = array();
				if (!empty($this->request->query['q']) ){
					$conditions['name LIKE'] =  '%'.$this->request->query['q'].'%';
				}
				if (!empty($this->request->query['st']) ){
					$conditions['state_id'] = $this->request->query['st'];
				}
				$order=$this->paginate['order'] = array('LgArea.name' => '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();		
					$lgAreas = $this->LgArea->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
				} else {
				    $lgAreas = $this->paginate('LgArea', $conditions);
				}
				$this->set('lgAreas', $lgAreas);
				$this->set(compact('offset'));
				if(isset($this->request->query['export'])){ 
					$this->set('filename', 'Lga');
					$this->render('export_lgareas','export_xls');
				}
			break;
		}
	}
	
	function _updateLga($id=0){
		$this->loadModel('Audit');
		$userData = $this->LgArea->read(null, $id);
		//$is_allow = $this->gradPermission(2);
		if ($this->request->data){
			if ($id){
				$conditions = array('LOWER(name)'=>strtolower($this->request->data['LgArea']['name']), 'id !=' => $id);
				$saveStatus = 'updated';
			}else{
				$conditions = array('LOWER(name)'=>strtolower($this->request->data['LgArea']['name']),'state_id'=>$this->request->data['LgArea']['state_id']);
				$saveStatus = 'added';
			}
			$is_exists = $this->LgArea->find('count', array('conditions'=>$conditions));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['LgArea']['name']));
			}else{
				$this->LgArea->save($this->request->data);
				if ($id){
				$conditions = array('LOWER(name)'=>strtolower($this->request->data['LgArea']['name']), 'id !=' => $id);
				$this->Audit->saveDeletedData($userData['LgArea']['id'], 'LgArea', $this->Auth->user('id') , serialize($userData),'LGA Has been updated', STATUS_EDIT);
				}
				$this->Session->setFlash(__('LGA was %s successfully', $saveStatus));
				$this->redirect('/region/lga');
			}
		}
		if ($id){
			$this->LgArea->id = $id;
			$this->request->data = $this->LgArea->read();
		}
		//if ($is_allow){
			$this->render('updateLga');
		//}
		
		
	}
	
	function _deleteLga($id){
		if(!$id){
			$this->redirect('/region/lga');
		}
		$data = array();
		$this->LgArea->id = $id;
		$lgarea = $this->LgArea->read();
		$data['serialize'] = serialize($lgarea);
		$data['model_id'] = $lgarea['LgArea']['id'];
		$this->LgArea->delete();
		$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'LgArea', $this->Auth->user('id') , $data['serialize'],'LGA Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('LGA was deleted successfully'));
		$this->redirect('/region/lga');
		
	}
	
	function _viewDepot($id){
		$this->Depot->id = $id;
		$this->Depot->hasOne = array('User'=>array('className'=>'User', 'foreignKey'=>'depot_id', 'conditions'=>array('User.role_id'=>4), 'fields'=>array('id', 'first_name', 'last_name')));
		$depot = $this->Depot->read();
		if(!$depot){
			throw new NotFoundException(__('Invalid Depot'));
		}
		$this->loadModel('CurrentStock');
		
		$stocks = $this->CurrentStock->getStockStatus('Depot', $id);
		$this->set(compact('depot', 'stocks'));
		$this->render('viewDepot');
	}
	
	public function getLgaOptions(){
		$result = array();
		
		$this->loadModel('LgArea');
		
		$conditions = array();
		if (!empty($this->request->data['state'])){
			$conditions['state_id'] = $this->request->data['state'];
		}
		
		$emptOpt = array('0'=>__('All LGA'));
		$lgaOptions = $this->LgArea->find('list', array('fields'=>array('id', 'name'), 'conditions'=>$conditions,'order'=>array('name'=>'asc')));
		$modelList = $emptOpt + $lgaOptions;
		$result['options'] = $modelList;
		echo json_encode($result);
		exit;
	}
	
	function _viewRoleCoditions(&$conditions){
		 $this->user = $this->Auth->user();
		switch($this->user['Role']['grade']){
			
			case 3:
				$conditions['Depot.region_id'] =  $this->user['region_id'] ;
			break;
			case 4:
				$conditions['Depot.id'] = $this->user['depot_id'];
			break;
			
			
		}
	}

	public function deleteAllRegion(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
	
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Region->deleteAll(array('Region.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Region was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}

	public function deleteAllDepots(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
	
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Depot->deleteAll(array('Depot.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Depot was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	/* public function getUser(){
		$this->loadModel('User');
		$result = $users = $list = array();
		$eoption = array("0"=>__('All Users'));
		if (!empty($this->request->data['depot'])){
			
			$users = $this->User->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot'], 'status'=>ACTIVE), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc')));
		}

		$result['users'] = $eoption + $users;
		echo json_encode($result);
		exit;
	} */
	
	public function getUser(){ 
		$this->loadModel('User');
		$result = $users = $list = array();
		$eoption = array("0"=>__('All Users'));
		
		$conditions['status'] = ACTIVE;
		
		if (!empty($this->request->data['region'])){
			$conditions['region_id'] = $this->request->data['region'];			
		}
		
		if (!empty($this->request->data['depot'])){
			$conditions['depot_id'] = $this->request->data['depot'];			
		}
		
		if (!empty($this->request->data['roleId'])){
			$conditions['role_id'] = $this->request->data['roleId'];			
		}
		
		if (!empty($this->request->data['verified'])){
			if ($this->request->data['verified'] == 1){
				$this->loadModel('Role');
				$roleIds = $this->Role->find('list', array('fields'=>array('id'), 'conditions'=>array('grade <=' => 3)));
				$conditions['role_id'] = $roleIds;			
		}}
		//pr($conditions);
		//$users = $this->User->find('list', array('conditions'=>$conditions, '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'=>$conditions, 'order'=>array('User.name'=>'asc')));

		if($userlist){
			foreach($userlist as $user){
				$users[$user['User']['id']] = $user['User']['name'].' ('.$user['Role']['name'].')';
			}
		}

		$result['users'] = $eoption + $users;
		
		echo json_encode($result);
		exit;
	}
	
	public function getCustomer(){
		$this->loadModel('Customer');
		$result = $customers = $list = array();
		$eoption = array("0"=>__('Select Customer'));
		if (!empty($this->request->data['depot'])){
			
			$customers = $this->Customer->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot'], 'status'=>ACTIVE), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc')));
		}

		$result['customers'] = $eoption + $customers;
		echo json_encode($result);
		exit;
	}
	
		/**
  	 *	Sub - Depots
  	 *
  	 *
  	 */

  	public function subdepots(){
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$this->loadModel('Subdepot');
		$conditions = array();
		$this->Subdepot->belongsTo  = array(		
			'Region' => array('className' => 'Region', 'foreignKey' => 'region_id', 'fields' => array('id', 'title'), 'type'=>'left'),'Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('id', 'title'), 'type'=>'left'));
		if (!empty($this->request->query['q']) ){
			$conditions['LOWER(Subdepot.title) LIKE'] =  '%'.strtolower($this->request->query['q']).'%';
		}
		
		if ( !empty($this->request->query['rg'])){
			$conditions['Subdepot.region_id'] = $this->request->query['rg'];
		}
		if ( !empty($this->request->query['dp'])){
			$conditions['Subdepot.depot_id'] = $this->request->query['dp'];
		}
		$order = $this->paginate['order'] = array('Subdepot.title' => 'asc');
		$this->_options();
		if (!empty($this->request->query['rg'])){
			$region_id = $this->request->query['rg'];
		}else{
			$region_id = 0;
		}
		$regions = $this->Region->getList();
		$depots = $this->Depot->getList($region_id);
		$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();		
			$subdepots = $this->Subdepot->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
			$this->set('subdepots', $subdepots);
			$this->set('filename', 'Subdepots');
			$this->set(compact('offset'));
			$this->render('export_subdepot','export_xls');
		} else {
		    $subdepots = $this->paginate('Subdepot', $conditions);
		}
		$this->set('subdepots', $subdepots);
		$this->set(compact('regions', 'depots'));
	}
	
	public function add_sub_depot(){
		$this->loadModel('Subdepot');
		if ($this->request->data){ //pr($this->request->data);die();
			$is_exists = $this->Subdepot->find('count', array('conditions'=>array('LOWER(Subdepot.title)'=>strtolower($this->request->data['Subdepot']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Subdepot']['title']));
			}else{
				if(@$this->request->data['data']){
					$this->request->data['Subdepot']['opening_stocks'] = serialize($this->request->data['data']['opening_stocks']);
					$this->request->data['Subdepot']['opening_data'] = serialize($this->request->data['data']);
				}
				$this->Subdepot->save($this->request->data);
				$this->Session->setFlash(__('Subdepot was added successfully'));
				$this->redirect(array('action'=>'subdepots'));
			}
		}
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->loadModel('BrandGroup');
		$brandGroups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->set(compact('brands','brandGroups'));
		$this->_options();
		//$this->loadModel('State');
	}
	
	public function edit_sub_depot($id=0){
		$this->loadModel('Subdepot');
		$this->loadModel('Audit');
		if (!empty($id)){
		   $this->Subdepot->id = $id;
		   $SubdepotData = $this->Subdepot->find('first', array('conditions'=>array('md5(Subdepot.id)'=>$id)));
		  // pr($SubdepotData);die();
		  }
		if ($this->request->data){
			$is_exists = $this->Subdepot->find('count', array('conditions'=>array('LOWER(Subdepot.title)'=>strtolower($this->request->data['Subdepot']['title']), 'md5(Subdepot.id) !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Subdepot']['title']));
			}else{ 
				if(@$this->request->data['data']){
					$this->request->data['Subdepot']['opening_stocks'] = serialize($this->request->data['data']['opening_stocks']);
					$this->request->data['Subdepot']['opening_data'] = serialize($this->request->data['data']);
				}
				if($this->Subdepot->save($this->request->data)){
					 $this->Audit->saveDeletedData($SubdepotData['Subdepot']['id'], 'Subdepot', $this->Auth->user('id') , serialize($SubdepotData),'Subdepot Has been updated', STATUS_EDIT);
					}
				$this->Session->setFlash(__('Subdepot was updated successfully'));
				$this->redirect(array('action'=>'subdepots'));
			}
		}
		
		if (!empty($id)){
			$this->Subdepot->id = $id;
			$this->request->data = $this->Subdepot->find('first', array('conditions'=>array('md5(Subdepot.id)'=>$id)));
			if ($this->request->data['Subdepot']['opening_stocks']){
				$this->request->data['data']['opening_stocks'] = unserialize($this->request->data['Subdepot']['opening_stocks']);
				
			}
			if ($this->request->data['Subdepot']['opening_data']){
				$this->request->data['data'] = unserialize($this->request->data['Subdepot']['opening_data']);
			}
		}
		$this->_options();
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->loadModel('BrandGroup');
		$brandGroups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		
		$this->set(compact('brands','brandGroups'));
		
		$this->render('add_sub_depot');
	}
	function _options(){		
		$Opdata = isset($this->request->data['Subdepot'] ) ? $this->request->data['Subdepot']  : array(); 
		$this->Option->Options($Opdata, $this->user);
	}
	
	public function delete_subdepots($id){
		$this->loadModel('Subdepot');
		$this->loadModel('Audit');
		if(!$id){
			$this->redirect(array('action'=>'subdepots'));
		}
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$data = array();
			$Subdepot = $this->Subdepot->find('first', array('conditions'=>array('md5(Subdepot.id)'=>$id)));
			$data['serialize'] = serialize($Subdepot);//pr($data['serialize']);die();
			$data['model_id'] = $Subdepot['Subdepot']['id'];
		if($id){
			$this->Subdepot->deleteAll(array('md5(Subdepot.id)'=>$id));
			$this->Audit->saveDeletedData($data['model_id'], 'Subdepot', $this->Auth->user('id') , $data['serialize'],'Subdepot Has been Deleted', STATUS_DELETE);
			$this->Session->setFlash(__('Subdepot was deleted successfully'));
			$this->redirect(array('action'=>'subdepots'));
		}
		
		
	}

	public function getSubdepot(){
		
		$result = $subdepots = $customers = array();
		
		
		if (!empty($this->request->data['depot'])){
			
			
			
			if (!empty($this->request->data['getSubdepot'])){
				$eoption = array("0"=>__('All Subdepots'));
				$this->loadModel('Subdepot');
				$subdepots = $this->Subdepot->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot']), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
				$result['subdepots'] = $eoption + $subdepots; 
			}
			
			if (!empty($this->request->data['getCust'])){
				$coption = array("0"=>__('All Customers'));
				$this->loadModel('Customer');
				$customers = $this->Customer->find('list', array('conditions'=>array('depot_id'=>$this->request->data['depot']), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc'))); 
				$result['customers'] = $coption + $customers;	
			} 
		}
		
		echo json_encode($result);
		exit;
	}
	
	/**
  	 *	Divisions
  	 *
  	 *
  	 */

  	public function divisions($opt = '', $id=''){
		//$this->gradPermission(3);
		$this->loadModel('Division');
		$this->set('title_for_layout', 'Divisions :: '.ucwords($opt));
		switch($opt){

			case 'add':
			case 'edit':			
		        //$this->roleBasePermission(array(SUPPORT));
				$this->_update_division($id);
			break;
			case 'delete':
			//$this->gradPermission(2);
				if (!$this->request->is('post')) {
					throw new MethodNotAllowedException();
				}
				if(!$id){
					$this->redirect('/divisions');
				}
				$this->Division->id = $id;
				$divison = $this->Division->read();
				$data = array();
				$data['serialize'] = serialize($divison);//pr($data['serialize']);die();
				$data['model_id'] = $divison['Division']['id'];
				$this->Division->delete();
				
				$this->loadModel('DivisionsDepot');
				$this->DivisionsDepot->deleteAll(array('division_id'=>$id), false);
				
				
				$this->loadModel('DivisionsRegion');
				$this->DivisionsRegion->deleteAll(array('division_id'=>$id), false);
				
				$this->loadModel('Audit');
					$this->Audit->saveDeletedData($data['model_id'], 'Division', $this->Auth->user('id') , $data['serialize'],'Division Has been Deleted',STATUS_DELETE);
				$this->Session->setFlash(__('Division was deleted successfully'));
				$this->redirect('/divisions');
			break;
			case 'view':
				$this->_viewDivision($id);
			break;
			default:
				$this->_divisionList();
			break;
		}
	}
	
	
	function _divisionList(){
		$this->loadModel('Division');
		
		$conditions = array();
		$order = $this->paginate['order'] = array('Division.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();		
			$divisions = $this->Division->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
  		} else {
		    $divisions = $this->paginate('Division', $conditions);
		}
		$this->set(compact('offset'));
		$this->set('divisions', $divisions);
		if(isset($this->request->query['export'])){  
			$this->set('filename','divisions'); 
			$this->render('export_divisions','export_xls');
		}
	}
	
	function _update_division($id=null){
		$this->loadModel('Division');
		$this->loadModel('Audit');
		
		
		if ($this->request->data){
			//pr($this->data);
			
			$is_exists = $this->Division->find('count', array('conditions'=>array('LOWER(Division.title)'=>strtolower($this->request->data['Division']['title']), 'Division.id !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Division']['title']));
			}else{
				$division = $this->Division->save($this->request->data);
				if ($this->request->data['Division']['depot_id']){
					$data = array();
					foreach ($this->request->data['Division']['depot_id'] as $depot_id){
						$data[] = array('division_id'=>$division['Division']['id'], 'depot_id'=>$depot_id);
					}
					
					$this->loadModel('DivisionsDepot');
					/* $this->DivisionsDepot->primaryKey = null; */
					$this->DivisionsDepot->deleteAll(array('division_id'=>$id), false);
					@$this->DivisionsDepot->saveAll($data, false);
				}
				
				if ($this->request->data['Division']['region_id']){
					$rdata = array();
					foreach ($this->request->data['Division']['region_id'] as $region_id){
						$rdata[] = array('division_id'=>$division['Division']['id'], 'region_id'=>$region_id);
					}
					$this->loadModel('DivisionsRegion');
					/* $this->DivisionsRegion->primaryKey = null; */
					$this->DivisionsRegion->deleteAll(array('division_id'=>$id), false);
					@$this->DivisionsRegion->saveAll($rdata, false);
				}
				
				if(!empty($id)){
					$userData = $this->Division->read(null, $id);
					
					$this->Audit->saveDeletedData($userData['Division']['id'], 'Division', $this->Auth->user('id') , serialize($userData),'Division Has been updated', STATUS_EDIT);
				}
				
				$this->Session->setFlash(__('Division was added sucessfully'));
				$this->redirect(array('action'=>'divisions'));
			}
		}
		
		if (!empty($id)){
			$this->Division->id = $id;
			$this->request->data = $this->Division->read();
			$region_ids = array();
			if ($this->request->data['Region']){
				
				foreach ($this->request->data['Region'] as $regions){
					$region_ids[] = $regions['id'];
				}
			}
			$this->request->data['Division']['region_id'] = $region_ids;
			$depot_ids = array();
			if ($this->request->data['Depot']){
				
				foreach ($this->request->data['Depot'] as $depots){
					$depot_ids[] = $depots['id'];
				}
			}
			$this->request->data['Division']['depot_id'] = $depot_ids;
			//pr($this->request->data);
		}
		
		$this->_options();
		
		$this->render('adddivision');
	}
	
	
	public function getRegion(){ 
		
		$result = $regions = $depots = $customers = $users = array();
		if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setsel'){
            $eoption = $doption = $uoption = $coption = array();
        }else{
            $eoption = array("0"=>__('All Regions'));
            $doption = array("0"=>__('All Depots'));
			$coption = array("0"=>__('All Customers'));
			$uoption = array("0"=>__('All Users'));
        }
		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'])));
			
			$regions = $this->Region->find('list', array('conditions'=>array('id'=>$rIds ), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc'))); 
			
			$this->loadModel('Depot');
			$depots = $this->Depot->find('list', array('conditions'=>array('region_id'=>$rIds ), 'fields'=>array('id','title'), 'order'=>array('title'=>'asc'))); 
			
			if (!empty($this->request->data['getUser'])){
				$this->loadModel('User');
				
				$this->User->unbindAllModels();
				$this->User->bindModel(array('belongsTo' => array('Role' => array('className' => 'Role'))));
		
				//$users = $this->User->find('list', array('conditions'=>array('User.status'=>ACTIVE, 'region_id'=>$rIds), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc'))); 
				
				$userlist = $this->User->find('all', array('fields' => array('User.id', 'User.name', 'Role.name'), 'conditions'=>array('User.status'=>ACTIVE, 'region_id'=>$rIds), 'order'=>array('User.name'=>'asc')));

				if($userlist){
					foreach($userlist as $user){
						$users[$user['User']['id']] = $user['User']['name'].' ('.$user['Role']['name'].')';
					}
				}
			}
			
			if (!empty($this->request->data['getCust'])){
				$this->loadModel('Customer');
				$customers = $this->Customer->find('list', array('conditions'=>array('division_id'=>$this->request->data['division']), 'fields'=>array('id','name'), 'order'=>array('name'=>'asc'))); 
				$result['customers'] = $coption + $customers;	
			}
		}
		$result['regions'] = $eoption + $regions;
		$result['depots'] = $doption + $depots;	 
	
		$result['users'] = $uoption + $users;	
		
		echo json_encode($result);
		exit;
	}

	public function getBrand(){ 
		$result = $brandList = $conditions = array();
		if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setsel'){
            $boption = array();
        }else{
            $boption = array("0"=>__('All Brands'));
        }
		if (!empty($this->request->data['brandgroup'])){			
			$conditions['brand_group_id'] = $this->request->data['brandgroup'];			
		}
		$this->loadModel('Brand');
		$brandList = $this->Brand->find('list', array('fields'=>array('id','name'),'conditions'=>$conditions));
		
		$result['brandList'] = $boption + $brandList;
		
		echo json_encode($result);
		exit;
	}
  
 }
