<?php
App::uses('CakeTime', 'Utility');
class InvpaidsController extends AdminAppController
{
    public $components = array('Session','Paginator','search-master.Prg');
    public $helpers=array('Paginator','Js'=> array('Jquery'));
    public $presetVars = true;
    var $paginate = array('page'=>1,'order'=>array('PlansPayment.payment_date'=>'desc'));

    public function index()
    {
        if(isset($this->request->named['isSearch']))
        {
            $requestStartDate=$this->CustomFunction->dateFormatBeforeSave($this->request->named['start_date']);
            $requestEndDate=$this->CustomFunction->dateFormatBeforeSave($this->request->named['end_date']);
            $conditions=array();
            if(strlen($requestStartDate)>0 && strlen($requestEndDate)>0)
            $conditions=array('DealsPayment.payment_date BETWEEN ? AND ?'=>array($requestStartDate,$requestEndDate));
        }
        else
        {
            $startDate=CakeTime::format('Y-m-01',CakeTime::convert(time(),$this->siteTimezone));
            $endDate=CakeTime::format('Y-m-31',CakeTime::convert(time(),$this->siteTimezone));
            $conditions=array('DealsPayment.payment_date BETWEEN ? AND ?'=>array($startDate,$endDate));
        }
        $condition=$this->CustomFunction->agencyWisePermission(NULL,$this->userType,$this->agencyId,'Property.project_id');
        $this->Prg->commonProcess();
        $this->Paginator->settings = $this->paginate;
        $this->Paginator->settings['fields'] =array('Contact.name','Contact.phone','Contact.id','Property.name','Invpaid.invoice_no','Invpaid.id','DealsPayment.total_amount','DealsPayment.payment_date','DealsPayment.tax_amount','DealsPayment.amount','PlansPayment.name');
        $this->Paginator->settings['conditions'] = array($this->Invpaid->parseCriteria($this->Prg->parsedParams()),$conditions,$condition);
		$this->Paginator->settings['limit']=$this->pageLimit;
        $this->Paginator->settings['maxLimit']=$this->maxLimit;
        $this->set('deal', $this->Paginator->paginate());
    	if ($this->request->is('ajax'))
        {
            $this->render('index','ajax'); // View, Layout
        }
    }
    public function deleteall(){
        $action=isset($this->request->data['action']) ? $this->request->data['action'] : '';
        try
        {
            if ($this->request->is('post'))
            {
            	$this->loadModel('DealsPayment');
            	$this->loadModel('Property');
                foreach($this->data['Invpaid']['id'] as $key => $value){
                    if($value!=0){
                        $expArr=explode(",",$value);
			try{
				$DealID = $expArr[1];
				//Getting Deal Information
				$Deal = $this->Invpaid->findById($DealID);
				$PropertyID = $Deal['Property']['id'];
				//Getting Property Information
				$Payment = $this->Property->findById($PropertyID);
			        $CommissionType = $Payment['Property']['commission_type'];
			        $Commission = $Payment['Property']['agent_commission'];
			        //Reverting Agent Comission
			        $AgentID = $Deal['Invpaid']['user_id'];
			        if(strlen($AgentID ) > 0){
			 		$EMI = $Deal['PlansPayment']['amount'];
			        	$Extra = $Deal['DealsPayment']['extra_payment'];
			        	$TotalAmount = $EMI + $Extra;
				        if($CommissionType == "Percentage" && $Commission != null){
				        	$Commission = ($Commission * $TotalAmount)/100;
			                }
		                	$this->CustomFunction->awalletInsert($AgentID,$Commission,'DBT','Reverting Commission',$Deal['DealsPayment']['id']);
		                }

		                //Removing Deal Payments
				$this->DealsPayment->deleteAll(array(
					'deal_id'=>$DealID
				),false);
				//Removing Current Row
				//$this->Invpaid->delete($DealID);
				$this->Session->setFlash(__('Invoice has been deleted'),'flash',array('alert'=>'success'));
	                }catch(Exception $e){
	                	echo $e->getMessage();die();
	                }
                    }
                }
            }
            $this->redirect(array('action' => 'index'));
        }
        catch (Exception $e)
        {
            $this->Session->setFlash($e->getMessage,'flash',array('alert'=>'danger'));
            return $this->redirect(array('action' => 'index'));
        }
    }
}
