<?php
App::uses('AppController', 'Controller');
	
/**
 * Controller name
 *
 * @var string
 */
class PaymentController extends AppController {
	var $helpers = array('Number');
	var $components = array('Option');
	public function index(){
		//$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['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
            if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                $conditions['User.division_id'] = $this->request->query['dv'];
            }
            if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
                $conditions['User.region_id'] = $this->request->query['rg'];
            }
            if (!empty($this->request->query['dp'])){
                $conditions['User.depot_id'] = $this->request->query['dp'];
            }

        }
		if ( !empty($this->request->query['ds'])){
			$conditions['Payment.distributor_id'] = $this->request->query['ds'];
		}
		if ( !empty($this->request->query['pm'])){
			$conditions['Payment.payment_mode'] = $this->request->query['pm'];
		}
		if ( !empty($this->request->query['bn'])){
			$conditions['Payment.bank_id'] = $this->request->query['bn'];
		}
		if ( !empty($this->request->query['bg'])){
			$conditions['Payment.brand_group_id'] = $this->request->query['bg'];
		}
		if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
			$conditions[] = array('Payment.payment_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));
			
		}elseif (!empty($this->request->query['from'])){
			$conditions['Payment.payment_date >= '] = $this->request->query['from'];
		} elseif (!empty($this->request->query['to'])){
			$conditions['Payment.payment_date <= '] = $this->request->query['to'];
		}
		
		if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
			$conditions['Payment.status'] = $this->request->query['sts'];
		}
		
		if (isset($this->request->query['via_app']) && $this->request->query['via_app']!='' ){
            $conditions['Payment.via_app'] = $this->request->query['via_app'];
        }
		
		$this->_userCondition($conditions);
		
		$totalPayment = $this->Payment->find('all', array('fields'=>array('SUM(Payment.amount) AS totalPayment'), 'conditions'=>$conditions));
		
		$order=$this->paginate['order'] = array('Payment.created' => 'desc','Payment.payment_date' => 'desc');
		$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;
			}	
			$payments = $this->Payment->find('all', array('conditions' =>$conditions,'order'=>$order,'limit'=>'10000','offset'=>$offset));			
		} else {
		    $payments = $this->paginate('Payment', $conditions);
	    }
		$Opdata = isset($this->request->data['Payment'] ) ? $this->request->data['Payment']  : array();
		$this->Option->Options($Opdata, $this->user);
		
		$this->_options();
		
		
		$this->loadModel('BrandGroup');
        $brand_groups = $this->BrandGroup->find('list', array('fields'=>array('id', 'name')));
		
		$this->set(compact('payments', 'depots','totalPayment','offset', 'brand_groups'));
		if(isset($this->request->query['export'])){ 
			$this->set('filename','Payments');
			$this->render('export_payment','export_xls');
		}
		
	}
	public function add(){
		//$set_var = $this->gradPermission(1);
		if ($this->request->data){
			$this->request->data['Payment']['user_id'] = $this->user['id'];
			if(empty($this->request->data['Payment']['depot_id'])){
				$this->request->data['Payment']['depot_id'] = $this->Auth->user('depot_id');
			}
			if(empty($this->request->data['Payment']['region_id'])){
				$this->request->data['Payment']['region_id'] = $this->Auth->user('region_id');
			}
			
			if (empty($this->request->data['Payment']['depot_id']) && !empty($this->user['depot_id'])){
				$this->request->data['Payment']['depot_id'] = $this->user['depot_id'];
			}
			if (empty($this->request->data['Payment']['payment_date'])){
				$this->request->data['Payment']['payment_date'] = date('Y-m-d H:i:s');
			}		

			if (!empty($this->request->data['Payment']['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['Payment']['brand_id']))); 
				$this->request->data['Payment']['brand_group_id'] = $group_id[$this->request->data['Payment']['brand_id']]; 
			}
			
			$this->Payment->save($this->request->data);
			$this->Session->setFlash(__('Payment was added successfully'));
			$this->redirect(array('action'=>'index'));
		}
		$Opdata = isset($this->request->data['Payment'] ) ? $this->request->data['Payment']  : array();
		$this->Option->Options($Opdata, $this->user);
		$this->_options();
		//if(!$set_var && $this->user['Role']['grade'] != 4){
			//$this->render('/Errors/access_denied');
		//}
	}
	public function edit($id){
		$this->loadModel('Audit');
		$userData = $this->Payment->read(null, $id);
		$this->roleBasePermission(array(SUPPORT));
		//$set_var=$this->gradPermission(1);
		if ($this->request->data){
			
			if (!empty($this->request->data['Payment']['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['Payment']['brand_id']))); 
				$this->request->data['Payment']['brand_group_id'] = $group_id[$this->request->data['Payment']['brand_id']]; 
			}
			
			$this->Payment->save($this->request->data);
			$this->Audit->saveDeletedData($userData['Payment']['id'], 'Payment', $this->Auth->user('id') , serialize($userData),'Payment Has been updated', STATUS_EDIT);
			$this->Session->setFlash(__('Payment was updated successfully'));
			$this->redirect(array('action'=>'index', '?'=> $this->request->query));
		}else{
			$this->Payment->id = $id;
			$this->request->data = $this->Payment->read();
			$this->_options();
		}
		$Opdata = isset($this->request->data['Payment'] ) ? $this->request->data['Payment']  : array();
		$this->Option->Options($Opdata, $this->user);
		//if(!$set_var && $this->user['Role']['grade'] != 4){
			//$this->render('/Errors/access_denied');
		//}else{
			
			$this->render('add');
		//}
	}
	public function delete($id){
		
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Payment->id = $id; //pr($this->request->query); die();
        if (!$this->Payment->exists()) {
            throw new NotFoundException(__('Invalid payment'));
        }
		$payment = $this->Payment->read();

		$data = array();
		$data['serialize'] = serialize($payment);
		$data['model_id'] = $payment['Payment']['id'];
        if ($this->Payment->delete()) {
			$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Payment', $this->Auth->user('id') , $data['serialize'],'Payment Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Payment was deleted successfully'));
            $this->redirect(array('action' => 'index', '?'=> $this->request->query));
        }
        $this->Session->setFlash(__('Payment was not deleted'));
        $this->redirect(array('action' => 'index', '?'=> $this->request->query));
	}
	
	public function deleteAllExpense(){
	
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Payment->deleteAll(array('Payment.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected payments was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
	
	function _options(){
		$this->loadModel('Bank');
		$this->loadModel('Distributor');
		$banks = $this->Bank->find('list', array('fields'=>array('id', 'name'),'order'=>array('name'=>'asc')));
		$distributors = $this->Distributor->find('list', array('fields'=>array('id', 'title'),'order'=>array('title'=>'asc')));
		$payment_mode = $this->_payment_mode();
		$this->loadModel('Brand');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name')));
		$this->set(compact('banks','payment_mode','distributors','brands'));
	}
	function _payment_mode($key=''){
	
		$payment_mode = array('Bank Deposit' => 'Bank Deposit', 'Cash'=>'Cash', 'Cheque'=>'Cheque', 'Other' => 'Other');
		if($key){
			return $payment_mode[$key];
		}else{
			return $payment_mode;
		}
	}
	
	function _userCondition(&$conditions){
		switch($this->user['Role']['grade']){
			case 2:
                if($this->user['role_id'] == DIVISIONMANAGER){
                    $conditions[] = 'Payment.depot_id IN (SELECT id FROM depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = '.$this->user['division_id'].'))';
                }
                break;
			case 3:
				$conditions[] = 'Payment.depot_id IN (SELECT id FROM depots WHERE region_id = '.$this->user['region_id'].')';
			break;
			case 4:
				$conditions['Payment.depot_id'] = $this->user['depot_id'];
			break;
			case 5:
				$conditions['Payment.user_id'] = $this->user['id'];
			break;
			case 6:
				$conditions['Payment.user_id'] = $this->user['id'];
			break;
			
		}
	}
	
	function view($id){
		//$this->gradPermission(4);
	//	if ($this->user['Role']['grade']==3 ){
		//	$this->render('/Errors/access_denied');
			//return false;
		//}
		$conditions = array();
		$this->_userCondition($conditions);
		
		$this->Payment->id = $id;
		$this->Payment->belongsTo['Depot'] = array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('title'), 'type'=>'left');
		$this->Payment->belongsTo['Brand'] = array('className' => 'Brand', 'foreignKey' => 'brand_id', 'fields' => array('name'), 'type'=>'left');
		$this->Payment->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
		
		$payment = $this->Payment->read();
		$this->set('payment', $payment);
	}
}
