<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: eWayModel.php, v 1.0 2011/06/14 20:52:11

//
class EWayModel extends PaymentModel
{
    public function process($order = '',$orderItems = '')//payment processing
    {
		$ObjCountry     = new CountryModel();
		$ObjState       = new StateModel();
		//define script constants
        define('REAL_TIME', 'REAL_TIME');
        define('REAL_TIME_CVN', 'REAL_TIME_CVN');
        define('GEO_IP_ANTI_FRAUD', 'GEO_IP_ANTI_FRAUD');
		
		$ObjCurrency	= new CurrencyModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $ewayPaymentMethod = REAL_TIME;
        // Set this to the payment gatway you would like to use (REAL_TIME, REAL_TIME_CVN or GEO_IP_ANTI_FRAUD)
        $ewayUseLive       = false;
        // Set this to true to use the live gateway
        $useLive           = urlencode($this->settingsVars["payment_test"]);
        if ($useLive == "On") {
            $useLive = false;
        } else {
            $useLive = true;
        }
        $ewayCustomerID    = urlencode($this->settingsVars["customer_id"]);
        $ewayPaymentMethod = REAL_TIME;
        $ewayUseLive       = $useLive;
        define('EWAY_DEFAULT_CUSTOMER_ID', $ewayCustomerID);
        define('EWAY_DEFAULT_PAYMENT_METHOD', $ewayPaymentMethod);
        define('EWAY_DEFAULT_LIVE_GATEWAY', $ewayUseLive);
       
        //define URLs for payment gateway
        define('EWAY_PAYMENT_LIVE_REAL_TIME', 'https://www.eway.com.au/gateway/xmlpayment.asp');
        define('EWAY_PAYMENT_LIVE_REAL_TIME_TESTING_MODE', 'https://www.eway.com.au/gateway/xmltest/testpage.asp');
        define('EWAY_PAYMENT_LIVE_AUTH_ONLY', 'https://www.eway.com.au/gateway/xmlauth.asp');
        define('EWAY_PAYMENT_LIVE_AUTH_ONLY_TESTING_MODE', 'https://www.eway.com.au/gateway/xmlauth.asp');
        //define('EWAY_PAYMENT_LIVE_AUTH_ONLY', 'https://www.eway.com.au/gateway/xmlstored.asp');
        //define('EWAY_PAYMENT_LIVE_AUTH_ONLY_TESTING_MODE', 'https://www.eway.com.au/gateway/xmlstored.asp');
        define('EWAY_PAYMENT_LIVE_REAL_TIME_CVN', 'https://www.eway.com.au/gateway_cvn/xmlpayment.asp');
        define('EWAY_PAYMENT_LIVE_REAL_TIME_CVN_TESTING_MODE', 'https://www.eway.com.au/gateway_cvn/xmltest/testpage.asp');
        define('EWAY_PAYMENT_LIVE_GEO_IP_ANTI_FRAUD', 'https://www.eway.com.au/gateway_beagle/xmlbeagle.asp');
        define('EWAY_PAYMENT_LIVE_GEO_IP_ANTI_FRAUD_TESTING_MODE', 'https://www.eway.com.au/gateway_beagle/test/xmlbeagle_test.asp');
        define('EWAY_PAYMENT_HOSTED_REAL_TIME', 'https://www.eway.com.au/gateway/payment.asp');
        define('EWAY_PAYMENT_HOSTED_REAL_TIME_TESTING_MODE', 'https://www.eway.com.au/gateway/payment.asp');
        define('EWAY_PAYMENT_HOSTED_REAL_TIME_CVN', 'https://www.eway.com.au/gateway_cvn/payment.asp');
        define('EWAY_PAYMENT_HOSTED_REAL_TIME_CVN_TESTING_MODE', 'https://www.eway.com.au/gateway_cvn/payment.asp');
        
		$payAmount      	= $order['orderTotalAmount'];
		$paymentCurrency	=	$this->settingsVars["payment_currency"];
		$supportedCurrencyID	= $order["purchasedCurrency"];
		$currencyArr	= '';
		$itemsArray  	= '';

		if ($paymentCurrency != '')
		{
			$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
			$currencyArr     = explode(",", $paymentCurrency);
		}
		if(count($currencyArr)<1)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Currency not configured , Please contact the site admin";
			return false;
		}
		else
		{
			$currencyFlag = false;
			$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
			$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
			$systemCurrencies 			= $ObjCurrency->listCurrencyCodes();
			if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
			{
				foreach ($systemCurrencies as $key => $currency)
				{
					if(in_array($currency['currencyCode'],$currencyArr))
					{
						$currencyFlag = true;
						$supportedCurrencyCode 	= $currency['currencyCode'];	
						$supportedCurrencyID 	= $currency['currencyID'];
						break;
					}
				}
				if($currencyFlag==true)
				{
					$payAmount 			= $ObjCurrency->convertValueCustom($payAmount,$order["purchasedCurrency"],$supportedCurrencyID);
					$currencyCode		=	$supportedCurrencyCode;
				}
				else
				{
					$this->isError 		= true;
					$this->errorMessage	= "Currency not configured , Please contact the site admin";
					return false;
				}
				
			}
		}
		
		if($payAmount<.01)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Invalid amount , please use another method";
			return false;
		}
		
        $userPayAmount  = ceil($payAmount);
        $userPayAmount  = $userPayAmount * 100;
        //converting amount to cent value.
        $txtFirstName   = $order['postData']['creditCardFirstName'];
        $txtLastName    = $order['postData']['creditCardLastName'];
        $txtEmail       = $order['billingAddress']['billingEmail'];
        $txtAddress     = htmlspecialchars($order['billingAddress']["billingAddress1"]);
		$txtAddress     .= ($order['billingAddress']['billingAddress2']!='') ? ', '.$order['billingAddress']['billingAddress2'] : '';	
        
		$languageIDs['Current']=1;
		$country 		= $ObjCountry->getCountryDetails($order['billingAddress']['billingCountry'],$languageIDs);
		$countryName 	= $country['countryName'];
		if ($order['billingAddress']['billingState'] >0)
		{
			$getStateDetails = $ObjState->getStateDetails($languageIDs,$order['billingAddress']['billingState']);
			$stateName       = $getStateDetails['stateShortName'];
		}
		else
		{
			$stateName = $order['billingAddress']['billingProvince'];
		}
		$txtAddress     .= " , ".$stateName." , ".$countryName." , ".$order['billingAddress']['billingCity'];
		
		$txtPostcode    = urlencode($order['billingAddress']["billingZip"]);
        $txtTxnNumber   = $order["masterOrderID"];
        $txtInvDesc     = "Payment From " . $order['postData']['creditCardFirstName'].' '.$order['postData']['creditCardLastName'];
        $txtInvRef      = $order["masterOrderID"];
        $txtOption2     = "";
        $txtOption3     = "";
        $txtCCNumber    = $order['postData']['creditCardNumber'];
        $ddlExpiryMonth = $order['postData']['expMonth'];
		// Last 2 digits of the year
        $ddlExpiryYear  = substr($order['postData']['expYear'],-2);
        $txtCCName      = $order['postData']['creditCardFirstName'];
		
		include_once ("EwaypaymentliveModel.php");
		
		$eway       = new EwaypaymentliveModel($ewayCustomerID, $ewayPaymentMethod, $ewayUseLive);
        $eway->setTransactionData("TotalAmount", $userPayAmount);
        //mandatory field
        $eway->setTransactionData("CustomerFirstName", $txtFirstName);
        $eway->setTransactionData("CustomerLastName", $txtLastName);
        $eway->setTransactionData("CustomerEmail", $txtEmail);
        $eway->setTransactionData("CustomerAddress", $txtAddress);
        $eway->setTransactionData("CustomerPostcode", $txtPostcode);
        $eway->setTransactionData("CustomerInvoiceDescription", $txtInvDesc);
        $eway->setTransactionData("CustomerInvoiceRef", $txtInvRef);
        $eway->setTransactionData("CardHoldersName", $txtCCName);
        //mandatory field
        $eway->setTransactionData("CardNumber", $txtCCNumber);
        //mandatory field
        $eway->setTransactionData("CardExpiryMonth", $ddlExpiryMonth);
        //mandatory field
        $eway->setTransactionData("CardExpiryYear", $ddlExpiryYear);
        //mandatory field
        $eway->setTransactionData("TrxnNumber", $txtTxnNumber);
        $eway->setTransactionData("Option1", "");
        $eway->setTransactionData("Option2", $txtOption2);
        $eway->setTransactionData("Option3", $txtOption3);
        $eway->setCurlPreferences(CURLOPT_SSL_VERIFYPEER, 0);
        // Require for Windows hosting
        // Send the transaction
        $ewayResponseFields = $eway->doPayment();
        if (strtolower($ewayResponseFields["EWAYTRXNSTATUS"]) == "false") {
            $this->isError      = true;
            $this->errorMessage = "We are sorry, but this transaction has been declined.<br>Payment gateway response: " . $this->escape($ewayResponseFields["EWAYTRXNERROR"]);
            $paymentStatus      = 'Failure';
        } else if (strtolower($ewayResponseFields["EWAYTRXNSTATUS"]) == "true") {
            $lblResult = " Result: " . $ewayResponseFields["EWAYTRXNSTATUS"] . "<br>";
            $lblResult .= " AuthCode: " . $ewayResponseFields["EWAYAUTHCODE"] . "<br>";
            $lblResult .= " Error: " . $ewayResponseFields["EWAYTRXNERROR"] . "<br>";
            $lblResult .= " eWAYInvoiceRef: " . $ewayResponseFields["EWAYTRXNREFERENCE"] . "<br>";
            $lblResult .= " Amount: " . $ewayResponseFields["EWAYRETURNAMOUNT"]/100 . "<br>";
            $lblResult .= " Txn Number: " . $ewayResponseFields["EWAYTRXNNUMBER"] . "<br>";
            $lblResult .= " Option1: " . (isset($ewayResponseFields["EWAYOPTION1"])?$ewayResponseFields["EWAYOPTION1"]:'') . "<br>";
            $lblResult .= " Option2: " . (isset($ewayResponseFields["EWAYOPTION2"])?$ewayResponseFields["EWAYOPTION2"]:'') . "<br>";
            $lblResult .= " Option3: " . (isset($ewayResponseFields["EWAYOPTION3"])?$ewayResponseFields["EWAYOPTION3"]:'') . "<br>";
            $transactionID        = $ewayResponseFields["EWAYTRXNNUMBER"];
            $paymentMethodName    = $this->settingsVars["payment_method_name"];
            parent::createTransaction($order, $transactionID, $lblResult, "", 
			"AUTH_CAPTURE", 0, $paymentMethodName,
			$supportedCurrencyID, $payAmount);
            if ($order['store_cc_info'] == 'Yes') {
                parent::saveCCdata($order['postData'], $order["userID"]);
            }
            $this->isError      = false;
            $this->errorMessage = "";
            $paymentStatus      = 'Pending';
        } else {
            $this->errorMessage = "Error: An invalid response was recieved from the payment gateway.";
            $paymentStatus = 'Failure';
        }
		
        return $paymentStatus;
    }
    public function processRefund($order = '', $postValues = '')//refund processing
    {
        parent::listPaymentSettingsValues($postValues['paymentSettingsGroupID']);
		$ObjCurrency		= new CurrencyModel();
		$paymentTxnDetails	= $this->getPaymentTransactionDetails('',$order['masterOrderID']);
		$refundAmount		= $order['orderTotalAmount'];
        $ewayCustomerID    	= urlencode($this->settingsVars["customer_id"]);
        $ewayPaymentMethod 	= 'REFUND';
        
		$supportedCurrencyID = $order["purchasedCurrency"];
		$paymentCurrency	 = $this->settingsVars["payment_currency"];
		
		if ($paymentCurrency != '')
		{
			$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
			$currencyArr     = explode(",", $paymentCurrency);
		}
		if(count($currencyArr)<1)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Currency not configured , Please contact the site admin";
			//return false;
		}
		else
		{
			$currencyFlag = false;
			$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
			$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
			$systemCurrencies 			= $ObjCurrency->listCurrencyCodes();
			if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
			{
				foreach ($systemCurrencies as $key => $currency)
				{
					if(in_array($currency['currencyCode'],$currencyArr))
					{
						$currencyFlag = true;
						$supportedCurrencyCode 	= $currency['currencyCode'];	
						$supportedCurrencyID 	= $currency['currencyID'];
						break;
					}
				}
				if($currencyFlag==true)
				{
					$refundAmount = $ObjCurrency->convertValueCustom($refundAmount,$order["purchasedCurrency"],$supportedCurrencyID);
				}
				else
				{
					$this->isError 		= true;
					$this->errorMessage	= "Currency not configured , Please contact the site admin";
					//return false;
				}
				
			}
		}
		
		$refundAmount = ceil($refundAmount);
		
		$useLive           	= urlencode($this->settingsVars["payment_test"]);
        if ($useLive == "On") {
            $ewayUseLive 	= false;
        } else {
            $ewayUseLive 	= true;
        }
        //$eWAY_RefundPswd 	= 'ewayref1';
		$eWAY_RefundPswd    = $this->settingsVars["refund_password"];
        define('EWAY_DEFAULT_CUSTOMER_ID', $ewayCustomerID);
        define('EWAY_DEFAULT_PAYMENT_METHOD', $ewayPaymentMethod);
        define('EWAY_DEFAULT_LIVE_GATEWAY', $ewayUseLive);
        define('EWAY_REFUND', 'https://www.eway.com.au/gateway/xmlpaymentrefund.asp');
        define('EWAY_REFUND_TESTING_MODE', 'https://www.eway.com.au/gateway/xmltest/refund_test.asp');
		include_once ("EwaypaymentliveModel.php");
        $eway = new EwaypaymentliveModel($ewayCustomerID, $ewayPaymentMethod, $ewayUseLive);
        $eway->setTransactionData("OriginalTrxnNumber", $postValues['apiPaymentTransactionID']);
        $eway->setTransactionData("TotalAmount", $refundAmount*100);
        $eway->setTransactionData("CardExpiryMonth", $postValues['expMonth']);
        $eway->setTransactionData("CardExpiryYear", $postValues['expYear']);
        $eway->setTransactionData("Option1", '');
        $eway->setTransactionData("Option2", '');
        $eway->setTransactionData("Option3", '');
        $eway->setTransactionData("RefundPassword", $eWAY_RefundPswd);
        $eway->setCurlPreferences(CURLOPT_SSL_VERIFYPEER, 0);
        // Require for Windows hosting
        $ewayResponseFields = $eway->doPayment();
        if (strtolower($ewayResponseFields["EWAYTRXNSTATUS"]) == "false") {
            $lblResult = " Result: " . $ewayResponseFields["EWAYTRXNSTATUS"] . "<br>";
            $lblResult .= " AuthCode: " . $ewayResponseFields["EWAYAUTHCODE"] . "<br>";
            $lblResult .= " Txn Ref: " . (isset($ewayResponseFields["EWAYTRXNREFERENCE"])?$ewayResponseFields["EWAYTRXNREFERENCE"]:"") . "<br>";
            $lblResult .= " Error: " . $ewayResponseFields["EWAYTRXNERROR"] . "<br>";
            $lblResult .= " Amount: " . $ewayResponseFields["EWAYRETURNAMOUNT"] . "<br>";
            $lblResult .= " Txn Number: " . $ewayResponseFields["EWAYTRXNNUMBER"] . "<br>";
            $lblResult .= " Option1: " . (isset($ewayResponseFields["EWAYOPTION1"])?$ewayResponseFields["EWAYOPTION1"]:'') . "<br>";
            $lblResult .= " Option2: " . (isset($ewayResponseFields["EWAYOPTION2"])?$ewayResponseFields["EWAYOPTION2"]:'') . "<br>";
            $lblResult .= " Option3: " . (isset($ewayResponseFields["EWAYOPTION3"])?$ewayResponseFields["EWAYOPTION3"]:'') . "<br>";
            $masterOrderID                         = $postValues['masterOrderID'];
            $refundTransactionID             = $postValues['keyRefundTransactionID'];
            $arrXnResponse['transactionID']  = '';
            $arrXnResponse['refundResponse'] = $lblResult;
            $arrXnResponse['refundAmount']   = '';
            $ObjRefund                       = new RefundModel();
            $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('', $refundTransactionID, $arrXnResponse, $masterOrderID);
            $this->isError                   = true;
            $this->errorMessage              = "This transaction has been declined.<br>Payment gateway response: " . $ewayResponseFields["EWAYTRXNERROR"];
            $refundStatus                    = 'Failure';
        } else if (strtolower($ewayResponseFields["EWAYTRXNSTATUS"]) == "true") {
            $lblResult = " Result: " . $ewayResponseFields["EWAYTRXNSTATUS"] . "<br>";
            $lblResult .= " AuthCode: " . $ewayResponseFields["EWAYAUTHCODE"] . "<br>";
            $lblResult .= " Txn Ref: " . (isset($ewayResponseFields["EWAYTRXNREFERENCE"])?$ewayResponseFields["EWAYTRXNREFERENCE"]:'') . "<br>";
            $lblResult .= " Error: " . $ewayResponseFields["EWAYTRXNERROR"] . "<br>";
            $lblResult .= " Amount: " . $ewayResponseFields["EWAYRETURNAMOUNT"] . "<br>";
            $lblResult .= " Txn Number: " . $ewayResponseFields["EWAYTRXNNUMBER"] . "<br>";
            $lblResult .= " Option1: " . (isset($ewayResponseFields["EWAYOPTION1"])?$ewayResponseFields["EWAYOPTION1"]:'') . "<br>";
            $lblResult .= " Option2: " . (isset($ewayResponseFields["EWAYOPTION2"])?$ewayResponseFields["EWAYOPTION2"]:'') . "<br>";
            $lblResult .= " Option3: " . (isset($ewayResponseFields["EWAYOPTION3"])?$ewayResponseFields["EWAYOPTION3"]:'') . "<br>";
            $masterOrderID                   = $postValues['masterOrderID'];
            $refundTransactionID             = $postValues['keyRefundTransactionID'];
            $arrXnResponse['transactionID']  = $ewayResponseFields["EWAYTRXNNUMBER"];
            $arrXnResponse['refundResponse'] = $lblResult;
            $arrXnResponse['refundAmount']   = $ewayResponseFields["EWAYRETURNAMOUNT"];
            $ObjRefund                       = new RefundModel();
            $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('', $refundTransactionID, $arrXnResponse, $masterOrderID);
            $this->isError                   = false;
            $this->errorMessage              = "";
            $refundStatus                    = 'Pending';
        } else {
			$this->isError                   = true;
            $lblResult    					 = "Error: An invalid response was recieved from the payment gateway.";
            $refundStatus 					 = 'Failure';
        }
        return !$this->isError;
    }
}