<?php
/**
* @version	$Id: paybox.php 13549 2010-05-11 21:03:39Z 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 = 'kPayboxGW'; // for automatic installation

	class kPayboxGW extends kGWBase
	{
		function InstallData()
		{
			$data = array(
				'Gateway' => Array('Name' => 'Paybox.com', 'ClassName' => 'kPayboxGW', 'ClassFile' => 'paybox.php', 'RequireCCFields' => 0),
				'ConfigFields' => Array(
					'binary' => Array('Name' => 'API Executable', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'params_file' => Array('Name' => 'OPT Params File', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'site_number' => Array('Name' => 'Site Number', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'rank_number' => Array('Name' => 'Rank Number', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'identity_number' => Array('Name' => 'Identity Number', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'currency_code' => Array('Name' => 'Currency Code', 'Type' => 'text', 'ValueList' => '', 'Default' => '978'),
					'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 $gw_params['submit_url'];
		}

		/**
		 * 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)
		{
			$params['PBX_MODE'] = $gw_params['params_file'] ? '34' : '4';
			$params['PBX_OUTPUT'] = 'B';
			$params['PBX_SITE'] = $gw_params['site_number'];
			$params['PBX_RANG'] = $gw_params['rank_number'];
			$params['PBX_IDENTIFIANT'] = $gw_params['identity_number'];
			$params['PBX_OPT'] = $gw_params['params_file'];
			$params['PBX_DEVISE'] = $gw_params['currency_code']; // 978 for the euro. 840 for the US dollar.

			$params['PBX_RETOUR'] = 'amount:M;reference:R;trans:T;autorization:A;subscription:B;payment:P;card:C;trans_id:S;country:Y;error:E;expiration:D';

			$params['PBX_EFFECTUE'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
			$params['PBX_REFUSE'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));

			$txt_amount = sprintf("%.2f", $item_data['TotalAmount']);
			$params['PBX_TOTAL'] = str_replace( Array('.', ','), '', $txt_amount);
			$params['PBX_CMD'] = $this->Application->GetSID().','.MD5($item_data['OrderId']);

			/*$params['order_id'] = $item_data['OrderId'];
			$params['customer_ip_address'] = $_SERVER['REMOTE_ADDR'];
			$params['customer_id'] = $item_data['PortalUserId'];*/

			$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'));
			}
			$params['PBX_PORTEUR'] = $billing_email;

			$params_str = '';
			foreach ($params as $key => $val) {
				$params_str .= ' '.$key . '="'.$val.'"';
			}
			$run_line = $gw_params['binary'].' '.$params_str;

//			$run_line = escapeshellcmd($run_line);
//			echo escapeshellcmd($run_line);

			exec ($run_line, $rets);

			$ret = implode("\n", $rets);

			$ret = preg_replace('/^(.*)!!/is', '', $ret);
			$ret = rtrim($ret, '!');

			return '</form>'.$ret.'<form>';
		}

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

		function processNotification($gw_params)
		{
			$result = $this->Application->HttpQuery->GetParams();
			$this->parsed_responce = $result;

			list ($sid, $auth_code) = explode(',', $result['reference']);
			$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);

			return $result['error'] === '00000' ? 1 : 0;
		}

		function parseGWResponce($str)
		{
			$response = explode ("!", $str);

			$result = Array (
				'code' => $response[1],
				'error' => $response[2],
				'merchant_id' => $response[3],
				'merchant_country' => $response[4],
				'amount' => $response[5],
				'transaction_id' => $response[6],
				'payment_means' => $response[7],
				'transmission_date' => $response[8],
				'payment_time' => $response[9],
				'payment_date' => $response[10],
				'response_code' => $response[11],
				'payment_certificate' => $response[12],
				'authorisation_id' => $response[13],
				'currency_code' => $response[14],
				'card_number' => $response[15],
				'cvv_flag' => $response[16],
				'cvv_response_code' => $response[17],
				'bank_response_code' => $response[18],
				'complementary_code' => $response[19],
				'complementary_info' => $response[20],
				'return_context' => $response[21],
				'caddie' => $response[22],
				'receipt_complement' => $response[23],
				'merchant_language' => $response[24],
				'language' => $response[25],
				'customer_id' => $response[26],
				'order_id' => $response[27],
				'customer_email' => $response[28],
				'customer_ip_address' => $response[29],
				'capture_day' => $response[30],
				'capture_mode' => $response[31],
				'data' => $response[32],
			);
			$this->parsed_responce = $result;
			return $result;
		}

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

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