<?php

/**
* @version 2.8.11
* @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
*/

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

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

class pxpay extends Payment 
{
	var $last_error;                 // holds the last error encountered
   
	var $fields = array();           // array holds the fields to submit to paypal

	var $bywebservice = false;
   
	function __construct()
	{
		global $pxpay_username,$pxpay_password;
		
		parent::__construct();
	}
		
	function process()
	{
        global $currency_code,$cardtype,$pxpay_username,$pxpay_password;
        $mosConfig_live_site = JURI::root( false );
        
		if($currency_code==""){$currency_code='USD';}
		
		$session_id = $this->saveSession();
		
		switch($cardtype[$this->cardtype])
		{			
			case 'AmericanExpress':
				$this->cardtype = 'Amex';
			break;
			default:
				 $this->cardtype = $cardtype[$this->cardtype];
			break;
		}
		
		$year = $this->x_exp_date_year;
		$exp_date=$this->x_exp_date_month."/".$year;
	   
		$this->x_exp_date = $exp_date ;
		$card_expiry_array = explode("/", $this->x_exp_date);
		
		$firstName 			= urlencode($this->firstname);
		$lastName 			= urlencode($this->lastname);
		$creditCardType 	= urlencode($this->cardtype);
		$creditCardNumber 	= urlencode($this->x_card_num);
		$expDateMonth 		= urlencode($card_expiry_array[0]);
		$expDateYear 		= urlencode($card_expiry_array[1]);
		$cvv2Number 		= urlencode($this->x_card_code);
		$address1 			= urlencode($this->address);
		$address2 			= '';
		$city 				= urlencode($this->city);
		$state 				= urlencode($this->state);
		$zip 				= isset($this->zipcode)?urlencode($this->zipcode):'';
		$amount 			= urlencode($this->cart->getAmount());
		$currencyCode		= urlencode($currency_code);
		$email              = urlencode($this->email);
		$paymentAction 		= urlencode("Purchase");
		$description        = urlencode($this->description);
		
		$CardName = $firstName .' '. $lastName;
		$Amount = $amount;
		$CardNum = $creditCardNumber;
		$ExMnth = $expDateMonth;
		$ExYear = $expDateYear;
		$MerchRef = $description;			
						
		$cmdDoTxnTransaction = "";
				
		$cmdDoTxnTransaction .="<GenerateRequest>";
		
		$cmdDoTxnTransaction .="<PxPayUserId>$pxpay_username</PxPayUserId>";
		$cmdDoTxnTransaction .="<PxPayKey>$pxpay_password</PxPayKey>";
		
		$cmdDoTxnTransaction .="<AmountInput>$Amount</AmountInput>";
		$cmdDoTxnTransaction .="<CurrencyInput>USD</CurrencyInput>";
		$cmdDoTxnTransaction .="<MerchantReference>Test Transaction</MerchantReference>";
		$cmdDoTxnTransaction .="<EmailAddress>$email</EmailAddress>";
		$cmdDoTxnTransaction .="<TxnData1>$address1</TxnData1>";
		$cmdDoTxnTransaction .="<TxnData2>$city</TxnData2>";
			$cmdDoTxnTransaction .="<TxnData3></TxnData3>";
		$cmdDoTxnTransaction .="<TxnType>Purchase</TxnType>";
			$cmdDoTxnTransaction .="<TxnId></TxnId>";
			$cmdDoTxnTransaction .="<BillingId></BillingId>";
		$cmdDoTxnTransaction .="<EnableAddBillCard>0</EnableAddBillCard>";
		
		$successUrl = rawurlencode($mosConfig_live_site."components/com_dtregister/success.php?return=$session_id&amp;Itemid=$Itemid&amp;task=restore");
		$cancelUrl = rawurlencode($mosConfig_live_site."components/com_dtregister/success.php?return=$session_id&amp;Itemid=$Itemid&amp;task=cancel");
					
		$successUrl = $mosConfig_live_site."components/com_dtregister/success.php?return=$session_id&amp;x_cust_id=$session_id&amp;Itemid=$Itemid&amp;task=restore";
		$cancelUrl = $mosConfig_live_site."components/com_dtregister/success.php?return=$session_id&amp;x_cust_id=$session_id&amp;Itemid=$Itemid&amp;task=cancel";
								
		$cmdDoTxnTransaction .="<UrlSuccess>$successUrl</UrlSuccess>";
		$cmdDoTxnTransaction .="<UrlFail>$cancelUrl</UrlFail>";
		//$cmdDoTxnTransaction .="<Opt>c4bc8v4bcv8b</Opt>";
		$cmdDoTxnTransaction .="</GenerateRequest>";
									   
		//$URL = "sec.paymentexpress.com/pxpost.aspx";
		//$URL = "sec.paymentexpress.com/pxpay/pxaccess.aspx";
		$URL = "sec.paymentexpress.com/pxaccess/pxpay.aspx";
		        
        $curl_conn = curl_init();
		curl_setopt($curl_conn, CURLOPT_URL,"https://".$URL);
		curl_setopt($curl_conn, CURLOPT_HTTPGET, 1); 
		curl_setopt($curl_conn, CURLOPT_HEADER, 0);
		curl_setopt($curl_conn, CURLOPT_FAILONERROR,true);
		curl_setopt($curl_conn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				
		curl_setopt($curl_conn, CURLOPT_VERBOSE, 1);
		curl_setopt($curl_conn, CURLOPT_POST, 1);
		curl_setopt($curl_conn, CURLOPT_POSTFIELDS, $cmdDoTxnTransaction);
			
		curl_setopt($curl_conn, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($curl_conn, CURLOPT_RETURNTRANSFER, 1);
		// Send the request
		$result = curl_exec($curl_conn);        
       
        $result =  str_replace('<Request valid="1"><URI>','',$result);
		$result =  str_replace('</URI></Request>','',$result);
		$result =  str_replace('&amp;','&',$result);
		      
		$app	= JFactory::getApplication();
		$app->redirect($result);
	
	}
		
	function success(){
	   	   
	   	global $currency_code,$cardtype,$pxpay_username,$pxpay_password;   
	   	   	   	   
		if(isset($_REQUEST['result']))
		{
			$cmdDoTxnTransaction1 = "<ProcessResponse>
			<PxPayUserId>$pxpay_username</PxPayUserId>
			<PxPayKey>$pxpay_password</PxPayKey>
			<Response>".$_REQUEST['result']."</Response>
			</ProcessResponse>";
		   
		    //$URL = "sec.paymentexpress.com/pxpay/pxaccess.aspx";
		    $URL = "sec.paymentexpress.com/pxaccess/pxpay.aspx";
		        
			$curl_conn = curl_init();
			curl_setopt($curl_conn, CURLOPT_URL,"https://".$URL);
			curl_setopt($curl_conn, CURLOPT_HTTPGET, 1); 
			curl_setopt($curl_conn, CURLOPT_HEADER, 0);
			curl_setopt($curl_conn, CURLOPT_FAILONERROR,true);
			curl_setopt($curl_conn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
					
			curl_setopt($curl_conn, CURLOPT_VERBOSE, 1);
			curl_setopt($curl_conn, CURLOPT_POST, 1);
			curl_setopt($curl_conn,CURLOPT_POSTFIELDS,$cmdDoTxnTransaction1);
				
			curl_setopt($curl_conn, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($curl_conn, CURLOPT_RETURNTRANSFER, 1);
			// Send the request
			$result = curl_exec($curl_conn);        
		   
			$xml_parser = xml_parser_create();
			xml_parse_into_struct($xml_parser, $result, $vals, $index);
			xml_parser_free($xml_parser);
				 
			$params = array();
			$level = array();
			foreach ($vals as $xml_elem) {
				if ($xml_elem['type'] == 'open') {
					if (array_key_exists('attributes',$xml_elem)) {
						list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
					} 
					else {
						$level[$xml_elem['level']] = $xml_elem['tag'];
					}
				}
				if ($xml_elem['type'] == 'complete') {
					$start_level = 1;
					$php_stmt = '$params';
								 
					while($start_level < $xml_elem['level']) {
						$php_stmt .= '[$level['.$start_level.']]';
						$start_level++;
					}
					$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
					eval($php_stmt);
				}
			}
		   
			//$TransactionID = $params[1][TXNID];
			$TransactionID = $params[1][AUTHCODE];
		   				   
		    if($TransactionID){
				$this->transactionId = $TransactionID;
				$process = DT_Session::get('Setting.process');
				DT_Session::set($process.'.payment.transactionId', $this->transactionId);
											
				return true;
			}
			else
			{
				return false;
			}
						   
		}
		else
		{
			return false;
		}
				
	}

	
}
