<?php

	// Load gateway setings
	$sRootPath = dirname(__FILE__);

	while((strlen($sRootPath) > 3) && !is_dir($sRootPath . '/idealcheckout'))
	{
		$sRootPath = dirname($sRootPath);
	}

	if(!is_dir($sRootPath . '/idealcheckout'))
	{
		die('Cannot find /idealcheckout/ folder.<br>File: ' . __FILE__ . '<br>Line: ' . __LINE__);
	}

	require_once($sRootPath . '/idealcheckout/includes/library.php');



	class pm_idealcheckoutcreditcard
	{
		private $system;
		public $id = __CLASS__;
		public $name = 'Creditcard';
		public $description = '';
		public $author = 'iDEAL Checkout';
		public $version = '2.0.2';
		public $website = 'https://www.ideal-checkout.nl';
		public $priority = 0;


	  /*
	   * Return selectable payment options for checkout
	   */
		public function options($items, $subtotal, $tax, $currency_code, $customer) 
		{
			global $order;
			// If not enabled
			if(empty($this->settings['status']))
			{
				return;
			}

			if (!empty($this->settings['geo_zone_id'])) 
			{
				if (functions::reference_in_geo_zone($this->settings['geo_zone_id'], $customer['country_code'], $customer['zone_code']) != true) return;
			}

			$aPaymentMethod = array(
				'title' => $this->name,
				'options' => array(
					array(
					'id' => 'creditcard',
					'icon' => $this->settings['icon'],
					'name' => 'Creditcard',
					'description' => language::translate('pay_with_creditcard', 'Pay with Creditcard'),
					'fields' => '',
					'cost' => floatval($this->settings['fee']) + floatval($subtotal + $tax) * floatval(floatval($this->settings['fee_percent'])/100),
					'tax_class_id' => 0,
					'confirm' => language::translate('pay', 'pay'),
					),
				)
			);

			return $aPaymentMethod;
		}
		
		public function pre_check() 
		{
		
		}

		public function transfer($order) // Collect order data and execute payment
		{
			if(empty($order))
			{
				global $order;
			}

			$aDatabaseSettings = idealcheckout_getDatabaseSettings();

			$sStoreCode = idealcheckout_getStoreCode();
			$sGatewayCode = 'creditcard';
			$sLanguageCode = 'nl'; // nl, de, en
			$sCountryCode = '';
			$sCurrencyCode = 'EUR';


			// Add transaction record to database
			$sOrderId = $order->data['uid'];
			$sOrderCode = idealcheckout_getRandomCode(32);
			$aOrderParams = array();
			$sTransactionId = idealcheckout_getRandomCode(32);
			$sTransactionCode = idealcheckout_getRandomCode(32);
			$fTransactionAmount = round(str_replace(',', '', $order->data['payment_due'] * $order->data['currency_value']), 2);
			$sTransactionDescription = idealcheckout_getTranslation($sLanguageCode, 'idealcheckout', 'Webshop order #{0}', array($sOrderId));
			
			if(class_exists('document'))
			{
				$sTransactionPaymentUrl = document::ilink('order_process');
				$sTransactionSuccessUrl = $sTransactionPaymentUrl;
				$sTransactionPendingUrl = $sTransactionPaymentUrl;
				$sTransactionFailureUrl = document::ilink('checkout');
			}
			else
			{			
				$sTransactionPaymentUrl = $GLOBALS['system']->document->link('order_process.php');
				$sTransactionSuccessUrl = $sTransactionPaymentUrl;
				$sTransactionPendingUrl = $sTransactionPaymentUrl;
				$sTransactionFailureUrl = $GLOBALS['system']->document->link('checkout.php');
			}


			// Insert into #_transactions
			$sql = "INSERT INTO `" . $aDatabaseSettings['table'] . "` SET 
`id` = NULL, 
`order_id` = '" . idealcheckout_escapeSql($sOrderId) . "', 
`order_code` = '" . idealcheckout_escapeSql($sOrderCode) . "', 
`order_params` = '" . idealcheckout_escapeSql(idealcheckout_serialize($aOrderParams)) . "', 
`store_code` = " . (empty($sStoreCode) ? "NULL" : "'" . idealcheckout_escapeSql($sStoreCode) . "'") . ", 
`gateway_code` = '" . idealcheckout_escapeSql($sGatewayCode) . "', 
`language_code` = " . (empty($sLanguageCode) ? "NULL" : "'" . idealcheckout_escapeSql($sLanguageCode) . "'") . ", 
`country_code` = " . (empty($sCountryCode) ? "NULL" : "'" . idealcheckout_escapeSql($sCountryCode) . "'") . ", 
`currency_code` = '" . idealcheckout_escapeSql($sCurrencyCode) . "', 
`transaction_id` = '" . idealcheckout_escapeSql($sTransactionId) . "', 
`transaction_code` = '" . idealcheckout_escapeSql($sTransactionCode) . "', 
`transaction_params` = NULL, 
`transaction_date` = '" . idealcheckout_escapeSql(time()) . "', 
`transaction_amount` = '" . idealcheckout_escapeSql($fTransactionAmount) . "', 
`transaction_description` = '" . idealcheckout_escapeSql($sTransactionDescription) . "', 
`transaction_status` = NULL, 
`transaction_url` = NULL, 
`transaction_payment_url` = '" . idealcheckout_escapeSql($sTransactionPaymentUrl) . "', 
`transaction_success_url` = '" . idealcheckout_escapeSql($sTransactionSuccessUrl) . "', 
`transaction_pending_url` = '" . idealcheckout_escapeSql($sTransactionPendingUrl) . "', 
`transaction_failure_url` = '" . idealcheckout_escapeSql($sTransactionFailureUrl) . "', 
`transaction_log` = NULL;";

			idealcheckout_database_query($sql);

			
			$sGatewayUrl = WS_DIR_HTTP_HOME . 'idealcheckout/setup.php?order_id=' . urlencode($sOrderId) . '&order_code=' . urlencode($sOrderCode);


			 return array(
'action' => $sGatewayUrl,
'method' => 'post',
'fields' => '',
);


		}
		
		public function verify() // Return from gateway
		{
			global $order;

			$aDatabaseSettings = idealcheckout_getDatabaseSettings();

			$errors = array();

			$sql = "SELECT * FROM `" . $aDatabaseSettings['table'] . "` WHERE (`order_id` = '" . idealcheckout_escapeSql($order->data['uid']) . "') LIMIT 1";
			if($aRecord = idealcheckout_database_getRecord($sql))
			{
				$sOrderId = $aRecord['order_id'];
				$sTransactionStatus = $aRecord['transaction_status'];
				
				if(strcmp($sTransactionStatus, 'SUCCESS') === 0)
				{
					$order->save(); // Save order to database

					return array(
						'order_status_id' => $this->settings['order_status_id_complete'],
						'payment_transaction_id' => $aRecord['transaction_id'],
						'transaction_id' => $aRecord['transaction_id'],
						'errors' => '',
					);
				}
				elseif(strcmp($sTransactionStatus, 'PENDING') === 0)
				{
					return array(
						'order_status_id' => $this->settings['order_status_id_complete'],
						'payment_transaction_id' => $aRecord['transaction_id'],
						'transaction_id' => $aRecord['transaction_id'],
						'errors' => '',
					);
				}
				elseif(strcmp($sTransactionStatus, 'CANCELLED') === 0) // Explicit cancel
				{
					return array(
						'order_status_id' => $this->settings['order_status_id_error'],
						'payment_transaction_id' => $aRecord['transaction_id'],
						'transaction_id' => $aRecord['transaction_id'],
						'errors' => '',
					);
				}
			
			}
		}
		
		public function after_process() 
		{
		}
		
		public function callback() 
		{
		}
		
		function settings() 
		{
			return array(
				array(
				'key' => 'status',
				'default_value' => '1',
				'title' => 'Status',
				'description' => 'Schakel de module in of uit.',
				'function' => 'toggle("e/d")',
				),
				array(
				'key' => 'icon',
				'default_value' => 'idealcheckout/images/creditcard.png',
				'title' => 'Icon',
				'description' => 'Het pad dat wijst naar het icon die je wil gebruiken.',
				'function' => 'input()',
				),
		        array(
		          'key' => 'fee',
		          'default_value' => '0',
		          'title' => language::translate(__CLASS__.':title_payment_fee', 'Payment Fee'),
		          'description' => language::translate(__CLASS__.':description_payment_fee', 'Adds a payment fee to the order.'),
		          'function' => 'decimal()',
		        ),
		        array(
		          'key' => 'fee_percent',
		          'default_value' => '0',
		          'title' => language::translate(__CLASS__.':title_payment_fee_percent', 'Payment Fee %'),
		          'description' => language::translate(__CLASS__.':description_payment_fee', 'Adds a payment fee % to the order.'),
		          'function' => 'decimal()',
		        ),
		        array(
		          'key' => 'geo_zone_id',
		          'default_value' => '',
		          'title' => language::translate(__CLASS__.':title_geo_zone', 'Geo Zone'),
		          'description' => language::translate(__CLASS__.':description_geo_zone', 'Limit this module to the selected geo zone. Otherwise leave blank.'),
		          'function' => 'geo_zones()',
		        ),
				array(
				'key' => 'order_status_id_complete',
				'default_value' => '0',
				'title' => 'Order status : Betaald',
				'description' => 'Geef bestellingen die succesvol betaald zijn deze status.',
				'function' => 'order_status()',
				),
				array(
				'key' => 'order_status_id_error',
				'default_value' => '0',
				'title' => 'Order status : Mislukt',
				'description' => 'Geef bestellingen die een mislukte betaling hebben zijn deze status.',
				'function' => 'order_status()',
				),
				array(
				'key' => 'priority',
				'default_value' => '0',
				'title' => 'Prioriteit',
				'description' => 'Verwerk de betaalmethode in deze volgorde.',
				'function' => 'int()',
				),
			);
		}

		public function install() 
		{
		}

		public function uninstall()
		{
		}

	}


?>