<?php
App::uses('AppController', 'Controller');
class BudgetController extends AppController {
/**
 * Controller Warehouse
 *
 * @var string
 */
 var $components = array('Option');

 	/**
     * index method
     * @params : $data (array)
     * @return none
     */
	public function index(){
		//$this->gradPermission(1);
		$this->Budget->belongsTo = array('Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'type'=>'left'));
		$conditions = array();
		
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Budget.created BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to'].' 23:59:59'));			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Budget.created >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Budget.created <= '] = $this->request->query['to'].' 23:59:59';
		}
		
		//new code for filter go here
		if (!empty($this->request->query['dv']) ) {
            $division_id = $this->request->query['dv'];
             if(empty($this->request->query['rg']) && empty($this->request->query['dp'])){
                 $conditions[] = 'Budget.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
				}
        }else{
            $division_id = 0;
             if(!empty($this->user['division_id']) && $this->user['role_id'] == DIVISIONMANAGER){
                 $this->request->query['dv'] = $division_id = $this->user['division_id'];
                 if (empty($this->request->query['rg']) && empty($this->request->query['dp'])) {
                     $conditions[] = 'Budget.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
                 }
             }
        }
		if (!empty($this->request->query['rg']) ){
            $region_id = $this->request->query['rg'];
            if(empty($this->request->query['dp'])){
                $conditions[] = 'Budget.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
        }else{
            $region_id = 0;
            if ($this->user['Role']['grade'] == 3){
                $region_id = $this->user['region_id'];
            }
        }
		if (!empty($this->request->query['dp'])){
            $conditions['Budget.depot_id'] = $this->request->query['dp'];
        }
		//new code end

		$order=$this->paginate['order'] = array('Budget.budget_date' => 'desc','Budget.created' =>'desc');

		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		if(isset($this->request->query['export'])){   
			$budgets = $this->Budget->find('all',array('conditions'=>$conditions,'order'=>$order));				
			//pr($budgets);
			//$this->set('budgets', $budgets);
			;
		} else {
		   $budgets = $this->paginate('Budget', $conditions);
		   //$this->render('index');
		}
		$this->loadModel('Depot');

		$this->set('budgets', $budgets);
		
		$this->_selectOptions2();

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

	//new fn added for filter data
	function _selectOptions2(){
        $Opdata = isset($this->request->data['Budget'] ) ? $this->request->data['Budget']  : array();
        $param = !empty($this->request->query ) ? $this->request->query  : array();
        $this->Option->Options2($Opdata, $this->user,$param);
    }


	public function add(){
		//$this->gradPermission(1);
		if ($this->request->data){
			
			if (!empty($this->request->data['Budget']['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['Budget']['brand_id']))); 
				$this->request->data['Budget']['brand_group_id'] = $group_id[$this->request->data['Budget']['brand_id']]; 
			}
			
			$this->Budget->save($this->request->data);
			$this->Session->setFlash(__('Budget was added successfully'));
			$this->redirect(array('action'=>'index'));
			
		}
		$this->loadModel('Depot');
		
		$depots = $this->Depot->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
		
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name')));
		
		$this->loadModel('BrandGroup');
		$brand_groups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name')));
		
		$this->set(compact('depots','brands', 'brand_groups','budgetType'));
	}
	
	public function edit($id=0){
		$this->loadModel('Audit');
		$userData = $this->Budget->read(null, $id);
		//$set_var=$this->gradPermission(1);
		if ($this->request->data){
				
				if (!empty($this->request->data['Budget']['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['Budget']['brand_id']))); 
					$this->request->data['Budget']['brand_group_id'] = $group_id[$this->request->data['Budget']['brand_id']]; 
				}
			
				$this->Budget->save($this->request->data);
				$this->Audit->saveDeletedData($userData['Budget']['id'], 'Budget', $this->Auth->user('id') , serialize($userData),'Budget Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Budget was updated sucessfully'));
				$this->redirect('/budget');
			
		}
		
		if (!empty($id)){
			$this->Budget->id = $id;
			$this->request->data = $this->Budget->read();
		}
		//$this->loadModel('BudgetType');
		$this->loadModel('Depot');
		//$budgetType = $this->BudgetType->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->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name')));	

		$this->loadModel('BrandGroup');
		$brand_groups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name')));
		
		$this->set(compact('depots','brands', 'brand_groups','budgetType')); 
		//if($set_var){
		$this->render('add');
		//}
	}
	
	public function delete($id=0){
		if (!$id){
			$this->redirect('/budget');
		}
		$this->Budget->id = $id;
		$budget = $this->Budget->read();

		$data = array();
		$data['serialize'] = serialize($budget);
		$data['model_id'] = $budget['Budget']['id'];
		$this->Budget->delete();
		$this->loadModel('Audit');
		$this->Audit->saveDeletedData($data['model_id'], 'Budget', $this->Auth->user('id') , $data['serialize'],'Budget Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Budget was deleted successfully'));
		$this->redirect('/budget');
	}

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

	public function budgettypes(){
		//$this->gradPermission(1);
		$conditions = array();
		$this->loadModel('BudgetType');
		$order=$this->paginate['order'] = array('BudgetType.title' => 'asc');
        
		if(isset($this->request->query['export'])){   			
			$budgetTypes = $this->BudgetType->find('all', array('conditions' =>$conditions,'order'=>$order));	
		} else {
		    $budgetTypes = $this->paginate('BudgetType', $conditions);
		}
		$this->set('budgetTypes', $budgetTypes);
		
		if(isset($this->request->query['export'])){  
			$this->set('filename', 'budgetTypes');
			$this->render('export_budgettype','export_xls');
		}
		
	}
	public function addbudgettype(){
		//$this->gradPermission(1);
		$this->loadModel('BudgetType');
		if ($this->request->data){
			$is_exists = $this->BudgetType->find('count', array('conditions'=>array('LOWER(title)'=>strtolower($this->request->data['BudgetType']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['BudgetType']['title']));
			}else{
				$this->BudgetType->save($this->request->data);
				$this->Session->setFlash(__('Budget type was added successfully'));
				$this->redirect('/budget/budgettypes');
			}
		}
	}
	
	public function updatebudgettype($id=0){
		//$set_var=$this->gradPermission(1);
		if (!$id){
			$this->redirect('/budget/budgettypes');
		}
		$this->loadModel('BudgetType');
		if ($this->request->data){			
			
			$is_exists = $this->BudgetType->find('count', array('conditions'=>array('LOWER(title)'=>strtolower($this->request->data['BudgetType']['title']), 'id !=' => $this->request->data['BudgetType']['id'])));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['BudgetType']['title']));
			}else{
				$this->BudgetType->save($this->request->data);
				$this->Session->setFlash(__('Brand was updated successfully'));
				$this->redirect('/budget/budgettypes');
			}
		}
		
		
		$this->request->data = $this->BudgetType->find('first', array('conditions'=>array('md5(id)'=>$id) ) );
		$this->render('addbudgettype');
	}
	public function deletebudgettype($id=0){
		//$this->gradPermission(1);
		if (!$id){
			$this->redirect('/budget/budgettypes');
		}
		$this->loadModel('BudgetType');
		$this->BudgetType->deleteAll(array('md5(id)'=>$id));
		
		$this->Session->setFlash(__('Budget type was deleted successfully'));
		$this->redirect('/budget/budgettypes');
		exit;
	}
	
	public function deleteAllbudgettype(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('BudgetType');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->BudgetType->deleteAll(array('BudgetType.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected budget types was deleted successfully') );
			$this->redirect(array('action'=>'budgettypes'));
		}
		exit;
	}
}