<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class InactiveusersController extends AppController {
	var $uses = array('User');
	/**
     * index method
     *
     * @return void
     */
	public function index(){
		
		//$this->gradPermission(4);
		$conditions = array('User.status !=' => ACTIVE);;
		if (!empty($this->request->query['q']) ){
			$conditions['OR']['User.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
			$conditions['OR']['User.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if ( !empty($this->request->query['r'])){
			$conditions['User.role_id'] = $this->request->query['r'];
		}
		if ( !empty($this->request->query['st'])){
			$conditions['User.state_id'] = $this->request->query['st'];
		}
		if ( !empty($this->request->query['rg'])){
			$conditions['User.region_id'] = $this->request->query['rg'];
		}
		if ( !empty($this->request->query['dp'])){
			$conditions['User.depot_id'] = $this->request->query['dp'];
		}
		
		$order=$this->paginate['order'] = array('User.first_name' => 'asc', 'User.last_name'=>'asc');
		$querystring = $this->request->query;
		
		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();		
			$users = $this->User->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));


		}else{
			$users = $this->paginate('User', $conditions);
		}
		

		$this->set(compact('querystring','users'));
		$this->set(compact('offset'));
		$this->_options();
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'inactiveusers');
			$this->render('export_users','export_xls');
		}
		
	}
	
	function _options(){
		$this->loadModel('Role');
		$this->loadModel('State');
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$roles = $this->Role->getRolesList();
		$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'), 'order'=>array('title'=>'asc')));
		
		$this->set(compact('roles', 'states', 'regions', 'depots'));
	}
	
	function activateall(){
		if (!empty($this->request->data['deleteAllValue'])){ 
			$this->User->updateAll(array('User.status' => ACTIVE), array('User.id' => explode(",", $this->request->data['deleteAllValue']) ) );
			$this->Session->setFlash(__('Selected users was activated successfully'));
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
}