<?php

header("Access-Control-Allow-Origin: *");
$output = array();

//if(filter_input(INPUT_SERVER, 'REMOTE_ADDR') != '193.248.52.224') { die("Wrong credentials"); }

require("../shared/functions.php");

// Var initialize
$amount = '0.40';
$eci = 7;

$card = new stdClass();

$post = new stdClass();
$post->account          = filter_input(INPUT_POST, 'account', FILTER_SANITIZE_STRING);
$post->account_id       = filter_input(INPUT_POST, 'account_id', FILTER_SANITIZE_STRING);
$post->is_sandbox       = filter_input(INPUT_POST, 'is_sandbox', FILTER_SANITIZE_STRING);
$post->payment_product  = filter_input(INPUT_POST, 'payment_product', FILTER_SANITIZE_STRING);
$post->currency         = filter_input(INPUT_POST, 'currency', FILTER_SANITIZE_STRING) ;
$post->authentication_indicator = filter_input(INPUT_POST, 'authentication_indicator', FILTER_SANITIZE_STRING);
$post->hpayment         = filter_input(INPUT_POST, 'hpayment', FILTER_SANITIZE_STRING) ;

$post->secret_key = filter_input(INPUT_POST, 'secret_key', FILTER_SANITIZE_STRING);

// Debug ?
//print_r($post); die("stop");

// Functionnal escape that is repeated in the code
function enrolled($payment_product) {
    closejs(array(
        'error' => "No enrolled Card $payment_product found."
    ));
}

if(isset($post->account) && isset($post->account_id) && isset($post->is_sandbox) && isset($post->payment_product) && isset($post->currency) && isset($post->authentication_indicator)) {
    
    $db = connecti('jabella');
    
    $account    = $db->real_escape_string($post->account);

    if ($db && $account) {
        
        $query = "SELECT user, password FROM tpp_accounts WHERE account = '$account' LIMIT 1;";
        $sql = $db->query($query);

        if(isset($sql->num_rows) && $sql->num_rows > 0) {
            $row = $sql->fetch_object();
            if(isset($row->user) && $row->user != '' && isset($row->password)&& $row->password != '') {

                // Define endpoint
                /*
                 * f : PRODUCTION
                 * t : STAGE
                 */
                if($post->is_sandbox == 'f') {
                    
                    /* 
                     * ================================================================================
                     * PRODUCTION =====================================================================
                     * ================================================================================
                     */
                    define('API_ENDPOINT', 'https://secure-gateway.hipay-tpp.com/rest/v1'); // HiPay TPP production platform
                    define('API_ENDPOINT_VAULT', 'https://secure-vault.hipay-tpp.com/rest/v1');
                    define('ENV', 'prod');
                    
                    // Decryption function
                    function decrypt($encrypted, $password, $salt='mkj6LU3S^Gc?q5f-') {
                        // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
                        $key = hash('SHA256', $salt . $password, true);
                        // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
                        $iv = base64_decode(substr($encrypted, 0, 22) . '==');
                        // Remove $iv from $encrypted.
                        $encrypted = substr($encrypted, 22);
                        // Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
                        $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
                        // Retrieve $hash which is the last 32 characters of $decrypted.
                        $hash = substr($decrypted, -32);
                        // Remove the last 32 characters from $decrypted.
                        $decrypted = substr($decrypted, 0, -32);
                        // Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
                        if (md5($decrypted) != $hash) return false;
                        // Yay!
                        return $decrypted;
                    }
                    //elseif($post->secret_key) { $eci = 7; $card = json_decode(decrypt("", $post->secret_key)); }
                    
                    
                    // Force HPayment ?
                    if(!$post->hpayment) { 
                        // Payment product Prod
                        switch($post->payment_product) {
                            case 'VISA':
                                $payment_product = 'visa';
                                if($post->authentication_indicator == 0) { $eci = 9; $card->token = '70f2c3de5195bb801e14f30428acbee3906f2cd7'; } // Carte Anytime
                                elseif($post->secret_key) { $eci = 7; $card = json_decode(decrypt("UTjfXh5jfNIkgYciRQFc9gxX04FupHFgIy2BEa29JPHn9rhj8Tcq0za7gLfZ10KtDWyfmFxFYQBpFT6kJ2xk/s/CpsDxEoXWObkPCt2S1GnoIxArIfJoab8TGx5CBFTv4wMQiD38MXvsPXvXhHPrk4FnAwTcdK1l8NK5oh9rcA8dDWuTxo3an8lewsNVCEfuI=", $post->secret_key)); } // Carte Transcash Red
                                break;
                            case 'MasterCard':
                                $payment_product = 'mastercard';
                                if($post->authentication_indicator == 0) { $eci = 9; $card->token = 'f4efe363ab79a870f7d3bebd3fb915bc8976c668'; } // Carte PCS
                                elseif($post->secret_key) { $eci = 7; $card = json_decode(decrypt("aaTVRWbGl2ODJVpgDVKivg72F76UWAF/s/rO6jaa2QXzE+OnuHX+4ZbRRm+5SZSeO4mPz9zbCyRBf+GNujSw7AoVH98eZ5GJZQIkxzZbfBa+4Ll3C9KCexqhyrfSc6pdwYswHQRUpbiC7bWdrLbpiuH1TskVtsSL+ofY46HGVC+dQLGe11imN4bi1TILAmM10=", $post->secret_key)); } // Carte PCS
                                break;
                            case 'American Express':
                                $payment_product = 'american-express';
                                if($post->authentication_indicator == 0) { $eci = 9; $card->token = 'a7158c56092f5c1dd2ab96ef542bb3d93422cc14'; }
                                elseif($post->secret_key) { $eci = 7; $card = json_decode(decrypt("AjBfqVuQ0wsKmEnptBGBygf/0OrZ7UAHV8kuB0v7e/hhaQZT9L+QlSDxJYptFHsHQVxEIpzgeUxGAlEkApwqvaP1ZxxyMKezQODhZchT39inOtZaeW66tRPxYbwSDjO7NBC2V3BzAEX180SLYoBr5rBEpVtnZKLkCgi4x2WUcFZPvkKFndPB9j/+bjYWf5tyc=", $post->secret_key)); }
                                break;
                            /* ONEY */
                            case  '3x Carte Bancaire':
                                $payment_product = '3xcb';
                                $use_hpayment = 1;
                                $amount = 200;
                                break;                        
                            case  '4x Carte Bancaire':
                                $payment_product = '4xcb';
                                $use_hpayment = 1;
                                $amount = 500;
                                break;
                            case  '3x Carte Bancaire sans frais':
                                $payment_product = '3xcb-no-fees';
                                $use_hpayment = 1;
                                $amount = 200;
                                break;                        
                            case  '4x Carte Bancaire sans frais':
                                $payment_product = '4xcb-no-fees';
                                $use_hpayment = 1;
                                $amount = 500;
                                break;
                            default:
                                closejs(array('error' => "No payment method found"));
                                break;
                        }
                    }
                    else {
                        // Force HPayment
                        $use_hpayment = 1;
                        $payment_product = '';
                    }
                }
                else {
                    /* 
                     * ================================================================================
                     * STAGE ==========================================================================
                     * ================================================================================
                     */
                    define('API_ENDPOINT', 'https://stage-secure-gateway.hipay-tpp.com/rest/v1'); // HiPay TPP test platform
                    define('API_ENDPOINT_VAULT', 'https://stage-secure-vault.hipay-tpp.com/rest/v1');
                    define('ENV', 'test');
   
                    // Force HPayment ?
                    if(!$post->hpayment) {
                        // Payment product Stage
                        switch($post->payment_product) {
                        
                            /* CARTES */
                            case 'CB':
                            case 'VISA':
                                $payment_product = 'visa';
                                if($post->authentication_indicator == 0) { $eci = 9; $card->token = 'f39bfab2b6c96fa30dcc0e55aa3da4125a49ab03'; /* 411111******1111 */  }
                                else { $eci = 7; $card->token = ''; $card->number = '4000000000000002'; $card->holder = 'Test HiPay'; $card->expmonth = date('m'); $card->expyear = date('Y')+2; $card->cvc = '123'; }
                                break;
                            case 'MasterCard':
                                $payment_product = 'mastercard';
                                if($post->authentication_indicator == 0) { $eci = 9; $card->token = 'c0f72a9583eb781cb28c3a9d8aa9d743e393bec2'; /* 539999******9999 */ }
                                else { $eci = 7; $card->token = ''; $card->number = '5399999999999999'; $card->holder = 'Test HiPay'; $card->expmonth = date('m'); $card->expyear = date('Y')+2; $card->cvc = '123'; }
                                break;
                            case 'American Express':
                                $payment_product = 'american-express';
                                if($post->authentication_indicator == 0) { $eci = 9; $card->token = 'a7ac04b7dc217211ec761221a1a38abec6fdf59f'; /* 373096******8560 */ }
                                else { $eci = 7; $card->token = ''; $card->number = '373096011258560'; $card->holder = 'Test HiPay'; $card->expmonth = date('m'); $card->expyear = date('Y')+2; $card->cvc = '1234'; }
                                break;
                            case 'Bancontact / Mister Cash':
                                $payment_product = 'bcmc';
                                $eci = 7; $card->token = ''; $card->number = '67030000000000003'; $card->holder = 'Test HiPay'; $card->expmonth = date('m'); $card->expyear = date('Y')+2; $card->cvc = '123';
                                break;
                            /* SDD */
                            case 'SEPA Direct Debit':
                                $payment_product = 'sdd';
                                $use_hpayment = 1;
                                break;
                            /* ONEY */
                            case  'Facily Pay 3x Carte Bancaire':
                                $payment_product = '3xcb';
                                $use_hpayment = 1;
                                $amount = 200;
                                break;                        
                            case  'Facily Pay 4x Carte Bancaire':
                                $payment_product = '4xcb';
                                $use_hpayment = 1;
                                $amount = 500;
                                break;
                            case  'Facily Pay 3x Carte Bancaire sans frais':
                                $payment_product = '3xcb-no-fees';
                                $use_hpayment = 1;
                                $amount = 200;
                                break;                        
                            case  'Facily Pay 4x Carte Bancaire sans frais':
                                $payment_product = '4xcb-no-fees';
                                $use_hpayment = 1;
                                $amount = 500;
                                break;
                            case  'Maestro':
                                $payment_product = 'maestro';
                                $use_hpayment = 1;
                                $eci = 9;
                                break;

                            default:
                                closejs(array('error' => "No payment method found"));
                                break;
                        }
                    }
                    else {
                        // Force HPayment
                        $use_hpayment = 1;
                        $payment_product = '';
                    }
                }
                
                // Define credentials
                define('API_USERNAME', $row->user);
                define('API_PASSWORD', $row->password);
                $credentials = API_USERNAME . ':' . API_PASSWORD;
               
               
                // Create query parameters
                if(($post->authentication_indicator == 0 && !isset($use_hpayment)) || isset($card->number)) {

                    if(isset($card->number) && isset($card->holder) && isset($card->expmonth) && isset($card->expyear) && isset($card->cvc)) {
                        // API TOKENIZATION
                        $resource = API_ENDPOINT_VAULT . '/token/create';
                        
                        // Create a new cURL resourse
                        $curl = curl_init();

                        // Set appropiate options
                        $httpheader = array(
                                'Content-Type: application/x-www-form-urlencoded',
                                'Accept: application/json' // 'text/xml'
                        );

                        $queryParameters = array(
                            'card_number' => $card->number,
                            'card_expiry_month' => $card->expmonth,
                            'card_expiry_year' => $card->expyear,
                            'card_holder' => $card->holder,
                            'cvc' => $card->cvc,
                        );

                        $options = array(
                                CURLOPT_URL => $resource,
                                CURLOPT_USERPWD => $credentials,
                                CURLOPT_HTTPHEADER => $httpheader,
                                CURLOPT_RETURNTRANSFER =>true,
                                CURLOPT_FAILONERROR => false,
                                CURLOPT_HEADER =>false,
                                CURLOPT_POST => true,
                                CURLOPT_POSTFIELDS => http_build_query($queryParameters),
                                CURLOPT_SSL_VERIFYPEER  => false,
                        );

                        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));
                                closejs(array(var_dump(curl_error($curl), curl_errno($curl))));
                        }

                        $status = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
                        $response = json_decode($result);

                        if (floor($status/100) != 2) {
                                closejs(array(var_dump($response->message, $response->code)));
                        }
                        curl_close($curl);
                        
                        $card->token = $response->token;
                    }
                    
                    
                    // API ORDER
                    $output['endpoint'] = "ORDER";
                    
                    $resource = API_ENDPOINT . '/order';
                    
                    $queryParameters = array(
                        'orderid'                   => 'HIPAY'.time(),
                        'operation'                 => 'sale', //'authorization',
                        'payment_product'           => $payment_product,
                        
                        'description'               => 'Test Support Hipay',
                        'long_description'          => 'Test Support Hipay',
                        'currency'                  => $post->currency,
                        'amount'                    => $amount,
                        'shipping'                  => '0.00',
                        'tax'                       => '0.01',
                        'cid'                       => 'user_0000001',
                        'ipaddr'                    => '127.0.0.0',
                        'email'                     => 'demo@hipay.com',
                        'firstname'                 => 'Support',
                        'lastname'                  => 'HIPAY',
                        'birthdate'                 => '19810225',
                        'gender'                    => 'M',
                        'streetaddress'             => '6 place du colonel Bourgoin',
                        'streetaddress2'            => 'Business IT Services',
                        'city'                      => 'Paris',
                        'zipcode'                   => '75012',
                        'country'                   => 'US',
                        'shipto_firstname'          => 'Support',
                        'shipto_lastname'           => 'HIPAY',
                        'shipto_streetaddress'      => '6 place du colonel Bourgoin',
                        'shipto_streetaddress2'     => 'Service Stocks',
                        'shipto_city'               => 'Paris',
                        'shipto_zipcode'            => '75012',
                        'shipto_country'            => 'US',
                        
                        'eci'                       => $eci,
                        'authentication_indicator'  => $post->authentication_indicator,
                        
                        'cardtoken'                 => $card->token,
                        
                        'accept_url'                => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-accept',
                        'decline_url'               => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-decline',
                        'pending_url'               => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-pending',
                        'exception_url'             => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-exception',
                        'cancel_url'                => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-cancel',
                        
                        'custom_data'               => json_encode(array('key 1' => 'value 1', 'key 2' => 'value 2',)),
                        'cdata1'                    => 'test cdata1',
                        'cdata2'                    => 'test cdata2',
                        'cdata9'                    => $post->account_id,
                    );
                    
                    $header = array(
                        'Accept: application/json',
                    );
                }
                else {
                    // API HPAYMENT SI 3DS
                    $output['endpoint'] = "HPAYMENT";
                    
                    $resource = API_ENDPOINT . '/hpayment';
                    
                    $queryParameters = array(
                        'orderid'                   => 'HIPAY'.time(),
                        'operation'                 => 'sale', //'authorization',
                        'payment_product_list'      => $payment_product,
                        'description'               => 'Test Support Hipay',
                        'long_description'          => 'Test Support Hipay',
                        'currency'                  => $post->currency,
                        'amount'                    => $amount,
                        'shipping'                  => '0.00',
                        'tax'                       => '0.01',
                        'cid'                       => 'user_0000001',
                        'ipaddr'                    => '127.0.0.0',
                        'email'                     => 'demo@hipay.com',
                        'firstname'                 => 'Support',
                        'lastname'                  => 'HIPAY',
                        'birthdate'                 => '19810225',
                        'gender'                    => 'M',
                        'streetaddress'             => '6 place du colonel Bourgoin',
                        'streetaddress2'            => 'Business IT Services',
                        'city'                      => 'Paris',
                        'zipcode'                   => '75012',
                        'country'                   => 'FR',
                        'shipto_firstname'          => 'Support',
                        'shipto_lastname'           => 'HIPAY',
                        'shipto_streetaddress'      => '6 place du colonel Bourgoin',
                        'shipto_streetaddress2'     => 'Service Stocks',
                        'shipto_city'               => 'Paris',
                        'shipto_zipcode'            => '75012',
                        'shipto_country'            => 'FR',

                        'eci'                       => $eci,
                        
                        'authentication_indicator'  => $post->authentication_indicator,
                        'multi_use'                 => '1',
                        
                        'merchant_display_name'     => substr('TEST HIPAY '.$payment_product.' - '.$post->account, 0, 32),
                        'template'                  => 'basic-js',
                        'language'                  => 'en_GB',
                        //'display_selector'        => '0',

                        'accept_url'                => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-accept',
                        'decline_url'               => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-decline',
                        'pending_url'               => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-pending',
                        'exception_url'             => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-exception',
                        'cancel_url'                => 'https://merchant.hipay-tpp.com/maccount/'.$post->account_id.'/account/payment-method/contracts#page-cancel',
                        
                        'custom_data'               => json_encode(array('key 1' => 'value 1', 'key 2' => 'value 2',)),
                        'cdata1'                    => 'test cdata1',
                        'cdata2'                    => 'test cdata2',
                        'cdata9'                    => $post->account_id,
                    ); 
                    
                    $header = array(
                        'User-Agent: ' . filter_input(INPUT_SERVER, 'HTTP_USER_AGENT'),
                        'Accept: application/json',
                        'Accept-Language: ' . filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE'),
                        //'Accept-Charset:' .  filter_input(INPUT_SERVER, 'HTTP_ACCEPT_CHARSET'),
                    );
                    
                    
                }
                
                // Create a new cURL resourse
                $curl = curl_init();

                // Create cURL options array
                $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)
                );

                foreach ($options as $option => $value) {
                        curl_setopt($curl, $option, $value);
                }

                // Execute the given cURL session
                if (false === ($result = curl_exec($curl))) {
                    $output['options'] = $options;    
                    $output['error'] = var_export(curl_error($curl), true);
                    closejs($output);
                }

                // Clean the answer 
                $status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
                $response = json_decode($result);
                $output['response'] = $response;

                if (floor($status/100) != 2) {
                    $output['error'] = var_export(curl_error($curl), true);
                    closejs($output);
                }

                // Close cURL
                curl_close($curl);

                // Store Transaction information
                if(!@$response->status) {
                    $response->status = 150;
                }
                
                // Do not store Error transactions
                if($response->status != 110 || $response->status != 113) {
                    $query_ins = "INSERT INTO tpp_transactions SET "
                        . "is_sandbox = '".$post->is_sandbox."', "
                        . "account = '$account', "
                        . "payment_product = '$payment_product', "
                        . "order_id = '".$response->order->id."', "
                        . "status = '".$response->status."', "
                        . "log = '".$db->real_escape_string($result)."'";

                    if(@$response->transactionReference) {
                        $query_ins .= ", transaction_id = '".$response->transactionReference."'";
                    }

                    $sql = $db->query($query_ins);
                }
                
                // Get payment page URL
                if(isset($response->forwardUrl) && $response->forwardUrl != '' && strlen($response->forwardUrl) > 0) {
                    $url = $response->forwardUrl;

                    // Redirect customer to payment page
                    //header('Location: ' . $url);
                    $output['forward'] = $url;
                }
                
                // END
                closejs($output);
            }

        }
        else {
            $output['error'] = "Merchant ".$post->account." not found, please create or update credentials first !";
            closejs($output);
        }
        
        $db->close();
    }
}

?>