<?php
/**
* @version	$Id: ideal_nl.php 13704 2010-06-09 14:52:56Z 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.
*/

/* http://www.ideal.nl/ gateway class */

	require_once GW_CLASS_PATH.'/gw_base.php';

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

	class kGWiDEALnl extends kGWBase
	{

		function InstallData()
		{
			$data = array(
				'Gateway' => Array('Name' => 'iDEAL.nl', 'ClassName' => 'kGWiDEALnl', 'ClassFile' => 'ideal_nl.php', 'RequireCCFields' => 0),
				'ConfigFields' => Array(
					'partner_id' => Array('Name' => 'Partner ID', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
					'request_url' => Array('Name' => 'Request URL', 'Type' => 'text', 'ValueList' => '', 'Default' => 'http://www.mollie.nl/xml/ideals'),
					'shipping_control' => Array('Name' => 'Shipping Control', 'Type' => 'select', 'ValueList' => '3=la_CreditDirect,4=la_CreditPreAuthorize', 'Default' => '3'),
				)
			);
			return $data;
		}

		/**
		 * 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)
		{
			$this->Application->StoreVar('gw_success_template',$tag_params['return_template']);
			$this->Application->StoreVar('gw_cancel_template',$tag_params['cancel_template']);

			$banks_query = $gw_params['request_url'].'?a=banklist';

			$banks = curl_post($banks_query, null, null, 'GET');

			$parser =& $this->Application->recallObject('kXMLHelper');
			/* @var $parser kXMLHelper */
			$bank_data =& $parser->Parse($banks);

			$bank_data->FindChild('response');
			$banks = array();
			foreach ($bank_data->Children as $a_child) {
				if ($a_child->Name != 'BANK') continue;
				$banks[$a_child->FindChildValue('bank_id')] = $a_child->FindChildValue('bank_name');
			}

			$ret = $this->Application->Phrase('lu_Select_iDEAL_bank').': <select name="ideal_nl_bank_id">';
			foreach ($banks as $id => $name) {
				$ret .= '<option value="'.$id.'">'.$name.'</option>';
			}
			$ret .= '</select>';
			$ret .= '<input type="hidden" name="events[ord]" value="OnCompleteOrder" />'."\n";
			return $ret;
		}

		function DirectPayment($item_data, $gw_params)
		{
			$fields = array();

			$fields['a'] = 'fetch';
			$fields['partnerid'] = $gw_params['partner_id'];
			$txt_amount = sprintf("%.2f", $item_data['TotalAmount']);
			$fields['amount'] = str_replace( Array('.', ','), '', $txt_amount);
			$fields['bank_id'] = $this->Application->GetVar('ideal_nl_bank_id');
			$fields['description'] = 'Invoice #'.$item_data['OrderNumber'];
			$fields['returnurl'] = $this->getNotificationUrl() . '?order_id='.$item_data['OrderId'];
			$fields['reporturl'] = $this->getNotificationUrl() . '?mode=report&order_id='.$item_data['OrderId'];

			$transaction_xml = curl_post($gw_params['request_url'], $fields, null, 'GET');

			$parser =& $this->Application->recallObject('kXMLHelper');
			/* @var $parser kXMLHelper */
			$trans_data =& $parser->Parse($transaction_xml);
			$transaction_id = $trans_data->FindChildValue('transaction_id');
			$url = $trans_data->FindChildValue('url');

			if ($transaction_id && $url) {
				$this->Application->Redirect('external:'.$url);
			}
			else {
				$error_msg = $trans_data->FindChildValue('message');
				$this->parsed_responce['XML'] = $transaction_xml;
				$this->Application->SetVar('failure_template', $this->Application->RecallVar('gw_cancel_template'));
				$this->parsed_responce['MESSAGE'] = $error_msg ? $error_msg : 'Unknown gateway error ('.htmlspecialchars($transaction_xml).')';
				return false;
			}
		}

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

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

		function processNotification($gw_params)
		{
			// silent mode
			if ($this->Application->GetVar('mode') == 'report') {
				$fields = array();

				$fields['a'] = 'check';
				$fields['partnerid'] = $gw_params['partner_id'];
				$fields['transaction_id'] =  $this->Application->GetVar('transaction_id');
				$fields['bank_id'] = $this->Application->GetVar('ideal_nl_bank_id');

				$check_xml = curl_post($gw_params['request_url'], $fields, null, 'GET');
				$parser =& $this->Application->recallObject('kXMLHelper');
				/* @var $parser kXMLHelper */
				$trans_data =& $parser->Parse($check_xml);

				$response = $trans_data->FindChild('order');
				foreach ($response->Children as $a_child) {
					$this->parsed_responce[$a_child->Name] = $a_child->Data;
				}
				$this->parsed_responce['XML'] = $check_xml;

				$result = $trans_data->FindChildValue('payed') == 'true' ? 1:0;
				return $result;
			}
			else {
				$order =& $this->Application->recallObject('ord');
				if ($order->GetDBField('Status') == ORDER_STATUS_INCOMPLETE) {
					// error
					$t = $this->Application->RecallVar('gw_cancel_template');
					$this->parsed_responce = unserialize($order->GetDBField('GWResult1'));
					$this->Application->StoreVar('gw_error', $this->getErrorMsg());
					$this->Application->Redirect($t, array('pass'=>'m', 'm_cat_id'=>0));
				}
				else {
					// ok
					$t = $this->Application->RecallVar('gw_success_template');
					$this->Application->Redirect($t, array('pass'=>'m', 'm_cat_id'=>0));

				}
			}
		}
	}