<?php

require_once('vn/web/util.php');
require_once(__DIR__.'/tpv.php');

/**
 * Gets transaction confirmation from SOAP service.
 */
class ConfirmSoap extends Vn\Web\RestRequest {
	function run($db) {
		global $tpvConfirmSoap;

		$tpvConfirmSoap = $this;
		ini_set('soap.wsdl_cache_enabled', FALSE);

		$server = new SoapServer(__DIR__ .'/soap.wsdl');
		$server->addFunction('procesaNotificacionSIS');
		$server->handle();
	}
}

function procesaNotificacionSIS($XML) {
	global $tpvConfirmSoap;

	$db = $tpvConfirmSoap->app->getSysConn();

	$status = 'OK';
	$requestString = $XML;

	// Processes the request

	try {
		$xml = new SimpleXMLElement($requestString);
		$params =(array) $xml->{'Request'};
		
		if (!(isset($params['Ds_Amount'])
		&& isset($params['Ds_Order'])
		&& isset($params['Ds_MerchantCode'])
		&& isset($params['Ds_Currency'])
		&& isset($params['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 = $db->getValue(
			'SELECT secretKey FROM tpvMerchant WHERE id = #'
			,[$params['Ds_MerchantCode']]
		);

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

		Tpv::confirm($db, $params);
	} catch (Exception $e) {
		$status = 'KO';
	}

	// 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;
*/}