<?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 myTpvTransaction_start(#, #)',
			[$amount, $companyId]);
		
		if (!isset($row))
			throw new Exception('Transaction error');

		$transactionId = str_pad($row->transactionId, 12, '0', STR_PAD_LEFT);
		$merchantUrl = $row->merchantUrl ? $row->merchantUrl : '';
		$urlOk = empty($_REQUEST['urlOk']) ? '' :
			str_replace('_transactionId_', $transactionId, $_REQUEST['urlOk']);
		$urlKo = empty($_REQUEST['urlKo']) ? '' :
			str_replace('_transactionId_', $transactionId, $_REQUEST['urlKo']);
		
		$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));

		$paddedData = $transactionId;
		if (strlen($paddedData) % 8) {
			$paddedData = str_pad($paddedData,
				strlen($paddedData) + 8 - strlen($paddedData) % 8, "\0");
		}

		$encryptedData = openssl_encrypt($paddedData,
			'des-ede3-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING , $iv);
		$signature = base64_encode(hash_hmac('sha256', $encodedParams, $encryptedData, TRUE));

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

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