<?php

use Vn\Tpv;

function procesaNotificacionSIS ($XML)
{
	$status = 'OK';
	$requestString = $XML;

	// Processes the request

	try {
		Tpv::init ();

		$xml = new SimpleXMLElement ($requestString);
		$request = (array) $xml->{'Request'};
		
		if (!(isset ($request['Ds_Amount'])
		&& isset ($request['Ds_Order'])
		&& isset ($request['Ds_MerchantCode'])
		&& isset ($request['Ds_Currency'])
		&& isset ($request['Ds_Response'])))
			throw new Exception ('Missing required parameters');
	
		// Checks the signature

		$start = strpos ($requestString, '<Request');
		$end = strrpos ($requestString, '</Request>');
		$shaString = substr ($requestString, $start, $end - $start + 10);

		$key = Tpv::$conn->getValue (
			'SELECT secret_key FROM tpv_merchant WHERE id = #'
			,[$request['Ds_MerchantCode']]
		);

		if (sha1 ($shaString.$key) != $xml->{'Signature'})
			throw new Exception ('Invalid signature');
			
		// Confirms the transaction

		Tpv::$conn->query (
			'CALL transaction_confirm (#, #, #, #, #)',
			[
				 $request['Ds_Amount']
				,$request['Ds_Order']
				,$request['Ds_MerchantCode']
				,$request['Ds_Currency']
				,$request['Ds_Response']
			]
		);
	}
	catch (Exception $e)
	{
		$status = 'KO';
	}

	Tpv::deinit ();

	// Generates the response

	$responseString = file_get_contents (__DIR__ .'/soap-reply.xml');
	$xml = new SimpleXMLElement ($responseString);

	$response = $xml->{'Response'};
	$response->{'Ds_Response_Merchant'} = $status;

	$xml->{'Signature'} = sha1 ($response->asXML ().$key);

	return $xml->asXML ();
/*
	// Another way to generate the response

	$xmlResponse =
	'<Response Ds_Version="0.0">
		<Ds_Response_Merchant>'. $status .'</Ds_Response_Merchant>
	</Response>';

	$xmlMessage =
	'<Message>
		'. $xmlResponse .'
		<Signature>'. sha1 ($xmlResponse.$key) .'</Signature>
	</Message>';

	return $xmlMessage;
*/}

?>
