<?php

/********************************************
ReviewRTOrder.php

This file is called after the user clicks on a button during
the checkout process to use PayPal's Express Checkout. The
user logs in to their PayPal account.

This file is called twice.

On the first pass, the code executes the if statement:

if (! isset ($token))

The code collects transaction parameters from the form
displayed by SetExpressCheckout.html then constructs and
sends a SetExpressCheckout request string to the PayPal
server. The paymentType variable becomes the PAYMENTACTION
parameter of the request string. The RETURNURL parameter
is set to this file; this is how ReviewOrder.php is called
twice.

On the second pass, the code executes the else statement.

On the first pass, the buyer completed the authorization in
their PayPal account; now the code gets the payer details
by sending a GetExpressCheckoutDetails request to the PayPal
server. Then the code calls GetExpressCheckoutDetails.php.

Note: Be sure to check the value of PAYPAL_URL. The buyer is
sent to this URL to authorize payment with their PayPal
account. For testing purposes, this should be set to the
PayPal sandbox.

Called by SetExpressCheckout.html.

Calls GetExpressCheckoutDetails.php, CallerServicert.php,
and APIError.php.

********************************************/

require_once 'CallerServicert.php';
require_once 'constants.php';

session_start();


$API_UserName=API_USERNAME;

$API_Password=API_PASSWORD;

$API_Signature=API_SIGNATURE;

$API_Endpoint =API_ENDPOINT;

$subject = SUBJECT;

/* An express checkout transaction starts with a token, that
   identifies to PayPal your transaction
   In this example, when the script sees a token, the script
   knows that the buyer has already authorized payment through
   paypal.  If no token was found, the action is to send the buyer
   to PayPal to first authorize payment
   */

$token = $_REQUEST['token'];

$getAuthModeFromConstantFile = true;
//$getAuthModeFromConstantFile = false;
$nvpHeader = "";

if(!$getAuthModeFromConstantFile) {
	//$AuthMode = "3TOKEN"; //Merchant's API 3-TOKEN Credential is required to make API Call. This is the sample set up
	//$AuthMode = "FIRSTPARTY"; //Only merchant Email is required to make EC Calls.
	$AuthMode = "THIRDPARTY"; //Partner's API Credential and Merchant Email as Subject are required.
} else {
	if(!empty($API_UserName) && !empty($API_Password) && !empty($API_Signature) && !empty($subject)) {
		$AuthMode = "THIRDPARTY";
	}else if(!empty($API_UserName) && !empty($API_Password) && !empty($API_Signature)) {
		$AuthMode = "3TOKEN";
	}else if(!empty($subject)) {
		$AuthMode = "FIRSTPARTY";
	}
	
}
switch($AuthMode) {
	
	case "3TOKEN" : 
			//This is the sample set up
			$nvpHeader = "&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature);
			break;
	case "FIRSTPARTY" :
			$nvpHeader = "&SUBJECT=".urlencode($subject);
			break;
	case "THIRDPARTY" :
			$nvpHeader = "&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature)."&SUBJECT=".urlencode($subject);
			break;		
	
}

if(! isset($token)) {

		/* The servername and serverport tells PayPal where the buyer
		   should be directed back to after authorizing payment.
		   In this case, its the local webserver that is running this script
		   Using the servername and serverport, the return URL is the first
		   portion of the URL that buyers will return to after authorizing payment
		   */
		   $serverName = $_SERVER['SERVER_NAME'];
		   $serverPort = $_SERVER['SERVER_PORT'];
		   $url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
		   //$urlReturn=dirname('http://'.$serverName.$_SERVER['REQUEST_URI']);
		   $urlReturn=dirname('https://'.$serverName.$_SERVER['REQUEST_URI']);
		   
		   $currencyCodeType=$_REQUEST['currencyCodeType'];
		   $billingType=$_REQUEST['billingType'];
		   $description=$_REQUEST['description'];
		   
		   //add reference number - KC
		   $custom = $_REQUEST['custom'];

		 /* The returnURL is the location where buyers return when a
			payment has been succesfully authorized.
			The cancelURL is the location buyers are sent to when they hit the
			cancel button during authorization of payment during the PayPal flow
			*/

		   $returnURL =urlencode($urlReturn.'/ReviewRTOrder.php?currencyCodeType='.$currencyCodeType.'&billingType='.$billingType."&CUSTOM=".$custom);
		   $cancelURL =urlencode("$url/SetBillingAgreement.php?billingType=$billingType" );
			
		 /* Construct the parameter string that describes the PayPal payment
			the varialbes were set in the web form, and the resulting string
			is stored in $nvpstr
			*/

           $nvpstr="";


           //$nvpstr="&PAYMENTTYPE=Any&ReturnUrl=".$returnURL."&BILLINGAGREEMENTDESCRIPTION=".$description."&CANCELURL=".$cancelURL."&CURRENCYCODE=".$currencyCodeType."&BILLINGTYPE=".$billingType;
		   $nvpstr="&PAYMENTTYPE=Any&ReturnUrl=".$returnURL."&BILLINGAGREEMENTDESCRIPTION=".urlencode($description)."&CANCELURL=".$cancelURL."&CURRENCYCODE=".urlencode($currencyCodeType)."&BILLINGTYPE=".urlencode($billingType)."&PAYFLOWCOLOR=000000&BRANDNAME=RBA&HDRIMG=".urlencode("https://www.dbfactory2.co.uk/secure/howyourbodyworks/logo.jpg");

           $nvpstr = $nvpHeader.$nvpstr;

		 	/* Make the call to PayPal to set the Express Checkout token
			If the API call succeded, then redirect the buyer to PayPal
			to begin to authorize payment.  If an error occured, show the
			resulting errors
			*/
  			
		   $resArray=hash_call("SetCustomerBillingAgreement",$nvpstr);
		   $_SESSION['reshash']=$resArray;
		   $ack = strtoupper($resArray["ACK"]);
			
		   if($ack=="SUCCESS"){
					// Redirect to paypal.com here
					$token = urldecode($resArray["TOKEN"]);
					$payPalURL = PAYPAL_URL.$token;
					header("Location: ".$payPalURL);
				  } else  {
					 //Redirecting to APIError.php to display errors.
						$location = "APIError.php";
						header("Location: $location");
					}
} else {
		 /* At this point, the buyer has completed in authorizing payment
			at PayPal.  The script will now call PayPal with the details
			of the authorization, incuding any shipping information of the
			buyer.  Remember, the authorization is not a completed transaction
			at this state - the buyer still needs an additional step to finalize
			the transaction
			*/

		   $token =urlencode( $_REQUEST['token']);

		 /* Build a second API request to PayPal, using the token as the
			ID to get the details on the payment authorization
			*/
		   $nvpstr="&TOKEN=".$token;
			
		   $nvpstr = $nvpHeader.$nvpstr;
		 /* Make the API call and store the results in an array.  If the
			call was a success, show the authorization details, and provide
			an action to complete the payment.  If failed, show the error
			*/
		   $resArray=hash_call("GetBillingAgreementCustomerDetails",$nvpstr);
		   $_SESSION['reshash']=$resArray;
		   $ack = strtoupper($resArray["ACK"]);

		   if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING'){
					//require_once "GetBillingAgreementCustomerDetails.php";
					session_start();

					/* Collect the necessary information to complete the
					   authorization for the PayPal payment
					   */
					
					$_SESSION['token']=$_REQUEST['token'];
					$_SESSION['payer_id'] = $_REQUEST['PayerID'];
					
					$_SESSION['currCodeType']=$_REQUEST['currencyCodeType'];
					$_SESSION['billingType']=$_REQUEST['billingType'];
					
					$resArray=$_SESSION['reshash'];
					
					/* Display the  API response back to the browser .
					   If the response from PayPal was a success, display the response parameters
					   */
					$custom2 = $_GET["CUSTOM"];
					?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Your Subscription: Order Confirmation</title>
<link href="./css/main.css" rel="stylesheet" type="text/css" />
<link href="./css/default.css" rel="stylesheet" type="text/css" />
<link href="./css/bootstrap.css" rel="stylesheet" />
<link href="./css/checkboxs.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="./javascript/generic.js"></script>
<script language="javascript" type="text/javascript" src="./javascript/date.js"></script>
<script language="javascript" type="text/javascript" src="./javascript/validations.js"></script>
<script language="javascript" type="text/javascript" src="./javascript/jquery.icheck.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
                                <body>

<script type="text/javascript" src="javascript/wz_tooltip.js"></script> <!-- this loads the tooltip plugin -->
<div id="wrapper">
		<div id="banner" align="center">
		  <table width="100%" border="0">
		    <tr>
		      <td width="15%" align="center"><img src="images/logoNational.png" alt="National Geographic" /></td>
		      <td width="70%" align="center"><img src="images/top_banner.gif" alt="Precious Rocks and Minerals collection" /></td>
		      <td width="15%">&nbsp;</td>
	        </tr>
	      </table>
    </div>
		
    
    <!-- this is the FAQ bit -->
    <table width="300" border="0" align="center">
    <tr>      </tr>
    </table>
    <div id="content">
<div id="bar">
        			<h2>SECURE ONLINE ORDER FORM</h2>           
                    </div>
<!-- START bmbPageContent -->
<div id="bmbPageOutterContent">
<div id="bmbConfirmationPageContent">

        
        
        
        
        
        
      <div class="container-fluid" style="padding:0;">
    	<div class="areaone col-lg-12"> 
             <div class="col-lg-2"></div>
          <div class="col-lg-8">

<!-- stuff goes here -->
<div class="col-lg-12">
<div class="area2"> 
                   <p style="font-size:x-large">Almost done - please confirm that you wish to set up your billing agreement and complete the PayPal signup by clicking the button below.</p><br /><br />
                                
 </div>                                      <br class="clear" />
              </div>
                     <div class="col-lg-12">
                <div class="area2">
				<form action="CreateBillingAgreement.php?CUSTOM=<?php echo($custom2); ?>" method="POST">
                                                         
                                                                                                                             
                                        <p>
																<?php 
                                                            foreach($resArray as $key => $value) {
                                                                
                                                                if ($key == "EMAIL")
                                                                    {
                                                                    $billingID = $value;
                                                                    echo "Email Address: $value<br />";
                                                                    }  
																if ($key == "PAYERID")
                                                                    {
                                                                    $billingID = $value;
                                                                    echo "Payer ID: $value<br />";
                                                                    } 
																if ($key == "FIRSTNAME")
                                                                    {
                                                                    $billingID = $value;
                                                                    echo "Firstname: $value<br />";
                                                                    }	
																if ($key == "LASTNAME")
                                                                    {
                                                                    $billingID = $value;
                                                                    echo "Lastname: $value<br />";
                                                                    }	
                                                                }	
																
																
                                                                ?>
                                                              
                                  </p>
                                                           <br />
                                                           <br />
                                                           <input type="submit" value="Confirm PayPal Signup" />
            </form>
                                                      <br class="clear" />
                  <!--area5-->
                </div>
                <br class="clear" />
              </div>                               
                                                    
                                                       </div>
                                 <div class="col-lg-2"></div>   
                                </div>
                                </div>  </div>       






<div id="footer">
	<a> This site is provided by </a><a href="http://www.dbfactory.co.uk">Data Base Factory Ltd</a><a> on behalf of </a>RBA Coleccionables S.A.
	<br />
	<a> If you have any problems ordering please call 0345 155 6396 for assistance.</a>
	<br />
	<a> This site is protected by Thawte using 256bit encryption for your security.</a>
	<br />
	<br />
	<!-- this is the Thawte site seal -->
	<table width="10" border="0" cellspacing="0" align="center">
 <tr>
  <td>
   <script src="https://siteseal.thawte.com/cgi/server/thawte_seal_generator.exe"></script>
  </td>
 </tr>
 <tr>
  <td height="0" align="center">
   <a style="color:#AD0034" target="_new"
   href="http://www.thawte.com/digital-certificates/">
   <span style="font-family:arial; font-size:8px; color:#AD0034">
   ABOUT SSL CERTIFICATES</span>
   </a>
  </td>
 </tr>
</table>
<!-- this is the end of the Thawte site seal code -->
	<br />
	<table align="center" width="100" border="0">
  <tr>
    <th scope="col"><img src="./images/visaLogo.gif" /></th>
    <th scope="col"><img src="./images/mastercardLogo.gif" /></th>
    <th scope="col"><img src="./images/DeltaLogo.gif" /></th>
    <th scope="col"><img src="./images/electronLogo.gif" /></th>	
    <th scope="col"><img src="./images/directdebitLogo2.gif"/></th>
	<th scope="col">&nbsp;</th>
	<th scope="col">&nbsp;</th>
	<th scope="col">&nbsp;</th>
	<th scope="col">&nbsp;</th>
	<th scope="col">&nbsp;</th>

  </tr>
</table>
<!-- this is the end of the Thawte site seal code -->
	<br />
	<a> &copy; 2015</a>
</div>
</div>
</div>
<!-- #22432 added by KC 15012015 -->

</body>
</html>
              <?php
			  } else  {
				//Redirecting to APIError.php to display errors.
				$location = "APIError.php";
				header("Location: $location");
			  }
}
?>