<?php

$title = 'Confirm payment details';
require 'inc_header.php';
?>

	<?php 
try {
    $token = $_GET['token'];
    $status = $_GET['result'];
    $params = array('method' => 'GetExpressCheckoutDetails', 'token' => $token, 'version' => PP_VERSION, 'user' => PP_USER, 'pwd' => PP_PWD, 'signature' => PP_SIGNATURE);
    $response = post_checkout($params);
    $checkoutDetails = parse_url_encoded($response);
    $_SESSION['user']['token'] = $checkoutDetails['TOKEN'];
    $_SESSION['user']['payer_id'] = $checkoutDetails['PAYERID'];
    $_SESSION['user']['amt'] = $checkoutDetails['AMT'];
    $invoice = array('Amount' => $checkoutDetails['AMT'], 'Name' => $checkoutDetails['SHIPTONAME'], 'Street' => $checkoutDetails['SHIPTOSTREET'], 'City' => $checkoutDetails['SHIPTOCITY'], 'State' => $checkoutDetails['SHIPTOSTATE'], 'Postal Code' => $checkoutDetails['SHIPTOZIP'], 'Country' => $checkoutDetails['SHIPTOCOUNTRYNAME']);
    $_SESSION['invoice'] = $invoice;
} catch (Exception $e) {
    $error = $e->getMessage();
}
?>

	<?php 
if (isset($_GET['result']) && $_GET['result'] == 'cancelled') {
    ?>
		<h2>Transaction Cancelled</h2>
		<p>Your transaction has been cancelled.</p>

	<?php 
} elseif (isset($error)) {
require_once 'inc_functions.php';
// if we've chosen a payment type from traditional flow
// OR set a preference for the streamlined flow in Admin
// THEN get the PP Identity Access Token and redirect to PP Express Checkout
if (isset($_POST['paymentType']) || isset($_GET['paymentType']) || isset($_SESSION['fastFlow']) && $_SESSION['fastFlow'] === true) {
    if (verify_nonce()) {
        try {
            $amount = 0.0;
            $cartItems = $_SESSION['cartItems'];
            foreach ($cartItems as $itm) {
                $amount += $storeItems[$itm]['price'];
            }
            $params = array('method' => 'SetExpressCheckout', 'itemamt' => $amount, 'amt' => $amount, 'currencycode' => 'USD', 'paymentaction' => 'Sale', 'returnUrl' => BASE_URL . 'confirm-purchase.php?result=success', 'cancelUrl' => BASE_URL . 'confirm-purchase.php?result=cancelled', 'version' => PP_VERSION, 'user' => PP_USER, 'pwd' => PP_PWD, 'signature' => PP_SIGNATURE, 'IDENTITYACCESSTOKEN' => get_access_token());
            $checkoutResponse = post_checkout($params);
            $parsedCheckoutResponse = parse_url_encoded($checkoutResponse);
            // NOTE: for header() to work properly, there must be NO whitespace, NO echo, etc. before this point
            header('Location:' . PP_CHECKOUT_URL . '&token=' . $parsedCheckoutResponse['TOKEN']);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
    ?>

	<?php 
} else {
    // ...else set the checkout preferences to traditional and present the form:
    ?>
		<?php 
    $_SESSION['fastFlow'] = false;
    ?>