<?php
/***************************************************************************
*                                                                          *
*    Copyright (c) 2009 Simbirsk Technologies Ltd. All rights reserved.    *
*                                                                          *
* This  is  commercial  software,  only  users  who have purchased a valid *
* license  and  accept  to the terms of the  License Agreement can install *
* and use this program.                                                    *
*                                                                          *
****************************************************************************
* PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
* "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
****************************************************************************/


//
// $Id: ideal_xml.php 8138 2009-10-28 12:45:37Z zeke $
//

use Tygh\Registry;

if(!defined('BOOTSTRAP')) { die('Access denied'); }

$sRootPath = dirname(__FILE__);

while((strlen($sRootPath) > 2) && !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');





if(!function_exists('idealcheckout_getPrices'))
{
	function idealcheckout_getPrices($fPrice, $iItemId, $aTaxes, $sItemCode = 'P')
	{
		$aPrices = array();
		$aPrices['price_incl'] = 0;
		$aPrices['price_excl'] = 0;
		$aPrices['price_vat'] = 0;
		$aPrices['percentage_vat'] = 0;

		$fIncludedTaxPercentage = 0;
		$fIncludedTaxFixed = 0;

		$fExcludedTaxPercentage = 0;
		$fExcludedTaxFixed = 0;

		if(is_array($aTaxes))
		{
			foreach($aTaxes as $aTax)
			{
				if(isset($aTax['applies']['items'][$sItemCode][$iItemId]) || isset($aTax['applies']['items'][$sItemCode][0][$iItemId]))
				{
					if($aTax['rate_type'] == 'P') // Percentage
					{ 
						if($aTax['price_includes_tax'] == 'Y')
						{
							$fIncludedTaxPercentage += $aTax['rate_value'];
						}
						else
						{
							$fExcludedTaxPercentage += $aTax['rate_value'];
						}
					} 
					else // Fixed
					{
						// If tax is NOT included into the price
						if($aTax['price_includes_tax'] == 'Y') 
						{
							$fIncludedTaxFixed += $aTax['rate_value'];
						}
						else
						{
							$fExcludedTaxFixed += $aTax['rate_value'];
						}
					}
				}
			}

			$aPrices['price_incl'] = round(($fPrice * (1 + (($fExcludedTaxPercentage) / 100))) + $fExcludedTaxFixed, 2);
			$aPrices['price_excl'] = round((($fPrice - $fIncludedTaxFixed) / (100 + $fIncludedTaxPercentage)) * 100, 2);
			$aPrices['vat'] = round((($aPrices['price_incl'] - $aPrices['price_excl']) / $aPrices['price_excl']) * 100, 0);
		}

		return $aPrices;
	}
}





// Load database settings
$aDatabaseSettings = idealcheckout_getDatabaseSettings();

if(defined('PAYMENT_NOTIFICATION'))
{
	if ($mode == 'notify') {
		if(isset($_GET['order_id']) && isset($_GET['order_code']))
		{
			$sOrderId = $_GET['order_id'];
			$sOrderCode = $_GET['order_code'];

			$sql = "SELECT * FROM `" . $aDatabaseSettings['table'] . "` WHERE (`order_id` = '" . idealcheckout_escapeSql($sOrderId) . "') AND (`order_code` = '" . idealcheckout_escapeSql($sOrderCode) . "') ORDER BY `id` DESC LIMIT 1;";
			$aRecord = idealcheckout_database_getRecord($sql);

			if($aRecord)
			{
				$pp_response['transaction_id'] = $aRecord['transaction_id'];

				if(in_array($aRecord['transaction_status'], array('SUCCESS')))
				{
					$pp_response['order_status'] = 'P';
					$pp_response['reason_text'] = 'Payment processed.';
				}
				elseif(in_array($aRecord['transaction_status'], array('PENDING', 'OPEN')))
				{
					$pp_response['order_status'] = 'O'; // still waiting for the response
					$pp_response['reason_text'] = 'Payment open.';
				}
				else
				{
					$pp_response['order_status'] = 'F';
					$pp_response['reason_text'] = 'Payment failed.';
				}

				fn_finish_payment($sOrderId, $pp_response, false);
				fn_order_placement_routines('route', $sOrderId);
			}
		}
	}
} else {

	$aDatabaseSettings = idealcheckout_getDatabaseSettings();

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

	$sOrderId = $order_id;
	$sOrderCode = idealcheckout_getRandomCode(32);
	$aOrderParams = array();
	$sTransactionId = idealcheckout_getRandomCode(32);
	$sTransactionCode = idealcheckout_getRandomCode(32);
	$fTransactionAmount = number_format($order_info['total'], 2, '.', '');
	$sTransactionDescription = idealcheckout_getTranslation($sLanguageCode, 'idealcheckout', 'Webshop order #{0}', array($sOrderId));
	$sTransactionPaymentUrl = Registry::get('config.current_location') . '/' . (AREA == 'A' ? Registry::get('config.admin_index') : Registry::get('config.customer_index')) . '?dispatch=payment_notification.notify&payment=idealcheckoutideal&order_id=' . $order_id . '&order_code=' . $sOrderCode;
	// $sTransactionPaymentUrl = fn_url('payment_notification.return?payment=idealcheckoutideal&order_id=' . $order_id . '&order_code=' . $sOrderCode, AREA, 'current');
	$sTransactionSuccessUrl = $sTransactionPaymentUrl;
	$sTransactionPendingUrl = $sTransactionPaymentUrl;
	$sTransactionFailureUrl = $sTransactionPaymentUrl;
	$aTransactionParams = array();



	$aOrderParams['customer'] = array();




	// Shipment data
	list($sStreetName, $sStreetNumber, $sExtension) = idealcheckout_mb_splitAddress($order_info['s_address'] . ' ' . $order_info['s_address_2']);

	$aOrderParams['customer']['shipment_company'] = '';
	$aOrderParams['customer']['shipment_name'] = trim($order_info['s_firstname'] . ' ' . $order_info['s_firstname']);
	$aOrderParams['customer']['shipment_first_name'] = $order_info['s_firstname'];
	$aOrderParams['customer']['shipment_last_name'] = $order_info['s_lastname'];
	$aOrderParams['customer']['shipment_gender'] = '';
	$aOrderParams['customer']['shipment_date_of_birth'] = '';
	$aOrderParams['customer']['shipment_phone'] = $order_info['s_phone'];
	$aOrderParams['customer']['shipment_email'] = $order_info['email'];
	$aOrderParams['customer']['shipment_address'] = trim($order_info['s_address'] . (empty($order_info['s_address_2']) ? '' : ', ' . $order_info['s_address_2']));
	$aOrderParams['customer']['shipment_street_name'] = $sStreetName;
	$aOrderParams['customer']['shipment_street_number'] = $sStreetNumber;
	$aOrderParams['customer']['shipment_street_number_extension'] =  $sExtension;
	$aOrderParams['customer']['shipment_zipcode'] = $order_info['s_zipcode'];
	$aOrderParams['customer']['shipment_city'] = $order_info['s_city'];
	$aOrderParams['customer']['shipment_country_code'] = $order_info['s_country'];
	$aOrderParams['customer']['shipment_country_name'] = ((strcasecmp($order_info['s_country'], 'BE') === 0) ? 'Belgie' : 'Nederland');


	// Payment data
	list($sStreetName, $sStreetNumber, $sExtension) = idealcheckout_mb_splitAddress($order_info['b_address'] . ' ' . $order_info['b_address_2']);

	$aOrderParams['customer']['payment_company'] = '';
	$aOrderParams['customer']['payment_name'] = trim($order_info['b_firstname'] . ' ' . $order_info['b_firstname']);
	$aOrderParams['customer']['payment_first_name'] = $order_info['b_firstname'];
	$aOrderParams['customer']['payment_last_name'] = $order_info['b_lastname'];
	$aOrderParams['customer']['payment_gender'] = '';
	$aOrderParams['customer']['payment_date_of_birth'] = '';
	$aOrderParams['customer']['payment_phone'] = $order_info['b_phone'];
	$aOrderParams['customer']['payment_email'] = $order_info['email'];
	$aOrderParams['customer']['payment_address'] = trim($order_info['b_address'] . (empty($order_info['b_address_2']) ? '' : ', ' . $order_info['b_address_2']));
	$aOrderParams['customer']['payment_street_name'] = $sStreetName;
	$aOrderParams['customer']['payment_street_number'] = $sStreetNumber;
	$aOrderParams['customer']['payment_street_number_extension'] = $sExtension;
	$aOrderParams['customer']['payment_zipcode'] = $order_info['b_zipcode'];
	$aOrderParams['customer']['payment_city'] = $order_info['b_city'];
	$aOrderParams['customer']['payment_country_code'] = $order_info['b_country'];
	$aOrderParams['customer']['payment_country_name'] = ((strcasecmp($order_info['b_country'], 'BE') === 0) ? 'Belgie' : 'Nederland');





	// Products
	$aOrderParams['products'] = array();

	foreach($order_info['products'] as $k => $aProduct)
	{
		if(!empty($aProduct['product']))
		{
			$sDescription = $aProduct['product'];
		}
		elseif(!empty($aProduct['product_code']))
		{
			$sDescription = $aProduct['product_code'];
		}
		else
		{
			$sDescription = $aProduct['sku'];
		}

		if(isset($aProduct['extra']) && isset($aProduct['extra']['exclude_from_calculate']) && $aProduct['extra']['exclude_from_calculate']==1)
		{
			$fPriceIncl = 0.00;
			$fPriceExcl = 0.00;
			$fVat = 0; // Percentage
		}
		else
		{
			$aPrices = idealcheckout_getPrices($aProduct['original_price'], $aProduct['item_id'], $order_info['taxes'], 'P');

			$fPriceIncl = $aPrices['price_incl'];
			$fPriceExcl = $aPrices['price_excl'];
			$fVat = $aPrices['vat']; // Percentage
		}

		$aOrderParams['products'][] = array('code' => $aProduct['product_code'], 'description' => $sDescription, 'quantity' => $aProduct['amount'], 'price_incl' => $fPriceIncl, 'price_excl' => $fPriceExcl, 'vat' => $fVat);
	}





	// Discount?
	if(isset($order_info['discount']) && ($order_info['discount'] != 0))
	{
		$fBaseDiscountAmount = round(0 - floatval($order_info['discount']), 2);
		$fBaseDiscountTaxAmount = 0;
		$fBaseDiscountTax = 0;

		$aOrderParams['products'][] = array('code' => 'DISCOUNT', 'description' => 'Korting en overige kosten', 'quantity' => '1', 'price_incl' => ($fBaseDiscountAmount + $fBaseDiscountTaxAmount), 'price_excl' => $fBaseDiscountAmount, 'vat' => $fBaseDiscountTax);
	}


	// Discount?
	if(isset($order_info['subtotal_discount']) && ($order_info['subtotal_discount'] != 0))
	{
		$fBaseDiscountAmount = round(0 - floatval($order_info['subtotal_discount']), 2);
		$fBaseDiscountTaxAmount = 0;
		$fBaseDiscountTax = 0;

		$aOrderParams['products'][] = array('code' => 'DISCOUNT', 'description' => 'Korting en overige kosten', 'quantity' => '1', 'price_incl' => ($fBaseDiscountAmount + $fBaseDiscountTaxAmount), 'price_excl' => $fBaseDiscountAmount, 'vat' => $fBaseDiscountTax);
	}


	// Shipping costs?
	if(isset($order_info['shipping_ids']))
	{
		$aPrices = idealcheckout_getPrices($order_info['shipping_cost'], $order_info['shipping_ids'], $order_info['taxes'], 'S');

		$aOrderParams['products'][] = array('code' => 'SHIPPING', 'description' => 'Verzendkosten', 'quantity' => '1', 'price_incl' => $aPrices['price_incl'], 'price_excl' => $aPrices['price_excl'], 'vat' => $aPrices['vat']);
	}


	// Payment costs?
	if(isset($order_info['payment_surcharge']) && ($order_info['payment_surcharge'] > 0))
	{
		$fBasePaymentAmount = round(floatval($order_info['payment_surcharge']), 2);
		$fBasePaymentTaxAmount = 0;
		$fBasePaymentTax = 0;

		$aOrderParams['products'][] = array('code' => 'PAYMENT', 'description' => 'Betaalkosten', 'quantity' => '1', 'price_incl' => ($fBasePaymentAmount + $fBasePaymentTaxAmount), 'price_excl' => $fBasePaymentAmount, 'vat' => $fBasePaymentTax);
	}


	// Gift certificates?
	if(isset($order_info['use_gift_certificates']) && ($order_info['use_gift_certificates'] > 0))
	{
		$fDiscount = 0.00;

		foreach($order_info['use_gift_certificates'] as $aCertificate)
		{
			$fDiscount += floatval($certificate['amount']);
		}

		$fBaseDiscountAmount = round($fDiscount, 2);
		$fBaseDiscountTaxAmount = 0;
		$fBaseDiscountTax = 0;

		$aOrderParams['products'][] = array('code' => 'DISCOUNT', 'description' => 'Cadeaubon', 'quantity' => '1', 'price_incl' => ($fBaseDiscountAmount + $fBaseDiscountTaxAmount), 'price_excl' => $fBaseDiscountAmount, 'vat' => $fBaseDiscountTax);
	}





	// 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;";
	db_query($sql);

	echo '<html><body onLoad="javascript: document.process.submit();"><form method="post" action="' . Registry::get('config.http_path') . '/idealcheckout/setup.php?order_id=' . $sOrderId . '&order_code=' . $sOrderCode . '" name="process"></form></body></html>';
	exit;
}

?>