<?php
include_once(dirname(__FILE__).'/../../../config/config.inc.php');
include_once(dirname(__FILE__).'/../../../init.php');

include_once(_PS_MODULE_DIR_.'multisafepay/fastcheckout/multisafepay_express_checkout.php');
include_once(_PS_MODULE_DIR_.'multisafepay/api/MultiSafepay.combined.php');

if (_PS_VERSION_ < '1.5')
	require_once(_PS_ROOT_DIR_.'/controllers/OrderConfirmationController.php');

/* 1.4 Compatibility */
class MultisafepayExpressCheckoutSubmit extends OrderConfirmationControllerCore
{
	public function __construct()
	{
		$this->multisafepay = new Multisafepay();
		$this->context 		= Context::getContext();
		parent::__construct();
		$this->run();
	}

	public function displayContent()
	{
		$order = MultisafepayOrder::getOrderById((int)Tools::getValue('id_order'));

		$this->context->smarty->assign(array(
			'order' => $order,
			'price' => Tools::displayPrice($order['total_paid'], $this->context->currency),
			'use_mobile' => $this->context->getMobileDevice()));

		if (!$order)
			$this->context->smarty->assign('errors', array($this->multisafepay->l('Payment error')));

		echo $this->multisafepay->fetchTemplate('/views/templates/front/', 'order-confirmation');
	}
}

if(isset($_REQUEST['gateway']))
{
	if((($_REQUEST['method'] == 'connect' || $_REQUEST['method'] != 'gateways') || isset($_REQUEST['issuer']) ) && $_REQUEST['gateway'] != 'fastcheckout')
	{
		$vendor_tax 						= 	Configuration::get('MULTISAFEPAY_DEFAULT_TAX')/100;

		$order 		= new Multisafepay();
		$customer 	= new Customer((int)$cart->id_customer);
		$total 		= $cart->getOrderTotal(true, Cart::BOTH);
		//$order->validateOrder((int)$cart->id, Configuration::get('PS_OS_PREPARATION'), $total, 'Multisafepay', null, array(), null, false, $customer->secure_key);
		
		$query = "SELECT * FROM `"._DB_PREFIX_."orders` WHERE `id_cart`='".$cart->id."'";
		//$orderid = Db::getInstance()->getValue($query);
		
		$stamp = date("Ymdhis");
		$ip = $_SERVER['REMOTE_ADDR'];
		$orderid = "$stamp-$ip";
		$orderid = str_replace(".", "", "$orderid");
		
		if(isset($_REQUEST['gateway']))
		{
			if($_REQUEST['gateway'] != "connect"){
				$gateway = $_REQUEST['gateway'];
			}else{
				$gateway = '';
			}
		}else{
			$gateway = '';
		}

		$msp 								= 	new MultiSafepayConnector();
				
		if(Configuration::get('MULTISAFEPAY_SANDBOX'))
		{
			$msp->test 						= 	true;
		}
		else
		{
			$msp->test 						= 	false;
		}
		
		$address  							= 	new Address(intval($cart->id_address_invoice));
		$customer 							= 	new Customer(intval($cart->id_customer));
		$country  							= 	new Country(intval($address->id_country));
		$amount = number_format(Tools::convertPrice($cart->getOrderTotal(), $currency), 2, '.', '');

		$state_id = intval($address->id_state);
		if ($state_id > 0){
			$state = new State(intval($address->id_state));
			$state_code = $state->iso_code;
		}else{
			$state_code = '';
		}

		// determine amount
		$amount = round($amount * 100);
		
		// generate items list
		$products = $cart->getProducts();
		$items = "<ul>\n";
		foreach ($products as $product) {
			$items .= "<li>";
			$items .= $product['cart_quantity'] . " x : " . $product['name'];
			
			if (!empty($product['attributes_small']))
			 $items .= '(' . $product['attributes_small'] . ')';
			
			$items .= "</li>\n";
		}
		$items .= "</ul>\n";

		
		
		$msp->merchant['account_id'] 		=	Configuration::get('MULTISAFEPAY_API_USER');
		$msp->merchant['site_id'] 			= 	Configuration::get('MULTISAFEPAY_API_SIGNATURE');
		$msp->merchant['site_code'] 		= 	Configuration::get('MULTISAFEPAY_API_PASSWORD');
		$msp->merchant['notification_url'] 	= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/multisafepay/validation.php?mode=connect&type=initial&key='.$customer->secure_key;
		$msp->merchant['redirect_url'] 		= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/multisafepay/validation.php?mode=connect&redirect=true&type=initial&key='.$customer->secure_key;
		$msp->merchant['cancel_url']       	= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'order.php?step=3';
		$msp->merchant['close_window']		= 	true;
		$msp->customer['locale']			=  	str_replace('-', '_', Language::getLanguageCodeByIso(Language::getIsoById($cart->id_lang)));
		$msp->customer['firstname']        	= 	$address->firstname;
		$msp->customer['lastname']         	= 	$address->lastname;
		$msp->customer['zipcode']          	= 	$address->postcode;
		$msp->customer['city']             	= 	$address->city;
		$msp->customer['state']				= 	$state_code;
		$msp->customer['email']             = 	$customer->email;
		$msp->customer['phone']				= 	$address->phone_mobile;
		$msp->customer['country']          	= 	$country->iso_code;
		$msp->customer['referrer']			=	$_SERVER['HTTP_REFERER'];
		$msp->customer['user_agent']		=	$_SERVER['HTTP_USER_AGENT'];
		$msp->customer['ipaddress']			= 	$_SERVER['REMOTE_ADDR'];
		$msp->parseCustomerAddress($address->address1);
		$msp->customer['address2']			=	$address->address2;
		$msp->transaction['id']            	= 	$orderid;
		$msp->transaction['var1']			= 	$cart->id;
		$msp->transaction['var2']			= 	$customer->secure_key;
		$msp->transaction['currency']      	= 	'EUR'; //MSP only supports EUR at the moment  ->  $order_info['currency_code'];
		$msp->transaction['amount']        	= 	$amount;
		$msp->transaction['description']  	= 	'Order #' . $msp->transaction['id'];
		$msp->transaction['gateway']		= 	$gateway;
		$msp->plugin_name					= 	'PrestaShop '._PS_VERSION_;
		$msp->version						= 	'(1.7.1)';
		
		$msp->plugin['shop']				= 'PrestaShop';
		$msp->plugin['shop_version']		= _PS_VERSION_;
		$msp->plugin['plugin_version']		= '1.7.1';
		$msp->plugin['partner']				= '';
		$msp->plugin['shop_root_url']		= (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__;
		
		$msp->transaction['items']			= 	$items;
		$total_data = $cart->getSummaryDetails();
		
		if($gateway == 'IDEAL' && isset($_REQUEST['issuer'])){
			$msp->extravars					= 	$_REQUEST['issuer'];	
			$url 							= 	$msp->startDirectXMLTransaction();
		}elseif($gateway == 'PAYAFTER')
		{
			if(Configuration::get('MULTISAFEPAY_SANDBOX_PAD'))
			{
				$msp->test 						= 	true;
			}
			else
			{
				$msp->test 						= 	false;
			}
			
			$msp->merchant['account_id'] 		=	Configuration::get('MULTISAFEPAY_API_USER_PAD');
			$msp->merchant['site_id'] 			= 	Configuration::get('MULTISAFEPAY_API_SIGNATURE_PAD');
			$msp->merchant['site_code'] 		= 	Configuration::get('MULTISAFEPAY_API_PASSWORD_PAD');
			
		
			$msp->gatewayinfo['email']          = 	$customer->email;
			$msp->gatewayinfo['phone']			= 	$address->phone_mobile;
			$msp->gatewayinfo['bankaccount']    =	'';//not available
			$msp->gatewayinfo['referrer']		=	$_SERVER['HTTP_REFERER'];
			$msp->gatewayinfo['user_agent']		=	$_SERVER['HTTP_USER_AGENT'];
			$msp->gatewayinfo['birthday']		= 	'';//not available
		
	
			/*$c_item = new MspItem('Payment Fee' . " " . 'EUR', 'Payment Fee', '1', '2.95', '0', '0');//configurable amount must be set.
			$msp->cart->AddItem($c_item);	
			$c_item->SetMerchantItemId('Payment Fee');
			$c_item->SetTaxTableSelector($vendor_tax);//change taxrate
			*/
			$wrapping_tax_percentage = 0;
			$discount_tax_percentage = 0;
			$shipping_tax_percentage = 0;
			
			//Calculate discount tax and add it to the tax table
			if($total_data['total_discounts'] > 0){
				$discount_tax = $total_data['total_discounts'] - $total_data['total_discounts_tax_exc'];
				$discount_tax_percentage =  $discount_tax/$total_data['total_discounts_tax_exc'];
				$table 								= 	new MspAlternateTaxTable();
				$table->name						=	'discount_tax';
				$rule 								= 	new MspAlternateTaxRule($discount_tax_percentage);
				$table->AddAlternateTaxRules($rule);
				$msp->cart->AddAlternateTaxTables($table);
			}
			
			//Calculate wrapping tax and add it to the tax table
			if($total_data['total_wrapping'] > 0){
				$wrapping_tax = $total_data['total_wrapping'] - $total_data['total_wrapping_tax_exc'];
				$wrapping_tax_percentage =  $wrapping_tax/$total_data['total_wrapping_tax_exc'];
				$table 								= 	new MspAlternateTaxTable();
				$table->name						=	'wrapping_tax';
				$rule 								= 	new MspAlternateTaxRule($wrapping_tax_percentage);
				$table->AddAlternateTaxRules($rule);
				$msp->cart->AddAlternateTaxTables($table);
			}
			//Calculate shipping tax and add it to the tax table
			if($total_data['total_shipping'] > 0){
				$shipping_tax = $total_data['total_shipping'] - $total_data['total_shipping_tax_exc'];
				$shipping_tax_percentage =  $shipping_tax/$total_data['total_shipping_tax_exc'];
				
				$table 								= 	new MspAlternateTaxTable();
				$table->name						=	'shipping_tax';
				$rule 								= 	new MspAlternateTaxRule($shipping_tax_percentage);
				$table->AddAlternateTaxRules($rule);
				$msp->cart->AddAlternateTaxTables($table);
			}
			
			//add wrapping item
			if($total_data['total_wrapping_tax_exc'] != 0){
				$c_item = new MspItem('Wrapping' . " " . 'EUR', 'Wrapping', '1', $total_data['total_wrapping_tax_exc'], '0', '0') ;
				$msp->cart->AddItem($c_item);	
				$c_item->SetMerchantItemId('wrapping');
				$c_item->SetTaxTableSelector('wrapping_tax');
			}
		
			//add discount as negative item
			if($total_data['total_discounts'] != 0){
				$c_item = new MspItem('Discount' . " " . 'EUR', 'Discount', '1', -$total_data['total_discounts'], '0', '0') ;
				$msp->cart->AddItem($c_item);	
				$c_item->SetMerchantItemId('discount');
				$c_item->SetTaxTableSelector('0%');
			}
			
			//add Shipping
			$c_item = new MspItem('Shipping' . " " . 'EUR', 'Shipping', '1', $total_data['total_shipping_tax_exc'], '0', '0') ;
			$msp->cart->AddItem($c_item);	
			$c_item->SetMerchantItemId('Shipping');
			if(Configuration::get('MULTISAFEPAY_TAX_SHIPPING') == 1 || Configuration::get('MULTISAFEPAY_TAX_SHIPPING') =='1'){
				$c_item->SetTaxTableSelector('shipping_tax');
			}else{
				$c_item->SetTaxTableSelector('0%');
			}
		
			$item_list 							= 	"<ul>";		
			$tax_array 							=	 array();

			$vendor_tax 						= 	Configuration::get('MULTISAFEPAY_DEFAULT_TAX')/100;
			$msp->tax_rate 						= 	$vendor_tax;
			$total_amount 						= 	0;
			
			$products = $cart->getProducts();
			$i									= 	0;
		
			while($products[$i])
			{	
				$my_taxrate 					= 	round($products[$i]['rate'])/100;
				$my_taxname						=   $products[$i]['tax_name'];
				$tax_array[$i]['name']			= 	$my_taxname;
				$tax_array[$i]['rate']			= 	$my_taxrate;
				$i++;
			}

			$a 					= 	0;
			while($tax_array[$a]){
				//if($tax_array[$a] != $vendor_tax){
					$table 						= 	new MspAlternateTaxTable();
					$table->name				=	$tax_array[$a]['name'];
					$rule 						= 	new MspAlternateTaxRule($tax_array[$a]['rate']);
					$table->AddAlternateTaxRules($rule);
					$msp->cart->AddAlternateTaxTables($table);
				//}
				$a++;
			}
			
			//0% tax rule
			$table 								= 	new MspAlternateTaxTable();
			$table->name						=	'0%';
			$rule 								= 	new MspAlternateTaxRule(0.00);
			$table->AddAlternateTaxRules($rule);
			$msp->cart->AddAlternateTaxTables($table);
			

			if(Configuration::get('MULTISAFEPAY_TAX_SHIPPING') == 1 || Configuration::get('MULTISAFEPAY_TAX_SHIPPING') =='1'){
				$rule 							= 	new MspDefaultTaxRule($vendor_tax, true);
			}
			else
			{
				$rule 							= 	new MspDefaultTaxRule($vendor_tax, false);
			}	
			$msp->cart->AddDefaultTaxRules($rule);
			
			//GET CART CURRENCY
			$sql = 'SELECT * FROM '._DB_PREFIX_.'currency WHERE id_currency=\''.$cart->id_currency.'\'';
			
			if ($results = Db::getInstance()->ExecuteS($sql))
			{
				foreach ($results as $row)
				{
					$currency = $row['iso_code'];
				}
			}	
			
			$p = 0;
			while($products[$p])
			{
				$my_taxrate 					= 	round($products[$p]['rate']);
				$tax 							= 	$my_taxrate / 100;
				$price 							=  	$products[$p]['price'];
				$product_price 					= 	round( $price, 4 );
				$product_name 					=	$products[$p]['name'];

				$c_item = new MspItem($product_name . " " . $currency, $products[$p]['description_short'], $products[$p]['quantity'], $product_price, 'KG', $products[$p]['weight'] );
				$msp->cart->AddItem($c_item);
				$c_item->SetMerchantItemId($products[$p]['id_product']);
				$c_item->SetTaxTableSelector($products[$p]['tax_name']);
				$total_amount 					+= 	$product_price;
				$item_list 						.= 	'<li>'.$products[$p]['quantity'] . " x " . $product_name . "</li>"; //Text UTF-8
				$p++;
			}
			$item_list 							.= 	"</ul>";
		
			$url 							= 	$msp->startCheckout();
		}else
		{
			$url 							= 	$msp->startTransaction();
		}
		
		//print_r($msp);exit;
		
		if (!isset($msp->error)) 
		{
			header('Location: '. $url);
			exit;
		}else{
			echo 'Error: '.$msp->error;
		}
	}

	elseif (Tools::getValue('id_module') && Tools::getValue('key') && Tools::getValue('id_cart') && Tools::getValue('id_order'))
	{	
		//Hmm we are on an older version of Prestashop so we need to do things differently :)
		if (_PS_VERSION_ < '1.5')
			new MultisafepayExpressCheckoutSubmit();
	}
	else
	{
		$request_type = Tools::getValue('express_checkout');
		$ppec = new MultisafepayExpressCheckout($request_type);
		
		if ($request_type && $ppec->type || isset($_REQUEST['payafter']))
		{
			$id_product 			= (int)Tools::getValue('id_product');
			$id_product_attribute 	= (int)Tools::getValue('id_p_attr');
			$product_quantity 		= (int)Tools::getValue('quantity');

			if ($id_product && $id_product_attribute && $product_quantity)
			{
				// Create new Cart to avoid any refresh or other bad manipulations
				$ppec->context->cart 				= new Cart();
				$ppec->context->cart->id_currency 	= (int)$ppec->context->currency->id;
				$ppec->context->cart->id_lang 		= (int)$ppec->context->language->id;

				$secure_key = isset($ppec->context->customer) ? $ppec->context->customer->secure_key : '';
				$ppec->context->cart->secure_key = $secure_key;

				// Customer settings
				$ppec->context->cart->id_guest = (int)$ppec->context->cookie->id_guest;
				$ppec->context->cart->id_customer = (int)$ppec->context->customer->id;

				if (!$ppec->context->cart->add())
					$ppec->logs[] = $ppec->l('Cannot create new cart');
				else
					$ppec->context->cookie->id_cart = (int)$ppec->context->cart->id;
				
				$ppec->context->cart->updateQty((int)$product_quantity, (int)$id_product, (int)$id_product_attribute);
				$ppec->context->cart->update();
			}

			$msp 								= 	new MultiSafepayConnector();	
			$item_list 							= 	"<ul>";		
			$tax_array 							=	 array();

			if(Configuration::get('MULTISAFEPAY_SANDBOX'))
			{
				$msp->test 						= 	true;
			}
			else
			{
				$msp->test 						= 	false;
			}
			$msp->merchant['account_id'] 		=	Configuration::get('MULTISAFEPAY_API_USER');
			$msp->merchant['site_id'] 			= 	Configuration::get('MULTISAFEPAY_API_SIGNATURE');
			$msp->merchant['site_code'] 		= 	Configuration::get('MULTISAFEPAY_API_PASSWORD');
			$msp->merchant['notification_url'] 	= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/multisafepay/validation.php?mode=fastcheckout&type=initial&key='.$customer->secure_key;
			$msp->merchant['cancel_url']       	= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'order.php?step=3';
			$msp->merchant['redirect_url'] 	   	= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'order-confirmation.php?key='.$customer->secure_key;
			$msp->merchant['close_window']		= 	true;
			$vendor_tax 						= 	Configuration::get('MULTISAFEPAY_DEFAULT_TAX')/100;
			$msp->tax_rate 						= 	$vendor_tax;
			$total_amount 						= 	0;
			
			$products = $cart->getProducts();
			$i									= 	0;
			
			while($products[$i])
			{	
				$my_taxrate 					= 	round($products[$i]['rate'])/100;
				$my_taxname						=   $products[$i]['tax_name'];
				$tax_array[$i]['name']			= 	$my_taxname;
				$tax_array[$i]['rate']			= 	$my_taxrate;
				$i++;
			}
			$tax_array 							= 	array_unique($tax_array);

			$a 									= 	0;
			while($tax_array[$a]){
				$table 						= 	new MspAlternateTaxTable();
				$table->name				=	$tax_array[$a]['name'];
				$rule 						= 	new MspAlternateTaxRule($tax_array[$a]['rate']);
				$table->AddAlternateTaxRules($rule);
				$msp->cart->AddAlternateTaxTables($table);
				$a++;
			}

			if(Configuration::get('MULTISAFEPAY_TAX_SHIPPING') == 1 || Configuration::get('MULTISAFEPAY_TAX_SHIPPING') =='1'){
				$rule 							= 	new MspDefaultTaxRule($vendor_tax, true);
			}
			else
			{
				$rule 							= 	new MspDefaultTaxRule($vendor_tax, false);
			}	
			$msp->cart->AddDefaultTaxRules($rule);
			
			//GET CART CURRENCY
			$sql = 'SELECT * FROM '._DB_PREFIX_.'currency WHERE id_currency=\''.$cart->id_currency.'\'';
			
			if ($results = Db::getInstance()->ExecuteS($sql))
			{
				foreach ($results as $row)
				{
					$currency = $row['iso_code'];
				}
			}	

			//ADD PRODUCTS TO THE REQUEST
			$p = 0;
			while($products[$p])
			{
				//TODO: Prestashop rounds the product price to two decimals, this is wrong as some products have an amount with four decimals. This causes 1 cent rounding problems with FCO.
				//WE need to get the price from the Database by using the product id.
				
				$sql = 'SELECT * FROM '._DB_PREFIX_.'product WHERE id_product=\''.$products[$p]['id_product'].'\'';
				$results = Db::getInstance()->ExecuteS($sql);
				foreach ($results as $row)
				{
					$price = $row['price'];
				}
			
				$my_taxrate 					= 	round($products[$p]['rate']);
				$tax 							= 	$my_taxrate / 100;
				$price 							=  	$price;
				$product_price 					= 	round( $price, 4 );
				$product_name 					=	$products[$p]['name'];
				$c_item = new MspItem($product_name . " " . $currency, $products[$p]['description_short'], $products[$p]['quantity'], $product_price, 'KG', $products[$p]['weight'] );
				$msp->cart->AddItem($c_item);
				$c_item->SetMerchantItemId($products[$p]['id_product']);
				$c_item->SetTaxTableSelector($products[$p]['tax_name']);
				$total_amount 					+= 	$product_price;
				$item_list 						.= 	'<li>'.$products[$p]['quantity'] . " x " . $product_name . "</li>"; //Text UTF-8
				$p++;
				
				
			}
			$amount =$cart->getOrderTotal() *100;

		
			$item_list 							.= 	"</ul>";
			
			$msp->transaction['id']            	= 	$cart->id;
			$msp->transaction['currency']      	= 	'EUR'; //we accept only EUR!
			$msp->transaction['amount']        	= 	$amount;//$total_amount * 100;
			$msp->transaction['description']   	= 	'Transaction Order ID #' . $msp->transaction['id'];
			$msp->transaction['items']         	= 	$item_list;
			$msp->customer['referrer']			=	$_SERVER['HTTP_REFERER'];
			$msp->customer['user_agent']		=	$_SERVER['HTTP_USER_AGENT'];
			$msp->customer['ipaddress']			= 	$_SERVER['REMOTE_ADDR'];
			$extra_data							= 	array();
			$extra_data['id_shop']				= 	$cart->id_shop;
			$extra_data['id_lang']				= 	$cart->id_lang;
			$extra_data['id_currency']			= 	$cart->id_currency;
			$var3								= 	$cart->id_guest;
			$extra_data['secure_key']			= 	$cart->secure_key;
			$extra_data 						= 	json_encode($extra_data);
			$msp->transaction['var1']			= 	$extra_data;
			$msp->transaction['var2']			= 	$cart->id_customer;
			$msp->transaction['var3']			= 	$var3;
			
			$sql = 'SELECT * FROM '._DB_PREFIX_.'lang WHERE id_lang=\''.$cart->id_lang.'\'';
			if ($results = Db::getInstance()->ExecuteS($sql))
			{
				foreach ($results as $row)
				{
					$lang_code = $row['language_code'];
				}
			}
		
			$msp->customer['locale']			=  	str_replace('-', '_', Language::getLanguageCodeByIso(Language::getIsoById($cart->id_lang)));
			$msp->customer['ipaddress']			=  	$_SERVER['REMOTE_ADDR'];

			if(isset($cart->id_customer))
			{
				$sql = 'SELECT * FROM '._DB_PREFIX_.'customer WHERE id_customer=\''.$cart->id_customer.'\'';
				
				if ($results = Db::getInstance()->ExecuteS($sql))
				{
					foreach ($results as $row)
					{
						$currency = $row['iso_code'];
						$msp->customer['firstname'] 	= $row['firstname'];
						$msp->customer['lastname'] 		= $row['lastname'];
						$msp->customer['email'] 		= $row['email'];
						$sql = 'SELECT * FROM '._DB_PREFIX_.'address WHERE id_customer=\''.$cart->id_customer.'\'';
						if ($adresses= Db::getInstance()->ExecuteS($sql))
						{
							foreach ($adresses as $address)
							{
								$msp->parseCustomerAddress($address['address1']);
								$msp->customer['city']			= $address['city'];
								$msp->customer['zipcode'] 		= $address['postcode'];
								$msp->customer['phone'] 		= $address['phone'];
								$sql = 'SELECT * FROM '._DB_PREFIX_.'state WHERE id_state=\''.$address['id_state'].'\'';
								if ($states= Db::getInstance()->ExecuteS($sql))
								{
									foreach ($states as $state)
									{
										$msp->customer['state'] 		= $state['name'];
									}
								}
								$sql = 'SELECT * FROM '._DB_PREFIX_.'country WHERE id_country=\''.$address['id_country'].'\'';
								if ($countries= Db::getInstance()->ExecuteS($sql))
								{
									foreach ($countries as $country)
									{
										$msp->customer['country'] 		= $country['iso_code'];
									}
								}						
							}
						}	
					}
				}				
			}
			$msp->plugin_name					= 	'PrestaShop '._PS_VERSION_;
			$msp->version						= 	'(1.7.1)';
			
			$msp->plugin['shop']				= 	'PrestaShop';
			$msp->plugin['shop_version']		= 	_PS_VERSION_;
			$msp->plugin['plugin_version']		= 	'1.7.1';
			$msp->plugin['partner']				= 	'';
			$msp->plugin['shop_root_url']		= 	(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__;
			
			if(isset($_REQUEST['gateway'])){
				if($_REQUEST['gateway'] != "fastcheckout"){
					$msp->transaction['gateway']		= 	$msp->transaction['gateway'];
				}
			}
		
			$url 							= 	$msp->startCheckout();

		
			
			if ($msp->error)
			{
				echo "MultiSafepay Error " . $msp->error_code . ": " . $msp->error;
				exit();
			}
			header('Location: ' . $url);
			return true;
		}
	}
}
