<?php
/**
* @version	$Id: paypal_direct.php 16516 2017-01-20 14:12:22Z alex $
* @package	In-Commerce
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license	Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/

	require_once GW_CLASS_PATH.'/gw_base.php';

	$class_name = 'kGWPaypalDirect'; // for automatic installation

	class kGWPaypalDirect extends kGWBase
	{
		function InstallData()
		{
			$data = array(
				'Gateway' => Array('Name' => 'PayPal Pro', 'ClassName' => 'kGWPaypalDirect', 'ClassFile' => 'paypal_direct.php', 'RequireCCFields' => 1),
				'ConfigFields' => Array(
					'submit_url' => Array('Name' => 'Submit URL', 'Type' => 'text', 'ValueList' => '', 'Default' => 'https://api-3t.paypal.com/nvp'),
					'api_username' => Array('Name' => 'PayPal Pro API Username', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'api_password' => Array('Name' => 'PayPal Pro API Password', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'signature' => Array('Name' => 'PayPal Pro API Signature', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'shipping_control' => Array('Name' => 'Shipping Control', 'Type' => 'select', 'ValueList' => '3=la_CreditDirect', 'Default' => '3'),
				)
			);
			return $data;
		}

		function DirectPayment($item_data, $gw_params)
		{
			$post_fields = Array();
			// -- Login Information --
			$post_fields['METHOD']				=	'DoDirectPayment';
			$post_fields['VERSION']				=	'52.0';
			$post_fields['IPADDRESS']			=	$this->Application->getClientIp();
			$post_fields['USER']				=	$gw_params['api_username'];
			$post_fields['PWD']					=	$gw_params['api_password'];
			$post_fields['SIGNATURE']			=	$gw_params['signature'];
			$post_fields['PAYMENTACTION']		=	'Sale';
			$post_fields['AMT']					=	sprintf('%.2f', $item_data['TotalAmount']);

			switch ($item_data['PaymentCardType']) {
				case 1:
					$post_fields['CREDITCARDTYPE'] = 'Visa';
					break;
				case 2:
					$post_fields['CREDITCARDTYPE'] = 'MasterCard';
					break;
				case 3:
					$post_fields['CREDITCARDTYPE'] = 'Amex';
					break;
				case 4:
					$post_fields['CREDITCARDTYPE'] = 'Discover';
					break;
				default:
					$this->parsed_responce['responce_reason_text'] = 'Invalid Credit Card Type';
					return false;
			}

			$post_fields['ACCT']				=	$item_data['PaymentAccount'];
			$date_parts = explode('/', $item_data['PaymentCCExpDate']);
			$post_fields['EXPDATE']				=	$date_parts[0].'20'.$date_parts[1];
			$post_fields['CVV2']				=	$item_data['PaymentCVV2'];

			$names = explode(' ', $item_data['PaymentNameOnCard'], 2);
			$post_fields['FIRSTNAME']			=	getArrayValue($names, 0);
			$post_fields['LASTNAME']			=	getArrayValue($names, 1);

			$post_fields['STREET']				=	$item_data['BillingAddress1'];
			$post_fields['STREET2']				=	$item_data['BillingAddress2'];
			$post_fields['CITY']				=	$item_data['BillingCity'];
			$post_fields['STATE']				=	$item_data['BillingState'];

			/** @var kCountryStatesHelper $cs_helper */
			$cs_helper = $this->Application->recallObject('CountryStatesHelper');

			$post_fields['COUNTRYCODE']			=	$cs_helper->getCountryIso( $item_data['BillingCountry'] );
			$post_fields['ZIP']					=	$item_data['BillingZip'];
			$post_fields['INVNUM']				=	$item_data['OrderNumber'];
			$post_fields['CUSTOM']				=	$item_data['PortalUserId'];

/*
			$post_fields['x_encap_char']		=	$gw_params['encapsulate_char'];
			$post_fields['x_relay_response']	=	'False';
			$post_fields['x_type']				=	$gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'AUTH_ONLY' : 'AUTH_CAPTURE';
			$post_fields['x_login']				=	$gw_params['user_account'];
			$post_fields['x_tran_key']			=	$gw_params['transaction_key'];

			if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';

			// -- Payment Details --
			$names = explode(' ', $item_data['PaymentNameOnCard'], 2);
			$post_fields['x_first_name']		=	getArrayValue($names, 0);
			$post_fields['x_last_name']			=	getArrayValue($names, 1);
			$post_fields['x_amount']			=	sprintf('%.2f', $item_data['TotalAmount']);
			$post_fields['x_company']			=	$item_data['BillingCompany'];
			$post_fields['x_card_num']			=	$item_data['PaymentAccount'];
			$post_fields['x_card_code']			=	$item_data['PaymentCVV2'];
			$post_fields['x_exp_date']			=	$item_data['PaymentCCExpDate'];
			$post_fields['x_address']			=	$item_data['BillingAddress1'].' '.$item_data['BillingAddress2'];
			$post_fields['x_city']				=	$item_data['BillingCity'];
			$post_fields['x_state']				=	$item_data['BillingState'];
			$post_fields['x_zip']				=	$item_data['BillingZip'];

			$recurring = getArrayValue($item_data, 'IsRecurringBilling') ? 'YES' : 'NO';
			$post_fields['x_recurring_billing'] = $recurring;

			$billing_email = $item_data['BillingEmail'];
			if (!$billing_email) {
				$billing_email = $this->Conn->GetOne('	SELECT Email FROM '.$this->Application->getUnitOption('u', 'TableName').'
											WHERE PortalUserId = '.$this->Application->RecallVar('user_id'));
			}
			$post_fields['x_email'] = $billing_email;
			$post_fields['x_phone'] = $item_data['BillingPhone'];
			$post_fields['x_country']			=	$cs_helper->getCountryIso( $item_data['BillingCountry'] );

			$post_fields['x_cust_id']			=	$item_data['PortalUserId'];
			$post_fields['x_invoice_num']		=	$item_data['OrderNumber'];
			$post_fields['x_description']		=	'Invoice #'.$item_data['OrderNumber'];
			$post_fields['x_email_customer']	=	'FALSE';
*/
//			echo '<pre>';
//			print_r($post_fields);
//			exit;

			/** @var kCurlHelper $curl_helper */
			$curl_helper = $this->Application->recallObject('CurlHelper');

			$curl_helper->SetPostData($post_fields);
			$this->gw_responce = $curl_helper->Send($gw_params['submit_url']);

//			echo $this->gw_responce;
//			exit;
			$gw_responce = $this->parseGWResponce(null, $gw_params);
			// gw_error_msg: $gw_response['responce_reason_text']
			// gw_error_code: $gw_response['responce_reason_code']
//			echo '<pre>';
//			print_r($this->parsed_responce);
//			exit;
			return (isset($gw_responce['ACK']) && (substr($gw_responce['ACK'], 0, 7) == 'Success')) ? true : false;
		}

		/**
		 * Perform SALE type transaction direct from php script wihtout redirecting to 3rd-party website
		 *
		 * @param Array $item_data
		 * @param Array $gw_params
		 * @return bool
		 */
/*
		function Charge($item_data, $gw_params)
		{
			$gw_responce = unserialize( $item_data['GWResult1'] );

			if( $item_data['PortalUserId'] != $gw_responce['customer_id'] ) return false;

			if( ( strtolower($gw_responce['transaction_type']) == 'auth_only') )
			{
				$post_fields = Array();
				// -- Login Information --
				$post_fields['x_version']			=	'3.1';
				$post_fields['x_delim_data']		=	'True';
				$post_fields['x_encap_char']		=	$gw_params['encapsulate_char'];
				$post_fields['x_relay_response']	=	'False';
				$post_fields['x_type']				=	'PRIOR_AUTH_CAPTURE'; // $gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'PRIOR_AUTH_CAPTURE' : 'AUTH_CAPTURE'; // AUTH_CAPTURE not fully impletemnted/needed here
				$post_fields['x_login']				=	$gw_params['user_account'];
				$post_fields['x_tran_key']			=	$gw_params['transaction_key'];
				$post_fields['x_trans_id']			=	$gw_responce['transaction_id'];

				if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';

				$curl_helper = $this->Application->recallObject('CurlHelper');

				$curl_helper->SetPostData($post_fields);
				$this->gw_responce = $curl_helper->Send($gw_params['submit_url']);

				$gw_responce = $this->parseGWResponce(null, $gw_params);

				// gw_error_msg: $gw_response['responce_reason_text']
				// gw_error_code: $gw_response['responce_reason_code']
				return (is_numeric($gw_responce['responce_code']) && $gw_responce['responce_code'] != 1 && !$this->IsTestMode()) ? false : true;
			}
			else
			{
				return true;
			}
		}
*/
		/**
		 * Parse previosly saved gw responce into associative array
		 *
		 * @param string $gw_responce
		 * @param Array $gw_params
		 * @return Array
		 */
		function parseGWResponce($gw_responce = null, $gw_params)
		{
			if( !isset($gw_responce) ) $gw_responce = $this->gw_responce;

			if ($this->Application->isDebugMode()) {
				$this->Application->Debugger->appendHTML('Curl Error #'.$GLOBALS['curl_errorno'].'; Error Message: '.$GLOBALS['curl_error']);

				$this->Application->Debugger->appendHTML('Authorize.Net Responce:');
				$this->Application->Debugger->dumpVars($gw_responce);
			}

			$a_responce = explode('&', $gw_responce);
			$ret = Array();
			foreach($a_responce as $field)
			{
				$pos = strpos($field, '=');
				if ($pos) {
					$ret[substr($field, 0, $pos)] = urldecode(substr($field, $pos + 1));
				}
			}
			$this->parsed_responce = $ret;
//			$ret['unparsed'] = $gw_responce;
			return $ret;
		}

		function getGWResponce()
		{
			return serialize($this->parsed_responce);
		}

		function getErrorMsg()
		{
			return $this->parsed_responce['L_LONGMESSAGE0'];
		}

		function GetTestCCNumbers()
		{
			return array('370000000000002', '6011000000000012', '5424000000000015', '4007000000027', '4222222222222');
		}
	}