<?php

require_once ('vn/web/json-request.php');
require_once ('vn/tpv/tpv.php');

use Vn\Lib;

/**
 * Starts a new TPV transaction and returns the params.
 **/
class TpvTransaction extends Vn\Web\JsonRequest
{
	function run ()
	{
		$this->login ();

		if (empty ($_REQUEST['amount']))
			throw new Exception  ('Amount parameter not defined');

		$amount = (int) $_REQUEST['amount'];
		$companyId = empty ($_REQUEST['company']) ? NULL : $_REQUEST['company'];

		$db = $this->getSysConn ();
		$row = $db->getRow ('CALL transaction_start_sha256 (#, #)',
			[$amount, $companyId]);
		
		if (!isset ($row))
			throw new Exception ('Transaction error');

		$transactionId = str_pad ($row['transaction_id'], 12, '0', STR_PAD_LEFT);
		$urlOk = empty ($_REQUEST['urlOk']) ? '' : sprintf ($_REQUEST['urlOk'], $transactionId);
		$urlKo = empty ($_REQUEST['urlKo']) ? '' : sprintf ($_REQUEST['urlKo'], $transactionId);
		$merchantUrl = $row['merchant_url'] ? $row['merchant_url'] : '';
		
		$params = [
			 'Ds_Merchant_Amount'            => $amount
			,'Ds_Merchant_Order'             => $transactionId
			,'Ds_Merchant_MerchantCode'      => $row['merchant']
			,'Ds_Merchant_Currency'          => $row['currency']
			,'Ds_Merchant_TransactionType'   => $row['transaction_type']
			,'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['secret_key']);
		
		$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'];

		$this->json ([
			 'url'       => $url
			,'params'    => $encodedParams
			,'signature' => $signature
		]);
	}
}

?>