<?php
/**
* @version	$Id: sella_guestpay.php 12739 2009-10-20 19:38: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 = 'kSellaGuestPayGW'; // for automatic installation

	class kSellaGuestPayGW extends kGWBase
	{
		function InstallData()
		{
			$data = array(
				'Gateway' => Array('Name' => 'Sella/GuestPay', 'ClassName' => 'kSellaGuestPayGW', 'ClassFile' => 'sella_guestpay.php', 'RequireCCFields' => 0),
				'ConfigFields' => Array(
					'merchant_id' => Array('Name' => 'Merchant ID', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'merchant_country' => Array('Name' => 'Merchant Country Code', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'currency_code' => Array('Name' => 'Currency Code', 'Type' => 'text', 'ValueList' => '', 'Default' => '978'),
					'language_code' => Array('Name' => 'Language Code', 'Type' => 'text', 'ValueList' => '', 'Default' => '2'),
					'shipping_control' => Array('Name' => 'Shipping Control', 'Type' => 'select', 'ValueList' => '3=la_CreditDirect,4=la_CreditPreAuthorize', 'Default' => '3'),
				)
			);
			return $data;
		}

		/**
		 * Returns payment form submit url
		 *
		 * @param Array $gw_params gateway params from payment type config
		 * @return string
		 */
		function getFormAction($gw_params)
		{
			return 'https://ecomm.sella.it/gestpay/pagam.asp';
		}

		/**
		 * Processed input data and convets it to fields understandable by gateway
		 *
		 * @param Array $item_data
		 * @param Array $tag_params additional params for gateway passed through tag
		 * @param Array $gw_params gateway params from payment type config
		 * @return Array
		 */
		function getHiddenFields($item_data, $tag_params, $gw_params)
		{
			$a = $gw_params['merchant_id'];
			$params['PAY1_UICCODE'] = $gw_params['currency_code'];
			$params['PAY1_AMOUNT'] = $item_data['TotalAmount'];
			$params['PAY1_SHOPTRANSACTIONID'] = $item_data['OrderId'];
			$params['PAY1_IDLANGUAGE'] = $gw_params['language_code'];
			$params['CUSTOM_INFO'] = $this->Application->GetSID().','.MD5($item_data['OrderId']);

			$separator = '*P1*';
			$b = array();
			foreach ($params as $key=>$val) {
				$b[] = $key.'='.urlencode(trim($val));
			}
			//the last one is CUSTOMINFO according to GW specs, passing the atosorigin-style 'caddie'
			$b = join($separator, $b);
			$url = 'https://ecomm.sella.it/CryptHTTPS/Encrypt.asp?a='.$a.'&b='.$b.'&c=2.0';

			$res = curl_post($url, array(), null, 'GET');

			preg_match('/#cryptstring#(.*)#\/cryptstring#/', $res, $matches);
			$b = $matches[1];

			$res = '<input type="hidden" name="a" value="'.$a.'"><input type="hidden" name="b" value="'.$b.'">';
			return $res;
		}

		function NeedPlaceButton($item_data, $tag_params, $gw_params)
		{
			return true;
		}

		function processNotification($gw_params)
		{
			$a = $gw_params['merchant_id'];
			$b = $_REQUEST['b'];
			$url = 'https://ecomm.sella.it/CryptHTTPS/Decrypt.asp?a='.$a.'&b='.$b.'&c=2.0';

			$ret = curl_post($url, array(), null, 'GET');
			$result = $this->parseGWResponce($ret);

			list ($sid, $auth_code) = explode(',', $result['CUSTOM_INFO']);
			$session =& $this->Application->recallObject('Session');
			$session->SID = $sid;

			$order_id = $this->Conn->GetOne('SELECT OrderId FROM '.TABLE_PREFIX.'Orders WHERE md5(OrderId) = '.$this->Conn->qstr($auth_code));
			$this->Application->SetVar('ord_id', $order_id);
			$order =& $this->Application->recallObject('ord');
			$order->Load($order_id);

			if ($this->Application->GetVar('sella_ok')) {
				if ($result['PAY1_TRANSACTIONRESULT'] == 'OK') {
					$this->Application->Redirect('in-commerce/checkout/checkout_success', null, '_FRONT_END_', 'index.php');
				}
				else {
					$this->Application->SetVar('sella_error', 1);
				}
			}
			if ($this->Application->GetVar('sella_error')) {
				$this->Application->StoreVar('gw_error', $this->getErrorMsg());
				$this->Application->Redirect('in-commerce/checkout/billing', null, '_FRONT_END_', 'index.php');
			}

			return $result['PAY1_TRANSACTIONRESULT'] == 'OK' ? 1 : 0;
		}

		function parseGWResponce($str)
		{
			if (preg_match('/#decryptstring#(.*)#\/decryptstring#/', $str, $matches)) {
				$separator = '*P1*';
				$pairs = explode($separator, $matches[1]);
				foreach ($pairs as $a_pair) {
					list($key, $val) = explode('=', $a_pair);
					$result[$key] = $val;
				}
			}
			elseif (preg_match('/#error#(.*)#\/error#/', $str, $matches))
			{
				$result['PAY1_ERRORDESCRIPTION'] = $matches[1];
			}
			else { //unknown error
				$result['PAY1_ERRORDESCRIPTION'] = 'Unknown error';
			}

			$this->parsed_responce = $result;
			return $result;
		}

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

		function getErrorMsg()
		{
			$msg = $this->parsed_responce['PAY1_ERRORDESCRIPTION'];
			if (!$msg) {
				if ($this->parsed_responce['response_code'] != 'OK') {
					$msg = 'Transaction failed';
				}
			}
			return $msg;
		}
	}