<?php

/**
* @version 2.8.17
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

class DtregisterControllerPayment extends DtrController {

   var $name = "payment";

    function __construct($config = array()){

		 parent::__construct($config);

		 $this->view = & $this->getView( 'payment', 'html' );

		 $this->view->setModel($this->getModel('paymentmethod'));

		 $this->view->setModel($this->getModel('user'));
		
		 $this->view->setModel($this->getModel('event'));
		   
         $evtTable = $this->getModel('event')->table;  //prd($_SESSION);
		 if(DT_Session::get('Setting.eventId')){
		   $evtTable->slabId = DT_Session::get('Setting.eventId');
		   $evtTable->overrideGlobal(DT_Session::get('Setting.eventId'));
		 }
		 $process = DT_Session::get('Setting.process');
		 if(DT_Session::get($process.'.User.eventId') || DT_Session::get($process.'.User.0.eventId')){
			 if(DT_Session::get($process.'.User.eventId')){
				$evtTable->slabId = DT_Session::get($process.'.User.eventId');
			    $evtTable->overrideGlobal(DT_Session::get($process.'.User.eventId'));
			 } else {
				 $confirm_num_array =  array();
				 $users = array();
				 foreach(DT_Session::get($process.'.User') as $key=>$user) {
					 if(isset($user[$user['confirmNum']])) {
					    continue;
					 }
					 $users[] = $user;
					 $confirm_num_array[$user['confirmNum']] = $user['confirmNum'];
				 }
				
				 DT_Session::set($process.'.User',$users);
				 $evtTable->slabId = DT_Session::get($process.'.User.0.eventId');
				 $evtTable->overrideGlobal(DT_Session::get($process.'.User.0.eventId'));
			 }
		    
		 }
		
		$this->evtTable = $evtTable;
		
		$this->cart = new DT_Cart();

	}

	function methods(){
        global $mainframe,$offline_zero_credit,$depend_on_field,$field_options,$paylater_field,$paylater_field_options,$Itemid;
		$this->view->setLayout('options');
		$cart = new DT_Cart();
		$amount = $cart->getAmount();
		
		$process = DT_Session::get('Setting.process');
		if(Comp($amount,0,10) < 1){
			 $messageTask = 'index';
			 if(DT_Session::get('Setting.process')=="register"){
                if($offline_zero_credit) {
					$display_offline = false;
					if($depend_on_field != "") {
						
						foreach(DT_Session::get('register.User')  as $user) {
							
							if(isset($user['fields'][$depend_on_field])) {
								if(in_array($user['fields'][$depend_on_field] , $field_options)) { // display offline 
									$display_offline = true;
									break;
								} else{
									continue;
								}
							} else {
								continue;
							}
							
						}
					} else{
						$display_offline = true;
					}
					
					if($display_offline) {
						 
						$mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=payment&Itemid=$Itemid&task=form&paymentmethod=offline_payment",false));
					} else {
						
					    $function = 'registerall';
						$messageTask = 'freethanks';
					}
					
				} else {
					
					$function = 'registerall';
					$messageTask = 'freethanks';
					
				}

			 }else{

					  $function = DT_Session::get('Setting.process');

			 }
			 
			 $tableUser = $this->getModel('user')->table; 
			
			 $tableUser->{$function}(DT_Session::get($process),null); 
			 
			 
 $mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=message&Itemid=$Itemid&task=".$messageTask,false));
			 
		}
		if(DT_Session::get('Setting.process')){
			$this->view->assign('header_eventId',DT_Session::get($process.'.User.0.eventId'));
		}
        
		$this->view->display();

	}

	function billinginfo(){

	   global $mainframe,$Itemid;
       $this->getModel('field');
	   $process = DT_Session::get('Setting.process');
	   if(isset($_POST['billing'])){
           
		   DT_Session::set($process.'.payment.billing',$_POST['billing']);
 $mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=payment&task=form&Itemid=".$Itemid,false));

	   }
	   
	    if(DT_Session::get('Setting.process')){
			$this->view->assign('header_eventId',$this->evtTable->slabId);
		} 
        $billingInfo = DT_Session::get($process.'.payment.billing');
	   	$paymentClass = DT_Session::get($process.'.payment.method');

		if(!is_numeric($paymentClass)){
			//require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');
			$payment = DTreg::getPaymentInstance($paymentClass);
			$payment->setBillinginfo($billingInfo);
			$form = $payment->billingform();			
		} else {
			
			$tableUser = $this->getModel('user')->table;
			$paymethod = DT_Session::get($process.'.payment.method');
			 
			$tableUser->registerall(DT_Session::get($process),$paymethod);
			//$mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=message&task=paylater&Itemid=".$Itemid,false));
			
		}  

		$this->view->assign('form',$form);

	    $this->display();

	}

	function notification(){
	    global $Itemid,$mainframe,$DT_mailfrom,$DT_fromname;
		ob_start();
		if(file_exists(JPATH_BASE."/components/com_dtregister/lib/payment/payway/net.php")) {
		require_once(JPATH_BASE."/components/com_dtregister/lib/payment/payway/net.php");
		if(isset($_REQUEST['EncryptedParameters'])) {  // payway 
    
    $encryptedParametersText = $_GET['EncryptedParameters'];
    $signatureText = $_GET['Signature'];

    $_GET= $_POST = $_REQUEST = decrypt_parameters( $encryptedParametersText, $signatureText );
   
}
debugLog( var_export($_REQUEST,true) );
		}

		$process = DT_Session::get('Setting.process');
	    $paypal_session_id = JRequest::getVar('return',$_REQUEST['x_cust_id']);
		
		DT_Session::restoreFromPayment($paypal_session_id);
		$process = DT_Session::get('Setting.process');
		$paymethod = DT_Session::get($process.'.payment.method');
		$paymentClass = DT_Session::get($process.'.payment.method');
		//require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');
		$payment = DTreg::getPaymentInstance($paymentClass);
		$notify = $payment->notify();
		//$notify = true;
		if($notify){
		    
			if(!$payment->bywebservice){

			 // session restore here;
             $messageTask = 'index';
			 if(DT_Session::get('Setting.process')== "register"){

					  $function = 'registerall';
					  $messageTask = 'thanks';

			 }else{

					  $function = DT_Session::get('Setting.process');

			 }
			 
			 $processed = DT_Session::get($process.'.restore.processed');
		  
			// pr(DT_Session::get('register'));
		    if($processed !== false && $processed == "0"){ 
		      
				$tableUser = $this->getModel('user')->table; 
				$paymethod = DT_Session::get($process.'.payment.method');
			    $tableUser->{$function}(DT_Session::get($process), $paymethod);	
				$payment->markprocessed(DT_Session::get($process.'.restore.id'),$tableUser->userId);
			}  

		 }	else {
		 	// marked as processed  so when auto return it do not save on failed IPN
			//$payment->markprocessed(DT_Session::get('register.restore.id'),0);
		 }
			
		}
      echo   $body = ob_get_clean();
		
		DT_Session::clearAll();
		if(isset($payment->return_notify_html)) {
		   echo $body;
		   header( 'HTTP/1.0 200 OK' );
           flush();
	   
		}
		die("reached");
	}
	
	function restore(){
	    global $Itemid,$mainframe;
		if(isset($_REQUEST['EncryptedParameters'])) {  // payway 
    require_once(JPATH_BASE."/components/com_dtregister/lib/payment/payway/net.php");
    $encryptedParametersText = $_GET['EncryptedParameters'];
    $signatureText = $_GET['Signature'];

    $_GET= $_POST = $_REQUEST = decrypt_parameters( $encryptedParametersText, $signatureText );
	
   
}
	    $paypal_session_id = JRequest::getVar('return',$_REQUEST['x_cust_id']);
		DT_Session::restoreFromPayment($paypal_session_id);
		$paymethod = DT_Session::get($process.'.payment.method');
		$process = DT_Session::get('Setting.process');
   		$paymentClass = DT_Session::get($process.'.payment.method');
   		//require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');
   		$payment = DTreg::getPaymentInstance($paymentClass);
		$baseurl = str_replace('components/com_dtregister/','',Juri::base());
		if(isset($_REQUEST['x_cust_id'])) {
			if($payment->success()) {
				
			  $this->success();
			 
			} else {
			   if($payment->retry) {
				    $_SESSION['gateway_error'] = $payment->errorMsg;
				   $payment->update_session($paypal_session_id);
			        $this->retry();
				   
			   } else {
				  
			      $this->cancel();
				  
			   }
			}
		}
		
  		if(!isset($_REQUEST['failed']) && (isset($_REQUEST['passed']) || $payment->success())){
		   $mainframe->redirect($baseurl."index.php?option=com_dtregister&controller=payment&task=success&Itemid=$Itemid");
		}elseif($payment->retry == false && !isset($_REQUEST['retry']) ){
		   $mainframe->redirect($baseurl."index.php?option=com_dtregister&controller=payment&task=cancel&Itemid=$Itemid");
		}elseif($payment->retry || isset($_REQUEST['retry'])){
		   $mainframe->redirect($baseurl."index.php?option=com_dtregister&controller=payment&task=retry&Itemid=$Itemid");
		}

	}
    
	function retry() {
		
		$process = DT_Session::get('Setting.process');
   		$paymentClass = DT_Session::get($process.'.payment.method');
   		//require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');
   		$payment = DTreg::getPaymentInstance($paymentClass);
		
		if(isset($_REQUEST['x_cust_id'])) {
		 	
			echo Jtext::_('DT_REDIRECTING_TO_SITE');
			?>
            
             <script>
			    window.location = "<?php echo Juri::base()."success.php?return=".$_REQUEST['x_cust_id']."&retry=1" ?>";
			 </script>
            <?php
			die;
		 } else {
			
	     echo Jtext::_('DT_PAYMENT_DECLINED');
		 echo "<p>".$_SESSION['gateway_error']."</p>";
		 unset($_SESSION['gateway_error']);
		$payment->afterFailed();
		echo $payment->tryagain();
		}
		
	}
	
	function success(){

	  	global $Itemid,$mainframe;
		$tableUser = $this->getModel('user')->table;
		$process = DT_Session::get('Setting.process');
        $paymentClass = DT_Session::get($process.'.payment.method');
       // require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');
		$payment = DTreg::getPaymentInstance($paymentClass);

		if(!$payment->bywebservice){

			 // session restore here;
             $messageTask = 'index';
			 if(DT_Session::get('Setting.process')=="register"){

					  $function = 'registerall';
					  $messageTask = 'thanks';

			 }else{

					  $function = DT_Session::get('Setting.process');
					  $messageTask = DT_Session::get('Setting.process');

			 }
			 
			 $processed = DT_Session::get($process.'.restore.processed');
		 //if(1){
		    if($processed !== false && $processed === "0"){
				$paymethod = DT_Session::get($process.'.payment.method');
			    $tableUser->{$function}(DT_Session::get($process), $paymethod);
				$payment->markprocessed(DT_Session::get($process.'.restore.id'),$tableUser->userId);
			 }

		 }
		 if(isset($_REQUEST['x_cust_id'])) {
			 echo Jtext::_('DT_REDIRECTING_TO_SITE');
		 	?>
             <script>
			    window.location = "<?php echo Juri::base()."success.php?return=".$_REQUEST['x_cust_id']."&passed=1" ?>";
			 </script>
            <?php
			die;
		 }
         //DT_Session::clearAll();
		 $mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=message&Itemid=$Itemid&task=".$messageTask,false));
		 echo "event details Thanks";

	}

	function cancel(){

       global $xhtml_url,$Itemid; 
	  	
       $msg = '<h3>'.JText::_( 'DT_PAYMENT_CANCELLED' ).'</h3>';
	   
       DT_Session::clearAll();
	
	if(isset($_REQUEST['x_cust_id'])) {
		 	
			echo Jtext::_('DT_REDIRECTING_TO_SITE');
			?>
            
             <script>
			    window.location = "<?php echo Juri::base()."success.php?return=".$_REQUEST['x_cust_id']."&failed=1" ?>";
			 </script>
            <?php
			die;
		 }
	
         echo $msg.'<a href="'. JRoute::_('index.php',$xhtml_url).'">'.JText::_( 'RETURN_TO_SITE' ).'</a>';
	}

	function form(){
		global $Itemid;
		$process = DT_Session::get('Setting.process');
		if(DT_Session::get('Setting.process') == 'register'){
			$this->view->assign('header_eventId',DT_Session::get($process.'.User.0.eventId'));
			$this->header_eventId = DT_Session::get($process.'.User.0.eventId');
		}
		
        if(DT_Session::get('Setting.process') !='register'){
			$this->header_eventId = DT_Session::get($process.'.User.0.eventId');	
            //include(JPATH_SITE.DS.'components'.DS.'com_dtregister'.DS.'views'.DS.'user'.DS.'tmpl'.DS.'event_header.php');
			include(DTreg::get_template_path('user'.DS.'tmpl'.DS.'event_header.php'));
        }else{
			
       ?>
         <div class="componentheading"><?php echo JText::_('DT_EVENT_REGISTRATION')?>: <?php echo JText::_( 'DT_PAYMENT' );?>

		</div>
      <?php	
        }
		global $mainframe,$Itemid,$authorizenet_type,$moneris_type;
		$userIndex = DT_Session::get('Setting.current.userIndex');
		if($userIndex !== false && $userIndex !=""){
           DT_Session::clear($process.'.User.'.$userIndex.'.TableEvent');
		   DT_Session::clear($process.'.User.'.$userIndex.'.TableUser');
		}
		$billingInfo = DT_Session::get($process.'.payment.billing');
	
		if(isset($_REQUEST['paymentmethod'])){

		   	if($_REQUEST['paymentmethod']=="pay_later"){

				DT_Session::set($process.'.payment.method',$_REQUEST['pay_later_option']);

			}else{
				
               if($_REQUEST['paymentmethod'] == "authorizenet" && $authorizenet_type == "sim") {
			   		$_REQUEST['paymentmethod'] = "authorizenet_sim";
			   }
			    if($_REQUEST['paymentmethod'] == "moneris" && $moneris_type == "directpost") {
			   		$_REQUEST['paymentmethod'] = "moneris_directpost";
			   }
			   
			    if($_REQUEST['paymentmethod'] == "dt_pay" && $dtpay_type == "sim") {
			   		$_REQUEST['paymentmethod'] = "dt_pay_sim";
			   }
			  
			   DT_Session::set($process.'.payment.method',$_REQUEST['paymentmethod']);
               
			}

		}
		
		$no_billing = array('paypal','pay_later','saferpay','Eway', 'psigate','payfast','korta','worldpay','dt_pay_sim','authorizenet_sim','moneris','epdq');
        
		$paymentClass = DT_Session::get($process.'.payment.method');
		if(!is_numeric($paymentClass)){
			//require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');
			$payment = DTreg::getPaymentInstance($paymentClass);
		}else{
			
		}
		
		if(empty($billingInfo) && (!in_array($paymentClass,$no_billing) || (!is_numeric($paymentClass) && $payment->bywebservice)) && $_REQUEST['paymentmethod'] != "pay_later" && !is_numeric($paymentClass) || ($paymentClass == 'ideal' && empty($billingInfo))){
			if(isset($payment->billing) && $payment->billing === false) {}else{
			  $mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=payment&task=billinginfo&Itemid=".$Itemid,false));
			}

	   }

	    $tableUser = $this->getModel('user')->table;

		$paymentClass = DT_Session::get($process.'.payment.method');

		if(isset($_REQUEST['paymentmethod']) && $_REQUEST['paymentmethod']=="pay_later"){			 

			 $paymethod = DT_Session::get($process.'.payment.method');
			 
			 $tableUser->registerall(DT_Session::get($process),$paymethod);
			 $mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=message&task=paylater&Itemid=".$Itemid,false));
			
		}else{

		  //require_once( JPATH_SITE.'/components/com_dtregister/lib/payment/'.$paymentClass.'.php');

		  // prd($billingInfo);
		
		  $payment->setBillinginfo($billingInfo);
			 if(DT_Session::get('Setting.process')=="register"){

					  $function = 'registerall';
					  $messageTask = 'thanks';
					  
					  $count = count(DT_Session::get('register.User'));
					  
					  $payment->confirmNum = DT_Session::get('register.User.0.confirmNum');
					  if ($count == 1) {
					  		$payment->description = $this->evtTable->title;  
					  } else {
						  	$payment->description = JText::_('DT_EVENT_PAYMENT_DESCRIPTION');
					  }

				  }else{

					  $function = DT_Session::get('Setting.process');
					  $payment->confirmNum = DT_Session::get($process.'.User.0.confirmNum');
					  
					  $payment->description = $this->evtTable->title;

				  }	

		  $success = $payment->process();
          		  
		   if($payment->bywebservice){

			 if($success === true ){
                 	 
                  $paymethod = DT_Session::get($process.'.payment.method');
				   
				   if(DT_Session::get('Setting.process') === false || DT_Session::get('Setting.process')=="register"){
					    $function = 'registerall';
				   		$messageTask = 'thanks';
				   }else{
				        $messageTask = DT_Session::get('Setting.process');
						$function = DT_Session::get('Setting.process');
				   }	   
				   
				  $tableUser->{$function}(DT_Session::get($process),$paymethod);		 
				  $mainframe->redirect(JRoute::_("index.php?option=com_dtregister&controller=message&Itemid=$Itemid&task=".$messageTask,false));

			  }else if($success === false){

				  $payment->afterFailed();

				  echo $payment->tryAgain();

			  }

		   }
		   
		}

	  	$this->view->setLayout('form');

		$this->view->display();

	}

}