<?php
// 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

require_once 'functions.php';
$db = connecti();
$accounts = '';
if ($db) {
	$query = "SELECT * FROM `tpp_accounts` WHERE `id` = '".$_REQUEST['account']."' ORDER BY `account` ASC " ;
	$result = $db->query($query);
	$row = $result->fetch_array(MYSQLI_ASSOC);
	define('API_USERNAME', $row['user']);
	define('API_PASSWORD', $row['password']);
	
}

$credentials = API_USERNAME . ':' . API_PASSWORD;
$resource = API_ENDPOINT . '/hpayment';

if(!empty($row['merchant'])) {
	$merchant = $row['merchant'];
}
else {
	$merchant = $row['account'];
}

echo "<br/>" . $resource  . "<br/><u>User: </u>" . API_USERNAME . '<br/><u>Password: </u>' . API_PASSWORD;


/*
//$_username = '145.api.allopass.com';
//$_password = '8dqfp5AM53KMnlozVTW81atK';
$url = 'http://tanthoine.secure-gateway.allopass.dev/rest/v1/hpayment';

// overload with preprod parameters (65492 ALLOPASS PROD)
if (isset($_GET['env']) && $_GET['env'] == 'preprod') {
    $url = 'http://preprod-secure-gateway.allopass.com/rest/v1/hpayment';
    $_username = '94651723.29072013.api.allopass.preprod';
    $_password = 'b39Yr3tGEGm2WfPhvFoSNRG3';
}
*/

if (isset($_REQUEST['ai'])) {
	$ai = $_REQUEST['ai'];
}
else {
	$ai = 0;
}

if (isset($_REQUEST['lang'])) {
	$lang = $_REQUEST['lang'];
}
else {
	$lang = 'en_EN';
}

if (isset($_REQUEST['merchant'])) {
	$merchant = $_REQUEST['merchant'];
}

if (isset($_REQUEST['currency'])) {
	$currency = $_REQUEST['currency'];
}
else $currency = "EUR";

if (isset($_REQUEST['amount'])) {
	$amount = $_REQUEST['amount'];
}
else $amount = "10.00";

if (isset($_REQUEST['template'])) {
	$template = $_REQUEST['template'];
}
else $template = "basic2";


$uid = time();

echo "<br/>Route CSS: " . 'https://sd-20614.dedibox.fr/~jabella/fullservice/css/' . $_REQUEST['account'] . '.css';


if (file_exists('/home/jabella/public_html/fullservice/css/' . $_REQUEST['account'] . '.css')) {
	$css = 'https://sd-20614.dedibox.fr/~jabella/fullservice/css/' . $_REQUEST['account'] . '.css';
	echo " -- EXISTS";
	}
else {
	$css = '';
	echo " -- NOT EXSISTS";
	}


//$css = 'https://sd-20614.dedibox.fr/~jabella/fullservice/css/' . $_REQUEST['account'] . '.css';


if($_REQUEST['account'] == '59')
 $css = 'https://fb.sevenlike.com/franklinandmarshall/hipay.css?18';


$queryParameters = array(
            'orderid'                  => $uid,
            'operation'                => 'Authorization',
            'payment_product'          => 'cb',
            'description'              => 'Certification Allopass',
            'amount'                   => $amount,
//            'shipping'                 => '0.00',
//            'tax'                      => '0.00',
            'currency'                 => $currency,
//            'eci'                      => '7',
//            'ipaddr'                   => '149.5.217.122', // US
            'language'                 => $lang,
//            //'cardtoken'                => 'ce5f096fa6bc05989c170e7c96f94432660491bd', // TEST OGONE
            'email'                    => 'support_it@allopass.com',
//            'phone'                    => '02941429397',
            'cid'                      => '51792e6256b5d',
            'authentication_indicator' => $ai,
//            'uid'                      => $uid,
//            'accept_url' => 'http://sd-20614.dedibox.fr/~jabella/fullservice/notif.php?page=accept',
//		    'decline_url' => 'http://sd-20614.dedibox.fr/~jabella/fullservice/notif.php?page=decline',
//		    'exception_url' => 'http://sd-20614.dedibox.fr/~jabella/fullservice/notif.php?page=exception',
//		    'cancel_url' => 'http://sd-20614.dedibox.fr/~jabella/fullservice/notif.php?page=cancel',
		    
	    //'configuration'	       => array(
	      'payment_product_list' => 'mastercard,visa,maestro,american-express, bcmc',
		  'payment_product_category_list' => 'credit-card',
	      // [css : bootstrap]
	      //'css' => '//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css',
	      // [css : iframe]
	      //'css' => 'https://preprod-secure-gateway.allopass.com/css/client/client2.css',
	      // [css : basic]
	      //'css' => 'http://preprod-secure-gateway.allopass.com/css/client/client.css',
	      //'css' => 'https://sd-20614.dedibox.fr/~jabella/fullservice/css/' . $_REQUEST['account'] . '.css',
	      'css' => $css,
	      // [template : iframe / basic / basic2]
	      'template' => $template,
	      'merchant_display_name' => $merchant,
//	      'display_selector' => 0,
		//			  ),
	    //'profile_publicref'	       => ''   // '123456'
        );


// 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>";



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;
