<?php
App::uses('AppController', 'Controller');
class AssetsController extends AppController {
	var $components = array('Option');
/**
 * Controller name
 *
 * @var string
 */
	public function index(){ 
		//$this->gradPermission(1);
		$this->loadModel('AssetUser');
		$conditions = array();
		$query = $this->request->query;
		if (!empty($this->request->query['q']) ){
			$conditions['LOWER(Asset.number) LIKE'] =  '%'.strtolower($this->request->query['q']).'%';
		}
		if ( !empty($this->request->query['type'])){
			$conditions['Asset.type LIKE'] = $this->request->query['type'];
		}
		
		if ( !empty($this->request->query['department'])){
			$conditions['Asset.department'] = $this->request->query['department'];
		}
		
		if (isset($this->request->query['status']) && $this->request->query['status'] != ""){
			$conditions['Asset.status'] = $this->request->query['status'];
		}
		
		if (!empty($query['dv'])){
            if (empty($query['rg']) && empty($query['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$query['dv'])));
                
				$userCond['User.region_id IN'] =  $rIds;
            }

        }
		
		if (!empty($query['rg'])){
            $userCond['User.region_id'] = $query['rg'];
        }
		
		if (!empty($query['dp'])){
            $userCond['User.depot_id'] = $query['dp'];
        }
		
		if (!empty($query['user_id'])){
            $userCond['User.id'] =  $query['user_id'];
        }
		
		if(!empty($userCond)){
			$this->loadModel('User');
			$uids = $this->User->find('list', array('fields' => array('id'), 'conditions' => $userCond)); 
			if(!empty($uids)){  
				$aids = $this->AssetUser->find('list', array('fields' => array('asset_id'), 'conditions' => array('user_id' => $uids ))); 
			}
			
			if(!empty($aids)){  
				if(count($aids) > 1){
					$conditions['Asset.id IN'] =  $aids;
					
				}else{
					$conditions['Asset.id'] =  $aids;
				}
				
			} 
		}

		$order = $this->paginate['order'] = array('Asset.number' => 'asc');
		$querystring = $this->request->query;
		
		
		if(!isset($this->request->query['export'])){   
			// Calculate filtered count and adjust page number if needed
			$filteredCount = $this->Asset->find('count', array('conditions' => $conditions));
			$limit = $this->paginate['limit'];
			$totalPages = ceil($filteredCount / $limit);
			$currentPage = !empty($this->request->params['named']['page']) ? $this->request->params['named']['page'] : 1;
			
			if ($currentPage > $totalPages && $totalPages > 0) { 
				$this->redirect(array('action' => 'index', '?' => array_merge($this->request->query, array('page' => $totalPages))));
				return;
			}
		}
		

		
		$this->Asset->bindModel(
			array('hasMany' => array(
					'AssetUser' => array(
						'className' => 'AssetUser',
					)
				)
			)
		); 
		$this->AssetUser->bindModel(
			array('belongsTo' => array(
					'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('id', 'first_name', 'last_name', 'last_name', 'division_id', 'region_id', 'depot_id'), 'type'=>'left'),
				)
			)
		);
		
		$this->Asset->Behaviors->load('Containable');
		$this->paginate['contain'] = $contain = array(
			'AssetUser' => array(	
				'User' => array(	
					'Division' => array(
						'fields' => array('id', 'title'),
					),
					'Region' => array(
						'fields' => array('id', 'title'),
					),
					'Depot' => array(
						'fields' => array('id', 'title'),
					),
					'Role' => array(
						'fields' => array('id', 'name'),
					),
				)
			)
		);
		
		//pr($conditions);
		
	
		
		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;
			}
				
				
			$assets = $this->Asset->find('all',array('contain' => $contain, 'conditions' =>$conditions,'order'=>$order ,'limit'=>10000, 'offset'=>$offset));
			$this->set(compact('assets','offset'));
			$this->set('filename', 'Assets');
			$this->render('export_assets','export_xls');
		} else {		
		    $assets = $this->paginate('Asset', $conditions);
		} 
		//pr($assets); //die();
		$this->_options();
		
		$this->user = $this->Auth->user();
		$this->loadModel('User');
        $users = $this->User->usersListByRole($this->user);
		
		$this->set(compact('assets', 'querystring', 'users'));
	}
	
	public function add(){
		//$this->gradPermission(1);
		if ($this->request->data){ 
			$this->request->data['Asset']['created'] = date('Y-m-d H:i:s');
			$is_exists = $this->Asset->find('count', array('conditions'=>array('LOWER(number)'=>strtolower($this->request->data['Asset']['number']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Asset']['number']));
			}else{
				
				
				/*if(empty($this->request->data['Asset']['region_id']) && !empty($this->Auth->user('region_id'))){
						$this->request->data['Asset']['region_id'] = $this->Auth->user('region_id');
				}
					
				if(empty($this->request->data['Asset']['depot_id']) && !empty($this->Auth->user('depot_id')) ){
					$this->request->data['Asset']['depot_id'] = $this->Auth->user('depot_id');
				}*/
					
				$asset =  $this->Asset->save($this->request->data);
				if(!empty($asset) && !empty($this->request->data['Asset']['user_ids'])){
					foreach($this->request->data['Asset']['user_ids'] as $uid){					 
						$data[] = array(
							'user_id'=> $uid,
							'asset_id'=> $asset['Asset']['id'],
						);
					}	
				}
				//pr($data); 
				if ($data){
					$this->loadModel('AssetUser');
					$this->AssetUser->deleteAll(array('AssetUser.asset_id' => $asset['Asset']['id']), false);
                    $this->AssetUser->saveAll($data);
                }
				
				$this->Session->setFlash(__('Asset was added successfully'));
				$this->redirect('/assets');
			}
		}
		
		//$this->_selectOptions();
		
		$this->loadModel('User');
		$users = $this->User->find('list', array('fields'=>array('id', 'name'), 'conditions' => array('status' => 1), 'order' => array('name' => 'asc')));
		//$users = $this->User->usersListByRole($this->user);
		$this->set(compact('users'));
	}
	
	public function edit($id=0){
		$this->loadModel('Audit');
		$this->loadModel('User');
		$this->loadModel('AssetUser');
		//$set_var=$this->gradPermission(1);
		$assetData = $this->Asset->read(null, $id);
		if ($this->request->data){ 
			$is_exists = $this->Asset->find('count', array('conditions'=>array('LOWER(number)'=>strtolower($this->request->data['Asset']['number']), 'id !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Asset']['number']));
			}else{
				
				$asset =  $this->Asset->save($this->request->data);
				
				if(!empty($asset)){
					if(!empty($this->request->data['Asset']['user_ids']) && !empty($this->request->data['Asset']['user_ids'][0])){ 
						foreach($this->request->data['Asset']['user_ids'] as $uid){	
							if(!empty($uid)){
								$data[] = array(
									'user_id'=> $uid,
									'asset_id'=> $asset['Asset']['id'],
								);
							}
						}
						
						if (!empty($data)){
							
							$this->AssetUser->deleteAll(array('AssetUser.asset_id' => $asset['Asset']['id']), false);
							$this->AssetUser->saveAll($data);
						}
					}elseif(!empty($this->request->data['Asset']['user_ids']) && empty($this->request->data['Asset']['user_ids'][0])){ 
						$this->AssetUser->deleteAll(array('AssetUser.asset_id' => $asset['Asset']['id']), false);
					}
					
				}
				
				$this->Audit->saveDeletedData($assetData['Asset']['id'], 'Asset', $this->Auth->user('id') , serialize($assetData),'Asset Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Asset was updated successfully'));
				$this->redirect('/assets');
			}
		}
		
		if (!empty($id)){
			$this->Asset->id = $id;
			$this->request->data = $this->Asset->read();
		}
		
		//$this->_selectOptions();
		$users = $this->User->find('list', array('fields'=>array('id', 'name'), 'conditions' => array('status' => 1), 'order' => array('name' => 'asc')));
		//$users = $this->User->find('list', array('fields'=>array('id', 'name'), 'conditions' => array('status' => 1, 'region_id' =>$this->request->data['Asset']['region_id'], 'depot_id' =>$this->request->data['Asset']['depot_id'] ), 'order' => array('name' => 'asc')));
		$this->set(compact('users'));
		
		$this->request->data['Asset']['user_ids'] = $this->AssetUser->find('list', array('fields'=>array('user_id'), 'conditions' => array('asset_id' => $id)));
		
	    
	
		
		
		/* if(!empty($userAsset)){
			$this->request->data['Asset']['user_ids']
		} */
		
		//if($set_var){
		$this->render('add');
		//}
	}
	
	
	
	public function delete($id){
		if(!$id){
			$this->redirect('/assets');
		}
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->Asset->id = $id;
		$asset = $this->Asset->read();

		$data = array();
		$data['serialize'] = serialize($asset);
		$data['model_id'] = $asset['Asset']['id'];
		$this->request->data = $this->Asset->delete();
		$this->loadModel('Audit');
		$this->Audit->saveDeletedData($data['model_id'], 'Asset', $this->Auth->user('id') , $data['serialize'],'Asset Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Asset was deleted successfully'));
		$this->redirect('/assets');
	}
	public function deleteAllAssets(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Asset->deleteAll(array('Asset.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Assets was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	public function getAssets(){
		$result = $assets = array();
		
			
		if (!empty($this->request->data['type'])){
			$conditions['type'] = $this->request->data['type'];
		}	
		if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setsel'){
			if($this->request->data['type'] == 'bike'){
				$eoption = array("0"=>__('Select Bike'));
			}else{
				$eoption = array("0"=>__('Select Vehicle'));
			}
		}else{
			if($this->request->data['type'] == 'bike'){
				$eoption = array("0"=>__('All Bikes'));
			}else{
				$eoption = array("0"=>__('All Vehicles'));
			}
		}

		$conditions['status'] = 1;
			
		$assets = $this->Asset->find('list', array('conditions'=>$conditions, 'fields'=>array('id','number'), 'order'=>array('number'=>'asc')));
		
		$result['assets'] = $eoption + $assets; 
		echo json_encode($result);
		exit;
	}
	
	public function getAssetOptions(){
		$result = $assets = array();
		
		$userConditions['User.status'] = $conditions['Asset.status'] = 1;
		
		
		$eoption = array("0"=>__('Select Assets'));	
		if (!empty($this->request->data['regionId'])){
			$userConditions['User.region_id'] = $this->request->data['regionId'];
		}
		if (!empty($this->request->data['depotId'])){
			$userConditions['User.depot_id'] = $this->request->data['depotId'];
		}	
		
		$this->loadModel('User');
		$usrIds = $this->User->find('list', array('fields' => array('User.id'), 'conditions' => $userConditions));
		
		if(!empty($usrIds)){
			$this->loadModel('AssetUser');
			
			$assetIds = $this->AssetUser->find('list', array('fields' => array('AssetUser.asset_id'), 'conditions' => array('AssetUser.user_id' => $usrIds)));
			
			$conditions['Asset.id'] = $assetIds;
		}
		
		$this->Asset->virtualFields['numberType'] = 'CONCAT(Asset.number, " (",Asset.type, ")")';
		
		$assets = $this->Asset->find('list', array('fields' => array('id', 'numberType'), 'conditions' => $conditions, 'order' => array('Asset.numberType' => 'asc')));
		
		$result['assets'] = $eoption + $assets; 
		echo json_encode($result);
		exit;
	}
	
	function _options(){
        $Opdata = isset($this->request->data['Report'] ) ? $this->request->data['Report']  : array();
        $param = !empty($this->request->query ) ? $this->request->query  : array();
        $this->Option->Options($Opdata, $this->user,$param);
    }
    
    function _selectOptions(){
		$Opdata = isset($this->request->data['Asset'] ) ? $this->request->data['Asset']  : array();
		$param = !empty($this->request->query ) ? $this->request->query  : array();
		$this->Option->Options($Opdata, $this->user, $param);
	}
}