<?php
if (isset($_REQUEST['amount'])) {
	// Define credentials
	if ($_REQUEST['cc_plat'] == 'prod') {
		define('API_ENDPOINT', 'https://secure-gateway.allopass.com/rest/v1');
	} else {
		define('API_ENDPOINT', 'https://stage-secure-gateway.allopass.com/rest/v1');
	}
	
	// Define credentials	
	define('API_USERNAME', '94651622.api.allopass.com'); // Juan TEST
	define('API_PASSWORD', 'kcAihPJc0m8hhtJl9Tnh4pIP'); // Juan TEST
	//define('API_USERNAME', '94652618.api.hipay-tpp.com'); // support@hipay.com / HiPay Marketplace TEST
	//define('API_PASSWORD', 'KgS5GNhMGmAS7iK6vg4Mnwvq'); // support@hipay.com / HiPay Marketplace TEST
		
	$user = API_USERNAME;
	$password = API_PASSWORD;
	$credentials = $user . ':' . $password;
	$resource = API_ENDPOINT . '/hpayment';
	
	// Get merchant data
	require_once '../functions.php';
	$db = connecti();
	if ($db) {
		$merchant_query = "SELECT * FROM `merchants` WHERE `merchant_idwallet` = '".$_REQUEST['merchant_idwallet']."'" ;
		$merchant_result = $db->query($merchant_query);
		$merchant_row = $merchant_result->fetch_array(MYSQLI_ASSOC);
		
		$user_query = "SELECT * FROM `users` WHERE `user_idwallet` = '".$_REQUEST['user_idwallet']."'" ;
		$user_result = $db->query($user_query);
		$user_row = $user_result->fetch_array(MYSQLI_ASSOC);

	}
	
	if(!empty($merchant_row['merchant_name'])) {
		$merchant = $merchant_row['merchant_name'];
	}
	else {
		$merchant = 'Merchant ' . $_REQUEST['merchant_idwallet'] . ' not found';
	}
	
	echo "<br/>" . $resource  . "<br/><u>User: </u>" . $user . '<br/><u>Password: </u>' . $password;
	
	
	$products = 'cb';
	$ai = 1;
	$ds = 0;
	$lang = 'fr_FR';
	$category = 'credit-card';
	$currency = $_REQUEST['currency'];
	$amount = $_REQUEST['amount'];
	$template = "iframe-js";
	$uid = "MKP-".time();
	$operation = 'Sale';
	$email = $user_row['user_email'];
	$nom = $user_row['user_name'];
	
	$queryParameters = array(
	            'orderid'                  		=> $uid,
	            'operation'                		=> $operation,
	            'description'              		=> 'Alimentation de ' . $user_row['user_idwallet'] . ' via ' . $_REQUEST['merchant_idwallet'],
	            'amount'                   		=> $amount,
	            'currency'                 		=> $currency,
	            'eci'                      		=> '7',
	            'ipaddr'                   		=> '149.5.217.122', // US
	            'language'                 		=> $lang,
	            'email'                    		=> $email,
	            'cid'                      		=> $user_row['user_idwallet'],
	            'authentication_indicator' 		=> $ai,
	            'accept_url' 					=> 'http://sd-20614.dedibox.fr/~jabella/portage/ok.php',
			    'pending_url' 					=> 'http://sd-20614.dedibox.fr/~jabella/portage/pending.php',
			    'decline_url' 					=> 'http://sd-20614.dedibox.fr/~jabella/portage/decline.php',
			    'exception_url' 				=> 'http://sd-20614.dedibox.fr/~jabella/portage/exception.php',
			    'cancel_url' 					=> 'http://sd-20614.dedibox.fr/~jabella/portage/cancel.php',
			    'cdata1' 						=> $_REQUEST['merchant_idwallet'],
			    'cdata2' 						=> $merchant_row['merchant_email'],
			    'cdata3' 						=> 'portage',
			    'payment_product_list' 			=> $products,
			    'payment_product_category_list' => $category,
			    'template' 						=> $template,
			    'merchant_display_name' 		=> $merchant,
			    'display_selector' 				=> $ds,
			    'lastname'                  	=> $nom,
	            'firstname'               		=> '',
	        );
	
	
	// Create a new cURL resourse
	$curl = curl_init();
	
	$httpheader = array(
		'Content-Type: application/xml',
		'Accept: application/json' // 'text/xml'
	);
	
	$header = array(
	    'User-Agent: ' .$_SERVER['HTTP_USER_AGENT'],
	    'Accept: application/json', // 'text/xml' 'application/json'
	    'Accept-Language: ' . $_SERVER['HTTP_ACCEPT_LANGUAGE'],
//	    'Accept-Charset:' .  $_SERVER['HTTP_ACCEPT_CHARSET']
	);
	
	//test
	//$resource = "ifconfig.me";
	
	$options = array(
		CURLOPT_URL => $resource,
		CURLOPT_USERPWD => $credentials,
		CURLOPT_HTTPHEADER => $header,
		CURLOPT_RETURNTRANSFER =>true,
		CURLOPT_FAILONERROR => false,
		CURLOPT_HEADER =>false,
		CURLOPT_POST => true,
		CURLOPT_POSTFIELDS => http_build_query($queryParameters)
	);
	
	/*
		
		curl_setopt($_curlHandle, CURLOPT_HEADER, true);
	    curl_setopt($_curlHandle, CURLOPT_HTTPHEADER, $header);
	    curl_setopt($_curlHandle, CURLOPT_USERPWD, urlencode($username) . ':' . urlencode($password));
	    curl_setopt($_curlHandle, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($_curlHandle, CURLOPT_POST, true);
	    curl_setopt($_curlHandle, CURLOPT_POSTFIELDS, http_build_query($params));
	
	*/
	
	//echo "<br/><strong>Sent parameters: </strong><br/>" . http_build_query($queryParameters);
	
	
	
	foreach ($options as $option => $value) {
		curl_setopt($curl, $option, $value);
	}
	
	// execute the given cURL session
	if (false === ($result = curl_exec($curl))) {
		//throw new RuntimeException(curl_error($curl), curl_errno($curl));
		echo "<br/><strong>Error: </strong><br/>";
		var_dump(curl_error($curl), curl_errno($curl));
		exit();
	}
	
	//echo "<br/><strong>Return: </strong><br/>" . $result . "<br/>";
	//var_dump($result);
	
	//die();
		
	$status = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
	$response = json_decode($result);
	
	//echo "Status: " . $status . "<br/>";
	//var_dump($response);
	
	if (floor($status/100) != 2) {
		//throw new RuntimeException($response->message, $response->code);
		var_dump($response->message, $response->code);
		exit();
	}
	
	$url = $response->forwardUrl;
	//printf('URL: %s', $url);
	curl_close($curl);
	
	//echo "<br/><a href='".$url."' target='_blank'>Open page</a>";
	header('Location: ' . $url);
	
	
	function callCurlApi($url, $header, $params, $username, $password)
	{
	    $_curlHandle = curl_init();
	    curl_setopt(
	        $_curlHandle,        
		CURLOPT_URL,
		$url
	    );
	    curl_setopt($_curlHandle, CURLOPT_HEADER, true);
	    curl_setopt($_curlHandle, CURLOPT_HTTPHEADER, $header);
	    curl_setopt($_curlHandle, CURLOPT_USERPWD, urlencode($username) . ':' . urlencode($password));
	    curl_setopt($_curlHandle, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($_curlHandle, CURLOPT_POST, true);
	    curl_setopt($_curlHandle, CURLOPT_POSTFIELDS, http_build_query($params));
	
	    if (($transfer = curl_exec($_curlHandle)) === false) {
	        $errno   = curl_errno($_curlHandle);
	        $errmg   = curl_error($_curlHandle);
	
	        $message = sprintf(
	            'CURL execution failed with errno=%d and following message: %s',
	            $errno,
	            $errmg
	        );
	
	        throw new Exception($message);
	    }
	    return $transfer;
	}
	
	
	//$result = callCurlApi($resource, $httpheader, $queryParameters, API_USERNAME, API_PASSWORD);
	//print $result;
}
else { 
require_once '../functions.php';
$db = connecti();
$users = '';
$merchants = '';

if ($db) {
	$userslist_query = "SELECT * FROM `users` ORDER BY `user_email` ASC " ;
	$userslist_result = $db->query($userslist_query);
	while($userslist_row = $userslist_result->fetch_array(MYSQLI_ASSOC)) {
		$users .= '<option value="'.$userslist_row['user_idwallet'].'" label="'.$userslist_row['user_email'].'">'.$userslist_row['user_email'].'</option>'."\n";
	}
	$merchantslist_query = "SELECT * FROM `merchants` ORDER BY `merchant_email` ASC " ;
	$merchantslist_result = $db->query($merchantslist_query);
	while($merchantslist_row = $merchantslist_result->fetch_array(MYSQLI_ASSOC)) {
		$merchants .= '<option value="'.$merchantslist_row['merchant_idwallet'].'" label="'.$merchantslist_row['merchant_email'].'">'.$merchantslist_row['merchant_email'].'</option>'."\n";
	}
}

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Marketplace HiPay</title>
</head>
<body>
Make a payment:<br/>
<form action="payment.php" method="post" name="cc_form">
	<table>
		<tr>
			<td>User: </td>
			<td>
				<select name="user_idwallet" id="user_idwallet">
					<?php echo $users; ?>
				</select>
			</td>
		</tr>
		<tr>
			<td>Merchant: </td>
			<td>
				<select name="merchant_idwallet" id="merchant_idwallet">
					<?php echo $merchants; ?>
				</select>
			</td>
		</tr>
		 		 
		<tr>
			<td>Plateforme: </td>
			<td>
				<select name="cc_plat" id="cc_plat">
					<option value="sandbox" label="sandbox">Sandbox</option>
				    <option value="prod" label="prod">Production</option>
				</select>
			</td>
		</tr>
		<tr>
			<td>Amount: </td>
			<td><input type="text" name="amount" value="10"><input type="text" name="currency" value="EUR"></td>
		</tr>		
		<tr>
			<td colspan="2"><input type="submit"></td>
		</tr>
		
	</table>
</form>
</body>
</html>
<?php } ?>