<?php
$returnURL = $_SERVER["HTTP_REFERER"];
header("Refresh: 15; URL=$returnURL");

$message="";

include 'PhpApiSettings.php';
include 'Utilities.php';
include 'Json.php';


//call a function of Utilities.php to generate oAuth token 
//This sample code doesn't use any 0Auth Library

$oauth_result = oAuthTokenGenerator();

//call a function of Utilities.php to verify if there is any error with OAuth token. 
$oauth_moveforward = isFoundOAuthTokenError($oauth_result);

//If IsFoundOAuthTokenError results True, means no error 
//next is to move forward for the actual request 

$thankyou_fontcolor = "#000000";

if(!$oauth_moveforward){
    //Decode the Raw Json response.
    $json = jsonDecode($oauth_result['temp_json_response']); 
    
    //set Authentication value based on the successful oAuth response.
    //Add a space between 'Bearer' and access _token 
    $oauth_token = sprintf("Bearer %s",$json['access_token']);
 
    // Build the transaction 
    buildTransaction($oauth_token);  
    
}
//end of main script


function buildTransaction($oauth_token){
    // Build the request data
    $request_data = buildRequestData();
    
    //call to make the actual request
    $result = processTransaction($oauth_token,$request_data, URL_KEYED_SALE );
    
    /*echo "<br>json_response : " . $result['json_response'];
    echo "<BR>curl_error : ".$result['curl_error'];
    echo "<br>http_status_code :".  $result['http_status_code'];
    */
    //check the result
    $status = verifyTransactionResult($result);
	
	notification($status);
}


function buildRequestData(){
   //you can assign the values from any input source fields instead of hard coded values.
   //you can assign the values from any input source fields instead of hard coded values.

	global $message;

	//card info
    $encrypted_number = $_POST['ccNumber'];
    $encrypted_csc =$_POST['ccCSC'] ;
	$encrypted_month =$_POST['ccMonth'] ;
	$encrypted_year =$_POST['ccYear'] ;


	//customer info
	$name = $_POST['name'];
	$email = $_POST['email'];
	$phone = $_POST['phone'];
	$street_address = $_POST['street_address'];
	$city = $_POST['city'];
	$province = $_POST['province'];
	$postal = $_POST['postal'];
	$amount = $_POST['amount'];
	$size = $_POST['size'];

	//billing info
if(isset($_POST['billing'])){
	$billing_street_address = $street_address;
	$billing_city = $city;
	$billing_province = $province;
	$billing_postal = $postal;

}else{
	
	$billing_street_address = $_POST['billing_street_address'];
	$billing_city = $_POST['billing_city'];
	$billing_province = $_POST['billing_province'];
	$billing_postal = $_POST['billing_postal'];

}

	//deliver info
	$delivery_street_address = $_POST['delivery_street_address'];
	$delivery_city = $_POST['delivery_city'];
	$delivery_province = $_POST['delivery_province'];
	$delivery_postal = $_POST['delivery_postal'];
	$wasteType = $_POST['wasteType'];
	$deliveryDate = $_POST['deliveryDate'];


//add all info to the body of email notification

$message = '
<html>
	<body>
		<table rules="all" style="border-color: #666;" cellpadding="10">
			 <tr style="background: #eee;"><td><strong>Name:</strong> </td><td>' . $name . '</td></tr>
			 <tr><td><strong>Email:</strong> </td><td>'. $email . '</td></tr>
 			 <tr><td><strong>Phone:</strong> </td><td>'. $phone . '</td></tr>
 			 <tr><td><strong>Address:</strong> </td><td>' . $street_address.' '.$city.' '.$province.' '.$postal.'</td></tr>
			 <tr><td><strong>Bin Size:</strong> </td><td>' . $size . ' Yard Bin</td></tr>
			 <tr><td><strong>Waste Type:</strong> </td><td>' . $wasteType . '</td></tr>
			 <tr><td><strong>Delivery Date:</strong> </td><td>' . $deliveryDate . '</td></tr>
	 		 <tr><td><strong>Delivery Address:</strong> </td><td>' . $delivery_street_address.' '.$delivery_city.' '.$delivery_province.' '.$delivery_postal. '</td></tr>
			 <tr><td><strong>Billing Address:</strong> </td><td>' . $billing_street_address.' '.$billing_city.' '.$billing_province.' '.$billing_postal. '</td></tr>
			 <tr><td><strong>Total Amount:</strong> </td><td>$' . $amount . '</td></tr>
		</table>
	</body>
</html>
';





/*
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $name . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
$message .= "<tr><td><strong>Phone:</strong> </td><td>" . $phone . "</td></tr>";
$message .= "<tr><td><strong>Address:</strong> </td><td>" . $street_address." ".$city." ".$province." ".$postal."</td></tr>";
$message .= "<tr><td><strong>Waste Type:</strong> </td><td>" . $wasteType . "</td></tr>";
$message .= "<tr><td><strong>Delivery Date:</strong> </td><td>" . $deliveryDate . "</td></tr>";
$message .= "<tr><td><strong>Delivery Address:</strong> </td><td>" . $delivery_street_address." ".$delivery_city." ".$delivery_province." ".$delivery_postal. "</td></tr>";
$message .= "<tr><td><strong>Billing Address:</strong> </td><td>" . $billing_street_address." ".$billing_city." ".$billing_province." ".$billing_postal. "</td></tr>";
$message .= "<tr><td><strong>Total Amount:</strong> </td><td>$" . $amount . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
*/
	
    $request_data = array(
                    "amount" => $amount,
                    "credit_card"=> array (
                         "number"=> $encrypted_number,
                         "expiration_month"=> $encrypted_month,
                         "expiration_year"=> $encrypted_year),
                    "csc"=> $encrypted_csc,
                    "billing_address"=> array(
                        "name"=> $name,
                        "street_address"=> $billing_street_address,
                        "city"=> $billing_city,
                        "state"=> $billing_province,
                        "zip"=> $billing_postal)
                         );
    
    $request_data = json_encode($request_data);
   
    //optional : Display the Jason response - this may be helpful during initial testing.
    //displayRawJsonRequest($request_data);
   
    return $request_data ;  
}

//This function is to verify the Transaction result 
function verifyTransactionResult($trans_result){      

$status = "failed";	

//Handle curl level error, ExitOnCurlError
if($trans_result['curl_error'] ){
    //echo "<br>Error occcured : ";
    //echo '<br>curl error with Transaction request: ' . $trans_result['curl_error'] ;
    exit();  
}

//If we reach here, we have been able to communicate with the service, 
//next is decode the json response and then review Http Status code, response_code and success of the response

$json = jsonDecode($trans_result['temp_json_response']);  

if($trans_result['http_status_code'] != 200){
    if($json['success'] === false){
        //echo "<br><br>Transaction Error occurred : "; 
        
        //Optional : display Http status code and message
        //displayHttpStatus($trans_result['http_status_code']);
        
        //Optional :to display raw json response
        //displayRawJsonResponse($trans_result['temp_json_response']);
       
        //echo "<br>Keyed sale :  failed !";
        //to display individual keys of unsuccessful Transaction Json response
        //displayKeyedTransactionError($json) ;
    }
    else {
        //In case of some other error occurred, next is to just utilize the http code and message.
        //echo "<br><br> Request Error occurred !" ;
        //displayHttpStatus($trans_result['http_status_code']);
    }
}
else
{
    // Optional : to display raw json response - this may be helpful with initial testing.
    //displayRawJsonResponse($trans_result['temp_json_response']);
   
    // Do your code when Response is available and based on the response_code. 
    // Please refer PayTrace-Error page for possible errors and Response Codes
    
    // For transation successfully approved 
    if($json['success']== true && $json['response_code'] == 101){
		$status="success";
        //echo "<br><br>Keyed sale :  Success !";
        //displayHttpStatus($trans_result['http_status_code']);
        //to display individual keys of successful OAuth Json response 
        //displayKeyedTransactionResponse($json);   
   }
   else{
        //Do you code here for any additional verification such as - Avs-response and CSC_response as needed.
        //Please refer PayTrace-Error page for possible errors and Response Codes
        //success = true and response_code == 103 approved but voided because of CSC did not match.
   }
}
    return $status;
}


//This function displays keyed transaction successful response.
function displayKeyedTransactionResponse($json_string){
   
    //optional : Display the output
   
    echo "<br><br> Keyed Sale Response : ";
    //since php interprets boolean value as 1 for true and 0 for false when accessed.
    echo "<br>success : ";
    echo $json_string['success'] ? 'true' : 'false';  
    echo "<br>response_code : ".$json_string['response_code'] ; 
    echo "<br>status_message : ".$json_string['status_message'] ; 
    echo "<br>transaction_id : ".$json_string['transaction_id'] ;  
    echo "<br>approval_code : ".$json_string['approval_code'] ;
    echo "<br>approval_message : ".$json_string['approval_message'] ;
    echo "<br>avs_response : ".$json_string['avs_response'] ;
    echo "<br>csc_response : ".$json_string['csc_response'] ; 
    echo "<br>external_transaction_id: ".$json_string['external_transaction_id'] ;
    echo "<br>masked_card_number : ".$json_string['masked_card_number'] ;       

}


//This function displays keyed transaction error response.
function displayKeyedTransactionError($json_string){
    //optional : Display the output
    echo "<br><br> Keyed Sale Response : ";
    //since php interprets boolean value as 1 for true and 0 for false when accessed.
    echo "<br>success : ";
    echo $json_string['success'] ? 'true' : 'false';  
    echo "<br>response_code : ".$json_string['response_code'] ; 
    echo "<br>status_message : ".$json_string['status_message'] ;  
    echo "<br>external_transaction_id: ".$json_string['external_transaction_id'] ;
    echo "<br>masked_card_number : ".$json_string['masked_card_number'] ;  
   
    //to check the actual API errors and get the individual error keys 
    echo "<br>API Errors : " ;
   
    foreach($json_string['errors'] as $error =>$no_of_errors )
    {
        //Do you code here as an action based on the particular error number 
        //you can access the error key with $error in the loop as shown below.
        echo "<br>". $error;
        // to access the error message in array assosicated with each key.
        foreach($no_of_errors as $item)
        {
           //Optional - error message with each individual error key.
            echo "  " . $item ; 
        } 
    }
    
     
}

function notification($status){

	//session_start();
//$returnURL = $_POST['returnURL'];
error_reporting(E_ERROR);
//error_reporting(0);
ini_set("display_errors", 1);  
//$Submit = $_POST['Submit'];

	global $message;

if($status != "success") {
 echo "<center><font size='+3' color='#ff0000'>Error: Transaction Failed!</font></center><br>";
 $error = 1;

echo "<div style='font-family: arial; font-size: 12px; width:30em; height: 18em; background-color: #e4e4e4; border: solid 2px #cccccc; position: absolute; top: 50%; left: 50%; margin-top: -9em; margin-left: -15em;'><div style='margin-left: 5px; margin-top: 5px;'><h3>".$_SERVER['SERVER_NAME']."</h3>";

echo "<br><br>Re-directing you back in 15 sec...<br>or <a href='javascript:history.go(-1)'><font color='$thankyou_fontcolor'><b>click here to go back now</b></font></a></div>";
 }else{

$hostname = $_SERVER['SERVER_NAME'];
$ip = $_SERVER['REMOTE_ADDR'];

$subject = "New order from ".$_SERVER['SERVER_NAME'];
$sendTo = "carlton@netvatise.com";
$senderemail = "no-reply@netvatise.com";
$headers  = "From: ".$senderemail."\r\n"; 
$headers .= "Content-type: text/html\r\n";

mail($sendTo, $subject, $message, $headers);



//sleep(5);
echo "<div style='font-family: arial; font-size: 12px; width:30em; height: 18em; background-color: #e4e4e4; border: solid 2px #cccccc; position: absolute; top: 50%; left: 50%; margin-top: -9em; margin-left: -15em;'><div style='margin-left: 5px; margin-top: 5px;'><h3>".$_SERVER['SERVER_NAME']."</h3><font color='$thankyou_fontcolor'><b>Thank you.</b><br>Your Transaction has been processed.<br>Re-directing you back in 15 sec...<br><a href='http://temp.netvatise.net/torontobin/order.html'><font color='$thankyou_fontcolor'><b>click here to go back now</b></font></a></font></div></div>";
//echo $_SERVER["HTTP REFERER"];
		
}
}

function console_log( $data ){
  echo '<script>';
  echo 'console.log('. json_encode( $data ) .')';
  echo '</script>';
}

?>