<?php

/**
 * Starts a new TPV transaction and returns the params.
 */
class Transaction extends Vn\Web\JsonRequest
{
	const PARAMS = ['amount'];

	function run ($db)
	{
		$amount = (int) $_REQUEST['amount'];
		$companyId = empty ($_REQUEST['company']) ? NULL : $_REQUEST['company'];
			
		$row = $db->getObject ('CALL transactionStart (#, #)',
			[$amount, $companyId]);
		
		if (!isset ($row))
			throw new Exception ('Transaction error');

		$transactionId = str_pad ($row->transactionId, 12, '0', STR_PAD_LEFT);
		$urlOk = empty ($_REQUEST['urlOk']) ? '' : sprintf ($_REQUEST['urlOk'], $transactionId);
		$urlKo = empty ($_REQUEST['urlKo']) ? '' : sprintf ($_REQUEST['urlKo'], $transactionId);
		$merchantUrl = $row->merchantUrl ? $row->merchantUrl : '';
		
		$params = [
			 'Ds_Merchant_Amount'            => $amount
			,'Ds_Merchant_Order'             => $transactionId
			,'Ds_Merchant_MerchantCode'      => $row->merchant
			,'Ds_Merchant_Currency'          => $row->currency
			,'Ds_Merchant_TransactionType'   => $row->transactionType
			,'Ds_Merchant_Terminal'          => $row->terminal
			,'Ds_Merchant_MerchantURL'       => $merchantUrl
			,'Ds_Merchant_UrlOK'             => $urlOk
			,'Ds_Merchant_UrlKO'             => $urlKo
		];
		
		$encodedParams = base64_encode (json_encode ($params));
		
		$key = base64_decode ($row->secretKey);
		
		$bytes = [0, 0, 0, 0, 0, 0, 0, 0];
		$iv = implode (array_map ('chr', $bytes));
		$key = mcrypt_encrypt (MCRYPT_3DES, $key, $transactionId, MCRYPT_MODE_CBC, $iv);
		
		$signature = base64_encode (hash_hmac ('sha256', $encodedParams, $key, TRUE));

		$url = $row->url;
		$postValues = [
			'Ds_SignatureVersion'   => 'HMAC_SHA256_V1'
		   ,'Ds_MerchantParameters' => $encodedParams
		   ,'Ds_Signature'          => $signature
		];

		return [
			 'url'        => $url
			,'postValues' => $postValues
		];
	}
}

