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

/**
 * Controller name
 *
 * @var string
 */
 var $components = array('Option');
	public function index(){
		//pr($this->user);
		//$set_var = $this->gradPermission(4);
		//if ($this->user['Role']['grade']==3 ){
			//$this->render('/Errors/access_denied');
			//return false;
		//}

								
		$conditions = array();
		
		if (!empty($this->request->query['q'])){
			$conditions['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		
		if (!empty($this->request->query['cat']) ){
			$conditions['ExpType.category_id'] =  $this->request->query['cat'];
		}

		if (!empty($this->request->query['r'])){
			$conditions['User.role_id'] =  $this->request->query['r'];
		}
		
		if ( !empty($this->request->query['dp'])){
			$conditions['Expense.depot_id'] = $this->request->query['dp'];
		}
		if ( !empty($this->request->query['et'])){
			$conditions['Expense.exp_type_id'] = $this->request->query['et'];
		}
		if ( !empty($this->request->query['asset_id'])){
			$conditions['Expense.asset_id'] = $this->request->query['asset_id'];
		}
		
		if (empty($this->request->query['from'])){
			$this->request->query['from'] = date('Y-m-01');
		}
		
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Expense.exp_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Expense.exp_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Expense.exp_date <= '] = $this->request->query['to'];
		}
		if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
			$conditions['Expense.status'] = $this->request->query['sts'];
		}
		
		if (isset($this->request->query['via_app']) && $this->request->query['via_app']!='' ){
            $conditions['Expense.via_app'] = $this->request->query['via_app'];
        }
		
		
		//$this->Expense->_userCondition($conditions, $this->user);
		$this->Expense->_userRoleCondition($conditions, $this->user, $this->paginate);
		
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();

		//echo $this->paginate['joins'][0]['table'];// die();
		$order=$this->paginate['order'] = array('Expense.created' => 'desc');
		$querystring = $this->request->query;	
		$this->set(compact('querystring'));
	

		$totalExpense = $this->Expense->find('all', array('fields'=>array('SUM(Expense.exp_amount) AS totalExpense'), 'conditions'=>$conditions,'joins'=>$joins));
		
		$this->Expense->bindModel(
					array(
					'belongsTo'=>array(
						'Asset' =>array(
						
							'className' => 'Asset',
							'foreignKey'=> 'asset_id',
							'fields' => array('id', 'number', 'type')
							)
						)
					)
		);
			
		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;
			}	
			$expenses = $this->Expense->find('all', array('conditions' =>$conditions,'order'=>$order,'joins' => $joins,'limit'=>'10000','offset'=>$offset));			
		} else {
		    $expenses = $this->paginate('Expense', $conditions);
		}
		//pr($expenses);
		$this->loadModel('Role');
		$roles = $this->Role->getRolesList();
		
		$this->loadModel('Asset');
		$assetCond['status'] = 1;
		$assets = $this->Asset->find('list', array('conditions'=>$assetCond, 'fields'=>array('id','number'), 'order'=>array('number'=>'asc')));
		
		$this->loadModel('Category');
		$categories = $this->Category->find('list');

		$this->set(compact('expenses','offset', 'totalExpense', 'roles', 'assets','categories'));
		
		//options
		$this->_options();
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'Expenses');
			$this->render('export_expenses','export_xls');
		}
	}
	
 /**
 * Controller name
 *
 * @var string
 */
	public function add(){ 	
	   // $set_var = $this->gradPermission(1);
		if ($this->request->data && !empty($this->Auth->user('id'))){//pr($this->request->data);die();
			$this->request->data['Expense']['user_id'] = $this->Auth->user('id');
			
			if(empty($this->request->data['Expense']['depot_id'])){
				$this->request->data['Expense']['depot_id'] = $this->Auth->user('depot_id');
			}
			
			if(empty($this->request->data['Expense']['division_id']) && ($this->Auth->user('Role.id') == DIVISIONMANAGER || $this->Auth->user('Role.grade') >= RM)){
				$this->request->data['Expense']['division_id'] = $this->Auth->user('division_id');
			}
			
			if(empty($this->request->data['Expense']['region_id'])){
				$this->request->data['Expense']['region_id'] = $this->Auth->user('region_id');
			}
			if (empty($this->request->data['Expense']['exp_date'])){
				$this->request->data['Expense']['exp_date'] = date('Y-m-d H:i:s');
			}
			/* if(empty($this->request->data['Expense']['brand_id'])){
				$this->request->data['Expense']['brand_id'] = 1;
			} */
			
			/*** default all expenses posted by users from these two depots (Sokoto 2- Dosso and Kano 2- Maradi) only to report on one Brand “AllStars Niger Retail” - $brand_id = 14. And For Other depots “Yes Consumer” - $brand_id = 1 ***/
			
			if(!empty($this->request->data['Expense']['depot_id'])){
				$this->request->data['Expense']['brand_id'] = get_expense_brand_id($this->request->data['Expense']['depot_id']);
			}
			
			if(empty($this->request->data['Expense']['unit'])){
				$this->request->data['Expense']['unit'] = 'Case';			
			}
			
			if (!empty($this->request->data['Expense']['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['Expense']['brand_id']))); 
				$this->request->data['Expense']['brand_group_id'] = $group_id[$this->request->data['Expense']['brand_id']]; 
			}
			
			/* if (!empty($this->request->data['Expense']['exp_type_id']) && empty($this->request->data['Expense']['asset_id']){ 
			
				$this->loadModel('ExpType');
				$assetExpTypes = $this->ExpType->find('list', array('fields' => array('id' , 'id'), 'conditions' => array('ExpType.category_id IN' => [EXP_CAT_MO_BIKE, EXP_CAT_MO_VEHICLE])));
				
				if (in_array($this->request->data['Expense']['exp_type_id'], $assetExpTypes)){
					
					if (empty($this->request->data['Expense']['asset_id'])){

						if(count($this->Auth->user('assets')) == 1){
							$this->request->data['asset_id'] = $this->Auth->user('assets.0.Asset.id');
						}						
					}
										
					$this->request->data['Expense']['asset_id'] = $this->Auth->user('Asset.id');
				}
			} */
			
			$this->Expense->save($this->request->data);
			$this->Session->setFlash(__('Expense was saved'));
			if (isset($this->request->data['addmore'])){
				$this->redirect(array('action'=>'add'));
			}else{
				$this->redirect(array('action'=>'index'));
			}
		}
	

		if(!empty( $this->Auth->user('assets'))){
			$uAssets = [];
			foreach($this->Auth->user('assets') as $a){ 
				if($a['Asset']['status'] == ACTIVE){
					$uAssets[$a['Asset']['id']] = $a['Asset']['number'].' ('.$a['Asset']['type'].')';
				}
			}
		}/* elseif(!empty($this->Auth->user('depot_id')) && ($this->Auth->user('Role.grade') <= 3)){
			$aCond['Asset.depot_id'] = $this->Auth->user('depot_id');
		} */
		
		if(!empty($uAssets)){
			$assets = $uAssets;
		}else{
			$this->loadModel('Asset');
			$this->Asset->virtualFields['numberType'] = 'CONCAT(Asset.number, " (",Asset.type, ")")';
			$assets = $this->Asset->find('list', array('fields' => array('id', 'numberType'), 'conditions' => $aCond, 'order' => array('Asset.numberType' => 'asc')));
		} 
		
		
		$this->set(compact('assets'));
		
		$this->_options();
		//if (!$set_var && $this->user['Role']['grade'] == 4){
			$this->render('add');
		//}
	}
	
	function _options(){		
		$this->loadModel('ExpType');
		$this->loadModel('User');
		//$this->loadModel('Region');
		$users = $this->User->usersListByRole($this->user);
		//$regions = $this->Region->getList();
		
		//$banks = $this->Bank->find('list', array('fields'=>array('id','name')));
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name')));
		$expTypes = $this->ExpType->find('list', array('fields'=>array('id','name')));
		
		$Opdata = isset($this->request->data['Expense'] ) ? $this->request->data['Expense']  : array();
		$this->Option->Options($Opdata, $this->user);
		
		$this->set(compact('banks','expTypes','brands','users'));
	}
 /**
 * Controller name
 *
 * @var string
 */
	public function edit($id=0){
		$this->loadModel('Audit');
		//$set_var=$this->gradPermission(1);
		$this->Expense->id = $id;
		$userData = $this->Expense->read(null, $id);
        if (!$this->Expense->exists()) {
            throw new NotFoundException(__('Invalid Expense'));
        }
      if ($this->request->is('post') || $this->request->is('put')) {
		  
			/*** default all expenses posted by users from these two depots (Sokoto 2- Dosso and Kano 2- Maradi) only to report on one Brand “AllStars Niger Retail” - $brand_id = 14. And For Other depots “Yes Consumer” - $brand_id = 1 ***/
			
			if(!empty($this->request->data['Expense']['depot_id'])){
				$this->request->data['Expense']['brand_id'] = get_expense_brand_id($this->request->data['Expense']['depot_id']);
			}
			
			if(empty($this->request->data['Expense']['unit'])){					
				$this->request->data['Expense']['unit'] = "Case" ;				
			}
			
			if (!empty($this->request->data['Expense']['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['Expense']['brand_id']))); 
				$this->request->data['Expense']['brand_group_id'] = $group_id[$this->request->data['Expense']['brand_id']]; 
			}
			
			
			if ($this->Expense->save($this->request->data)) {

				//pr($this->Expense->save($this->request->data));die();
				$this->Audit->saveDeletedData($userData['Expense']['id'], 'Expense', $this->Auth->user('id') , serialize($userData),'Expense Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('The Expense has been updated'));
				if (isset($this->request->data['addmore'])){
					$this->redirect(array('action'=>'add'));
				}else{
					$this->redirect(array('action'=>'index', '?'=> $this->request->query));
				}
			} else {
				$this->Session->setFlash(__('The Expense could not be saved. Please, try again.'));
			}
		}
		
		else {
            $this->request->data = $this->Expense->read(null, $id);			
			$this->loadModel('User');
			$addedBy = $this->User->findById($this->request->data['Expense']['user_id']);
			
			$this->set('addedBy', $addedBy);
        }
		
		$aCond['Asset.status'] = ACTIVE;
		if(!empty($this->request->data['Expense']['user_id'])){
			$this->loadModel('AssetUser');
			$assetIds = $this->AssetUser->find('list', array('fields' => array('id', 'asset_id'), 'conditions' => array('AssetUser.user_id' => $this->request->data['Expense']['user_id'])));
			if(!empty($assetIds)){
				$aCond['Asset.id'] = $assetIds;
			}
			
		}elseif(!empty($this->request->data['Expense']['depot_id'])){
			$aCond['Asset.depot_id'] = $this->request->data['Expense']['depot_id'];
		}elseif(!empty($this->Auth->user('depot_id')) && ($this->Auth->user('Role.grade') <= 3)){
			$aCond['Asset.depot_id'] = $this->Auth->user('depot_id');
		}elseif(!empty( $this->Auth->user('assets'))){
			$uAssets = [];
			foreach($this->Auth->user('assets') as $a){
				if($a['Asset']['status'] == ACTIVE){
					$uAssets[$a['Asset']['id']] = $a['Asset']['number'].' ('.$a['Asset']['type'].')';
				}				
			}
		}
		if(!empty($uAssets)){
			$assets = $uAssets;
		}else{ 
			//pr($aCond);
			$this->loadModel('Asset');
			$this->Asset->virtualFields['numberType'] = 'CONCAT(Asset.number, " (",Asset.type, ")")';
			$assets = $this->Asset->find('list', array('fields' => array('id', 'numberType'), 'conditions' => $aCond, 'order' => array('Asset.numberType' => 'asc')));
		}
		
		
		$this->set(compact('assets'));
			
		$this->_options();
		//if (!$set_var && $this->user['Role']['grade'] == 4){
			$this->render('add');
		//}
	}
	public function delete($id){
	//	$this->gradPermission(2);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Expense->id = $id;
        $expense = $this->Expense->read();
		if (!$expense) {
            throw new NotFoundException(__('Invalid Expense'));
        }
		if ( $this->user['Role']['grade'] > 1 && $expense['Expense']['user_id'] != $this->user['id']) {
            throw new NotFoundException(__('Access Denied'));
        }
		$data = array();
		$data['serialize'] = serialize($expense);
		$data['model_id'] = $expense['Expense']['id'];
        if ($this->Expense->delete()) {
			$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Expense', $this->Auth->user('id') , $data['serialize'],'Expense Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Expense was deleted successfully'));
            $this->redirect(array('action' => 'index', '?'=> $this->request->query));
        }
        $this->Session->setFlash(__('Expense was not deleted'));
        $this->redirect(array('action' => 'index', '?'=> $this->request->query));
		
	}
	
	public function deleteAllExpense(){
		
		//$this->gradPermission(2);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Expense->deleteAll(array('Expense.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected expenses was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	public function types($op='', $id=''){
	//	$this->gradPermission(1);
		$this->loadModel('ExpType');
		switch ($op){
			case 'add':
				$this->_updateExpType();
			break;
			
			case 'edit':
				$this->_updateExpType($id);
			break;
			
			case 'delete':
				$this->_deleteExpType($id);
			break;
			
			default:
				$this->ExpType->belongsTo = array('Category' => array('className' => 'Category', 'foreignKey' => 'category_id', 'type'=>'left'));
				$conditions = array();
				if (!empty($this->request->query['q']) ){
					$conditions['ExpType.name LIKE'] =  '%'.$this->request->query['q'].'%';
				}
				
				if (!empty($this->request->query['cat']) ){
					$conditions['ExpType.category_id'] =  $this->request->query['cat'];
				}
				
				$this->paginate['order'] = array('ExpType.name' => 'asc');

				$querystring = $this->request->query;
				/*if(isset($this->request->query['export'])){   
					$expTypes = $this->ExpType->find('all',array('conditions'=>$conditions));					
				} else {*/
					$expTypes = $this->paginate('ExpType', $conditions);
			//	}
				$this->loadModel('Category');
				$categories = $this->Category->find('list'); 
				$this->set(compact('expTypes', 'querystring', 'categories'));
                if(isset($this->request->query['export'])){
					$this->set('filename','Expense Type');  
				     $this->render('export_exptypes','export_xls');
			    }
			break;
		}
	}
	
	function _updateExpType($id=0){
		$this->loadModel('Audit');
		$userData = $this->ExpType->read(null, $id);
	//$set_var=$this->gradPermission(1);
		if ($this->request->data){
			if ($id){
				$conditions = array('LOWER(name)'=>strtolower($this->request->data['ExpType']['name']), 'id !=' => $id);
				$saveStatus = 'updated';
			}else{
				$conditions = array('LOWER(name)'=>strtolower($this->request->data['ExpType']['name']));
				$saveStatus = 'added';
			}
			$is_exists = $this->ExpType->find('count', array('conditions'=>$conditions));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['ExpType']['name']));
			}else{
				//Category update
				//pr($this->request->data['ExpType']);
				if (!empty($this->request->data['ExpType']['category'] ) ){
					//Add Category
					$this->loadModel('Category');
					$conditions = array('LOWER(name)'=>strtolower($this->request->data['ExpType']['category']));
				
					$category = $this->Category->find('first', array('conditions'=>$conditions));
					if (!empty($category['Category']['id'])){
						$this->request->data['ExpType']['category_id'] = $category['Category']['id'];
					}else{
						$catData = array('name' => $this->request->data['ExpType']['category']);
						$category = $this->Category->save($catData);
						$this->request->data['ExpType']['category_id'] = $category['Category']['id'];
					}
				}
			
				$this->ExpType->save($this->request->data);
				if ($id){
				$conditions = array('LOWER(name)'=>strtolower($this->request->data['ExpType']['name']), 'id !=' => $id);
				$this->Audit->saveDeletedData($userData['ExpType']['id'], 'ExpType', $this->Auth->user('id') , serialize($userData),'Expense Type Has been updated', STATUS_EDIT);
				}
				$this->Session->setFlash(__('Expense Type was %s sucessfully', $saveStatus));
				$this->redirect(array('action'=>'types'));
			}
		}
		if ($id){
			$this->ExpType->id = $id;
			$this->request->data = $this->ExpType->read();
		}
		$this->loadModel('Category');
		$categories = $this->Category->find('list', array('fields'=>array('id','name')));
		$this->set('categories', $categories);
		//if($set_var)
		//{
		$this->render('update_exptype');
		//}
		
	}
	
	function _deleteExpType($id){
		
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->ExpType->id = $id;
        if (!$this->ExpType->exists()) {
            throw new NotFoundException(__('Invalid Expense Type'));
        }
		$exptype = $this->ExpType->read();

		$data = array();
		$data['serialize'] = serialize($exptype);
		$data['model_id'] = $exptype['ExpType']['id'];
		
		$this->ExpType->delete();
		$this->loadModel('Audit');
		$this->Audit->saveDeletedData($data['model_id'], 'ExpType', $this->Auth->user('id') , $data['serialize'],'Expense type Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Expense type was deleted sucessfully'));
		$this->redirect(array('action'=>'types'));
		
	}
	
	function view($id=0){
		//$set_var = $this->gradPermission(4);
		if ($this->user['Role']['grade']==3 ){
			$this->render('/Errors/access_denied');
			//return false;
		}
		$conditions = array();
		$this->Expense->_userCondition($conditions, $this->user);
		$this->Expense->id = $id;
		$this->Expense->belongsTo['Depot'] = array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('title'), 'type'=>'left');
		$this->Expense->belongsTo['Brand'] = array('className' => 'Brand', 'foreignKey' => 'brand_id', 'fields' => array('name'), 'type'=>'left');
		$this->Expense->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
		$this->Expense->belongsTo['Asset'] = array('className' => 'Asset', 'foreignKey' => 'asset_id', 'fields' => array('id', 'number', 'type'), 'type'=>'left');
		

		
		$expense = $this->Expense->read();
		if (!$expense){
			throw new NotFoundException(__('Invalid Expense'));
		}
		
		$this->set('expense', $expense);
	}

	public function deleteAllExpType(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('ExpType');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->ExpType->deleteAll(array('ExpType.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Expense Types was deleted successfully') );
			$this->redirect(array('action'=>'types'));
		}
		exit;
	}
	
	public function reimbursement(){
		$conditions = array();
		$this->loadModel('Depot');
		$this->loadModel('ExpenseReimbursement');
		if (!empty($this->request->query['q'])){
			$conditions['concat_ws(" ", User.first_name, User.last_name , User1.first_name, User1.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
		}
		if ( !empty($this->request->query['dp'])){
			$conditions['ExpenseReimbursement.depot_id'] = $this->request->query['dp'];
		}
		/*if ( !empty($this->request->query['et'])){
			$conditions['ExpenseReimbursement.exp_type_id'] = $this->request->query['et'];
		}
		*/
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('ExpenseReimbursement.exp_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));			
		}elseif (!empty($this->request->query['from'])){
			$conditions['ExpenseReimbursement.exp_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['ExpenseReimbursement.exp_date <= '] = $this->request->query['to'];
		}
		if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
			$conditions['ExpenseReimbursement.status'] = $this->request->query['sts'];
		}
		
		$this->ExpenseReimbursement->_userCondition($conditions, $this->user);
		$order=$this->paginate['order'] = array('ExpenseReimbursement.created' => 'desc');
		$querystring = $this->request->query;	
		$this->set(compact('querystring'));
		if(isset($this->request->query['export'])){
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();
			if(!empty($this->request->query['offset'])){
			$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}			
			$expensereimbursement = $this->ExpenseReimbursement->find('all', array('conditions' =>$conditions,'joins'=>$joins,'order'=>$order,'limit'=>'10000','offset'=>$offset));			
		} else {
		    $expensereimbursement = $this->paginate('ExpenseReimbursement', $conditions);
		}
		//pr($expensereimbursement);
		$this->set(compact('expensereimbursement','offset'));
		//options
		//$this->_options();
		$depots  = $this->Depot->getlist();
		$this->set(compact('depots'));
		if(isset($this->request->query['export'])){ 
			$this->set('filename', 'ExpensesReimbursement');
			$this->render('export_expenses_reimbursement','export_xls');
		}
	}
	
	public function reimbursementadd() {
		if(!empty($this->request->data)){
			$data = $this->request->data['ExpenseReimbursement'];
			$selecteduser = count($data['user_ids']);
			$this->loadModel('User');
			$udata = array();
			if($data['user_ids']){
				foreach($data['user_ids'] as $key => $uid){
					if(empty($this->request->data['check'])){
						$equalamnt = ($data['exp_amount'] / $selecteduser);
					}else{
						$equalamnt = $this->request->data[$key];
					}
					$this->User->unbindModelAll();
					$depot_id = $this->User->findById($uid);
					$udata[] = array('imburse_user_id' => $uid, 'exp_amount' => $equalamnt, 'user_id'=> $this->Auth->user('id'),'exp_date'=> $data['exp_date'],'depot_id'=>$depot_id['User']['depot_id'],'region_id'=>$depot_id['User']['region_id']);
				}
			}
			$this->loadModel('ExpenseReimbursement');
			$this->ExpenseReimbursement->saveAll($udata);
			if (isset($this->request->data['addmore'])){
				$this->redirect(array('controller' => 'expense','action'=>'reimbursementadd'));
			}else{
				$this->redirect(array('controller' => 'expense','action'=>'reimbursement'));
			}
			$this->redirect(array('controller'=>'expense','action'=>'reimbursement'));
			$this->Session->setFlash('Expense Reimbursement has been saved');
			
			
		}
		$this->_options();
	}
	
	public function reimbursementedit($id= null){
		$this->loadModel('Audit');
		$this->loadModel('ExpenseReimbursement');
		$this->ExpenseReimbursement->id = $id;
		$userData = $this->ExpenseReimbursement->read(null, $id);
        if (!$this->ExpenseReimbursement->exists()) {
            throw new NotFoundException(__('Invalid Expense Reimbursement'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->ExpenseReimbursement->save($this->request->data)) {
				
				$this->Audit->saveDeletedData($userData['ExpenseReimbursement']['id'], 'ExpenseReimbursement', $this->Auth->user('id') , serialize($userData),'Expense Reimbursement Has been updated', STATUS_EDIT);
				
				$this->Session->setFlash(__('The Expense has been updated'));
				if (isset($this->request->data['addmore'])){
					$this->redirect(array('controller' => 'expense','action'=>'reimbursementadd'));
				}else{
					$this->redirect(array('controller' => 'expense', 'action'=>'reimbursement'));
				}
			} else {
				$this->Session->setFlash(__('The Expense could not be saved. Please, try again.'));
			}
		}else {
            $this->request->data = $this->ExpenseReimbursement->read(null, $id);
			$this->_options();
			//if($set_var){
			$this->render('reimbursementadd');
			//}
        }
	}
	
		public function reimbursementview($id=0){
		$this->loadModel('ExpenseReimbursement');
		$conditions = array();
		$this->Expense->_userCondition($conditions, $this->user);
		$this->ExpenseReimbursement->id = $id;
		$this->ExpenseReimbursement->belongsTo['Depot'] = array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('title'), 'type'=>'left');
		$this->ExpenseReimbursement->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
		$expensereimburse = $this->ExpenseReimbursement->read();
		if (!$expensereimburse){
			throw new NotFoundException(__('Invalid Expense reimbursement'));
		}
		$this->_options();
		$this->set('expensereimburse', $expensereimburse);
	}
	
	public function reimbursementdelete($id=null){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->loadModel('ExpenseReimbursement');
        $this->ExpenseReimbursement->id = $id;
        $expense = $this->ExpenseReimbursement->read();
		if (!$expense) {
            throw new NotFoundException(__('Invalid Expense Reimbursement'));
        }
		$data = array();
		$data['serialize'] = serialize($expense);
		$data['model_id'] = $expense['ExpenseReimbursement']['id'];//pr($data['model_id']);die();
        
        $deletedData = $this->ExpenseReimbursement->delete();
		$this->loadModel('Audit');
        if($deletedData){
			$this->Audit->saveDeletedData($data['model_id'], 'ExpenseReimbursement', $this->Auth->user('id') , $data['serialize'],'Expense Reimbursement Has been Deleted',STATUS_DELETE);
			
            $this->Session->setFlash(__('Expense Reimbursement was deleted successfully'));
        }
        $this->loadModel('ExpenseReimbursementDeleted');
        $data = array_merge($expense['ExpenseReimbursement'],array('deleteby_user_id' => $this->Auth->user('id'),'deleted_date' => date('Y-m-d H:m:s')));
	//	pr($data);die();
		$this->ExpenseReimbursementDeleted->saveAll($data);
        $this->Session->setFlash(__('Expense Reimbursement was not deleted'));
        $this->redirect(array('controller' => 'expense', 'action'=>'reimbursement'));
	}
	
	public function getCategory(){
		$result = array();
		
		$this->loadModel('ExpType');
		$exp_type = $this->ExpType->findById($this->request->data['exp_type_id']);
		echo json_encode($exp_type);
		exit;
	}

	public function getExpType(){
		$result = $typeList = array();
		$conditions = array();
		$this->loadModel('ExpType');

		if (!empty($this->request->data['cat_id'])){
			$categoryId = $this->request->data['cat_id'];
		}else{
			$categoryId = 0;
		}
		//pr($this->request->data);
		if(!empty($this->request->data['eoption']) && $this->request->data['eoption'] == 'setsel'){
            $toption = array();
        }else{
            $toption = array("0"=>__('All'));
        }
		if($this->request->data['cat_id']){
			$typeList = $this->ExpType->find('list',array('fields'=>array('id','name'),'conditions'=>array('category_id'=>$categoryId),));
		}else{
			$typeList = $this->ExpType->find('list',array('fields'=>array('id','name')));
		}
		$result['typeList'] = $toption + $typeList;
		echo json_encode($result);
		exit;
	}
	

}
