<?php
/**********************************************************
DoExpressCheckoutPayment.php

This functionality is called to complete the payment with
PayPal and display the result to the buyer.

The code constructs and sends the DoExpressCheckoutPayment
request string to the PayPal server.

Called by GetExpressCheckoutDetails.php.

Calls 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;

ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);

/* Gather the information to make the final call to
   finalize the PayPal payment.  The variable nvpstr
   holds the name value pairs
   */
$token =urlencode( $_SESSION['token']);
$billingType = urlencode($_SESSION['billingType']);
$currCodeType = urlencode($_SESSION['currCodeType']);
$payerID = urlencode($_SESSION['payer_id']);
$serverName = urlencode($_SERVER['SERVER_NAME']);
$custom = $_REQUEST['custom'];

$nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$billingType.'&CURRENCYCODE='.$currCodeType.'&LOCALECODE='.IE.'&IPADDRESS='.$serverName ;

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

if(!$getAuthModeFromConstantFile) {
	//$AuthMode = "3TOKEN"; //Merchant's API 3-TOKEN Credential is required to make API Call.
	//$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" : 
			$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;		
	
}

$nvpstr = $nvpHeader.$nvpstr;

 /* Make the call to PayPal to finalize payment
    If an error occured, show the resulting errors
    */
$resArray=hash_call("CreateBillingAgreement",$nvpstr);

/* Display the API response back to the browser.
   If the response from PayPal was a success, display the response parameters'
   If the response was an error, display the errors received using APIError.php.
   */
$ack = strtoupper($resArray["ACK"]);


if($ack != 'SUCCESS' && $ack != 'SUCCESSWITHWARNING'){
	$_SESSION['reshash']=$resArray;
	$location = "APIError.php";
		 header("Location: $location");
               }

?>
<!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: Step 1 of 2</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 src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<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>
</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="col-lg-2"></div>
    </div>
    
    
    
    
    
     <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="area2"> 
                                <p style="color:#000">All done! PayPal will send you an email to confirm your PayPal set up which details your billing agreement number. <br />
                                  <br />Please keep this for your reference when contacting customer services.<br /><br />

                                     
	        	<?php 
    		foreach($resArray as $key => $value) {
    			
				if ($key == "BILLINGAGREEMENTID")
					{
					$billingID = $value;
					echo "Billing Agreement ID: $value";
					}    			
    			}	
       			?>
    	
                               </p>
                               
                            <form action="http://www.preciousrockscollection.co.uk" />
<input align="middle" type="submit" value="Return to website" />
</form>    
                                
                                
   </div>
             <table width="100%" height="250px">
               <tr>
                 <td>&nbsp;</td>
               </tr>
             </table>
          </div>
                                 <div class="col-lg-2"></div>   
                                </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>
    <br />
    <a> &copy; 2015</a> </div>
</div>
</body>
</html>
                                
                                
<!-- update code for matching the orderID into the database and inserting the billingID -->
<?php
$custom3 = $_GET["CUSTOM"];

//new SQL ODBC connection
//$odbc = odbc_connect ('WEBSUBS-SQL', 'websubs2', 'dbf_2010') or die('Could not connect to database - please refresh this page to submit order again.');

$db = 'C:\\database\\websubs.mdb';

//RBA still use old local access tables o_O!
$odbc = odbc_connect ('WEBSUBS', 'root', '') or die('Could Not Connect to ODBC Database!');


$sql = "
UPDATE tblSubscriptions SET txtCardNumber = '$billingID' WHERE intSubscriptionId = $custom3";
$query = odbc_exec($odbc, $sql) or die (odbc_errormsg());
$row = odbc_fetch_array($query);
odbc_close($odbc);


//Prepare and send email
$sql1 = "
SELECT selTitle,txtForename,txtSurname,txtEmail FROM tblSubscriptions WHERE ((txtCardNumber = '$billingID') AND (intSubscriptionId = $custom3))";
$query1 = odbc_exec($odbc, $sql1) or die (odbc_errormsg());
$row1 = odbc_fetch_array($query1);
$selTitle = $row1['selTitle'];
$txtForename = $row1['txtForename'];
$txtSurname = $row1['txtSurname'];
$txtEmail = $row1['txtEmail'];
odbc_close($odbc);

$to      = "$txtEmail";
$subject = 'Thank You For Your Order - PayPal confirmation';
$message = "
Dear $selTitle $txtForename $txtSurname,

Thank you for completing your PayPal set up to Precious Rocks and Minerals collection.

This is to confirm that your billing ID is $billingID.

If you have any queries please call 0345 155 6396 or email minerals@dbfactory.co.uk
 

Kind regards

RBA Coleccionables S.A";

$headers = 'From: donotreply@dbfactory2.co.uk' . "\r\n" .
    'Reply-To: donotreply@dbfactory2.co.uk' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

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

echo("<!-- message for email = $txtEmail -->");
echo("<!-- message for email = $message -->");

?>   