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

/**
 * Controller name
 *
 * @var string
 */
	public function index(){
		//$this->gradPermission(1);
		$conditions = array();
		if (!empty($this->request->query['q']) ){
			$conditions['Distributor.title LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if (!empty($this->request->query['st']) ){
			$conditions['Distributor.state_id'] = $this->request->query['st'];
		}
		$order = $this->paginate['Distributor.order'] = array('Distributor.title' => 'asc');
        
		$this->loadModel('State');
		$this->loadModel('Region');
		$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'));

		$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();		
			$distributors = $this->Distributor->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
			$this->set('distributors', $distributors);
			$this->set(compact('offset'));
			$this->set('filename', 'Distributors');
			$this->render('export_distributors','export_xls');
		} else {
			$distributors = $this->paginate('Distributor', $conditions);
		}
		//pr($distributors);
		$this->set('distributors', $distributors);
		
	}
	
	public function add(){
	//	$this->gradPermission(1);
		if ($this->request->data){
			//pr($this->data);
			
			$is_exists = $this->Distributor->find('count', array('conditions'=>array('LOWER(Distributor.title)'=>strtolower($this->request->data['Distributor']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Distributor']['title']));
			}else{
				$distributor = $this->Distributor->save($this->request->data);
				if ($this->request->data['Distributor']['depot_id']){
					$data = array();
					foreach ($this->request->data['Distributor']['depot_id'] as $depot_id){
						$data[] = array('distributor_id'=>$distributor['Distributor']['id'], 'depot_id'=>$depot_id);
					}
					
					$this->loadModel('DistributorsDepot');
					$this->DistributorsDepot->saveAll($data);
				}
				
				if ($this->request->data['Distributor']['region_id']){
					$rdata = array();
					foreach ($this->request->data['Distributor']['region_id'] as $region_id){
						$rdata[] = array('distributor_id'=>$distributor['Distributor']['id'], 'region_id'=>$region_id);
					}
					$this->loadModel('DistributorsRegion');
					$this->DistributorsRegion->saveAll($rdata);
				}
				
				$this->Session->setFlash(__('Distributor was added sucessfully'));
				$this->redirect(array('action'=>'index'));
			}
		}
		
		$this->loadModel('State');
		$this->loadModel('Region');
		$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'));
		
	}
	
	public function getDepotOptions(){
		$result = array();
		if (!empty($this->data['regionIds'])){
			$this->loadModel('Depot');
			
			$depots = $this->Depot->find('list', array('conditions'=>array('region_id'=>$this->data['regionIds'])));
			$result['options'] = $depots;
		}
		echo json_encode($result);
		exit;
	}
	public function edit($id=0){
		$this->loadModel('Audit');
		$this->Distributor->unBindModelAll();
		$userData = $this->Distributor->read(null, $id);
	//	$this->gradPermission(1);
	
		if ($this->request->data){
			$is_exists = $this->Distributor->find('count', array('conditions'=>array('LOWER(Distributor.title)'=>strtolower($this->request->data['Distributor']['title']), 'Distributor.id !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Distributor']['title']));
			}else{
				$this->Distributor->save($this->request->data);
				if ($this->request->data['Distributor']['depot_id']){
					$data = array();
					foreach ($this->request->data['Distributor']['depot_id'] as $depot_id){
						$data[] = array('distributor_id'=>$id, 'depot_id'=>$depot_id);
					}
					
					$this->loadModel('DistributorsDepot');
					$this->DistributorsDepot->primaryKey = null;
					$this->DistributorsDepot->deleteAll(array('distributor_id'=>$id), false);
					$this->DistributorsDepot->saveAll($data);
				}
				
				if ($this->request->data['Distributor']['region_id']){
					$rdata = array();
					foreach ($this->request->data['Distributor']['region_id'] as $region_id){
						$rdata[] = array('distributor_id'=>$id, 'region_id'=>$region_id);
					}
					
					$this->loadModel('DistributorsRegion');
					$this->DistributorsRegion->primaryKey = null;
					$this->DistributorsRegion->deleteAll(array('distributor_id'=>$id), false);
					$this->DistributorsRegion->saveAll($rdata);
					
					//pr($rdata);
					//die();
				}
				$this->Audit->saveDeletedData($userData['Distributor']['id'], 'Distributor', $this->Auth->user('id') , serialize($userData),'Distributor Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Distributor was updated sucessfully'));
				$this->redirect('/distributors');
			}
		}
		
		if (!empty($id)){
			$this->Distributor->id = $id;
			$this->request->data = $this->Distributor->read();
			$region_ids = array();
			if ($this->request->data['Region']){
				
				foreach ($this->request->data['Region'] as $regions){
					$region_ids[] = $regions['id'];
				}
			}
			$this->request->data['Distributor']['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['Distributor']['depot_id'] = $depot_ids;
			//pr($this->request->data);
		}
		$this->loadModel('State');
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$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')));
		$depots = $this->Depot->find('list', array('fields'=>array('id', 'title'), 'conditions'=>array('region_id'=>$depot_ids), 'order'=>array('title'=>'asc')));
		$this->set(compact('states', 'regions', 'depots'));
		//$this->render('add');
		
	}
	public function delete($id=0){
		if(!$id){
			$this->redirect('/distributors');
		}
		$this->Distributor->id = $id;
		$distributor = $this->Distributor->read();

		$data = array();
		$data['serialize'] = serialize($distributor);
		$data['model_id'] = $distributor['Distributor']['id'];
		$this->Distributor->delete();
		$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Distributor', $this->Auth->user('id') , $data['serialize'],'Distributor Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Distributor was deleted sucessfully'));
		$this->redirect(array('action'=>'index'));
	}
	
	public function view ($id){
		$this->Distributor->id = $id;
		//$this->Distributor->hasOne = array('User'=>array('className'=>'User', 'foreignKey'=>'depot_id', 'conditions'=>array('User.role_id'=>4), 'fields'=>array('id', 'first_name', 'last_name')));
		$warehouse = $this->Distributor->read();
		if(!$warehouse){
			throw new NotFoundException(__('Invalid warehouse'));
		}
		$this->loadModel('CurrentStock');
		
		$stocks = $this->CurrentStock->getStockStatus('Distributor', $id);
		$this->set(compact('warehouse', 'stocks'));
	}

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