<?php
/**
* @version	$Id: gw_base.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.
*/

	defined('FULL_PATH') or die('restricted access!');

	class kGWBase extends kBase
	{
		/**
		 * gateway received responce
		 *
		 * @var string
		 */
		var $gw_responce = '';

		var $parsed_responce = Array();

		/**
		 * Returns payment form submit url
		 *
		 * @return string
		 */
		function getFormAction($gw_params)
		{
			return $this->Application->ProcessParsedTag('m', 'FormAction', Array() );
		}

		/**
		 * 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)
		{
			return Array(	'events[ord]' => 'OnCompleteOrder',
							'success_template' => $tag_params['return_template'],
							'failure_template' => $tag_params['cancel_template']);
		}

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

		/**
		 * Process notification about payment from payment gateway
		 *
		 * @param Array $gw_params
		 * @return bool
		 */
		function processNotification($gw_params)
		{

		}

		/**
		 * Perform PREAUTH/SALE type transaction direct from php script wihtout redirecting to 3rd-party website
		 *
		 * @param Array $item_data
		 * @param Array $gw_params
		 * @return bool
		 */
		function DirectPayment($item_data, $gw_params)
		{
			return true;
		}

		/**
		 * 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)
		{
			return true;
		}

		/**
		 * Informs payment gateway, that order has been shipped
		 *
		 * @param Array $item_data
		 * @param Array $gw_params
		 * @return bool
		 */
		function OrderShipped($item_data, $gw_params)
		{

		}

		/**
		 * Informs payment gateway, that order has been declined
		 *
		 * @param Array $item_data
		 * @param Array $gw_params
		 * @return bool
		 */
		function OrderDeclined($item_data, $gw_params)
		{

		}

		/**
		 * Returns gateway responce from last operation
		 *
		 * @return string
		 */
		function getGWResponce()
		{
			return $this->gw_responce;
		}

		/**
		 * Parse previously saved gw responce into associative array
		 *
		 * @param string $gw_responce
		 * @param Array $gw_params
		 * @return Array
		 */
		function parseGWResponce($gw_responce, $gw_params)
		{
			return $this->gw_responce;
		}

		/**
		 * Returns true if we should use testing mode
		 *
		 * @return bool
		 */
		function IsTestMode()
		{
			return defined('DEBUG_MODE') && kUtil::constOn('DBG_PAYMENT_GW');
		}

		/**
		 * Convery primary currency to selected (if they are the same, converter will just return)
		 *
		 * @param double $value
		 * @param string $iso
		 * @param bool $format_value
		 * @return double
		 */
		function ConvertCurrency($value, $iso, $format_value = true)
		{
			/** @var CurrencyRates $converter */
			$converter = $this->Application->recallObject('CurrencyRates');

			$value = $converter->Convert($value, 'PRIMARY', $iso);
			return $format_value ? sprintf('%.2f', $value) : $value;
		}

		function InstallData()
		{
			return array();
		}

		function Install()
		{
			if ($this->IsInstalled()) {
				return;
			}

			$data = $this->InstallData();
			if (!$data) {
				return ;
			}

			// 1. create gateway record
			$fields_hash = Array ();
			$gw_fields = Array ('Name', 'ClassName', 'ClassFile', 'RequireCCFields');
			foreach ($gw_fields as $gw_field) {
				$fields_hash[$gw_field] = $data['Gateway'][$gw_field];
			}
			$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'Gateways');
			$gw_id = $this->Conn->getInsertID();

			// 2. create DISABLED payment type, that uses this gateway (used for storing configuration properties of gateway)
			/** @var kDBItem $payment_type */
			$payment_type = $this->Application->recallObject('pt.-item', null, Array ('skip_autoload' => true));

			$payment_type->Clear();
			$fields_hash = Array (
				'Name' => $data['Gateway']['Name'],
				'l' . $this->Application->GetDefaultLanguageId() . '_Description' => $data['Gateway']['Name'],
				'BuiltIn' => 1,
				'GatewayId' => $gw_id,
			);
			$payment_type->SetDBFieldsFromHash($fields_hash);
			$created = $payment_type->Create();
			if (!$created) {
				return ;
			}

			// 3. create gateway configuration fields
			foreach ($data['ConfigFields'] as $field => $properties) {
				$fields_hash = Array (
					'SystemFieldName' => $field,
					'GatewayId' => $gw_id,
					'FieldName' => $properties['Name'],
					'ElementType' => $properties['Type'],
					'ValueList' => $properties['ValueList'],
				);
				$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'GatewayConfigFields');
				$fld_id = $this->Conn->getInsertID();

				// 4. set default value for configuration property of gateway
				$fields_hash = Array (
					'GWConfigFieldId' => $fld_id,
					'PaymentTypeId' => $payment_type->GetID(),
					'Value' => $properties['Default'],
				);
				$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'GatewayConfigValues');
			}
		}

		function IsInstalled()
		{
			$data = $this->InstallData();
			if (!$data) {
				return true;
			}

			$sql = 'SELECT GatewayId
					FROM '.TABLE_PREFIX.'Gateways
					WHERE ClassName = '.$this->Conn->qstr($data['Gateway']['ClassName']);
			return $this->Conn->GetOne($sql);
		}

		function getErrorMsg()
		{
			return '';
		}

		function gettestccnumbers()
		{
			return array();
		}

		function getNotificationUrl($script = 'gw_notify.php', $use_ssl = null)
		{
			// custom path can be: units/gateways/gw_classes/notify_scripts/google_checkout_shippings.php'

			$ret = MODULES_PATH . '/in-commerce/' . $script;
			$ret = preg_replace('/^' . preg_quote(FULL_PATH . '/', '/') . '/', $this->Application->BaseURL('', $use_ssl), $ret);

			return str_replace(DIRECTORY_SEPARATOR, '/', $ret);
		}
	}