<?php

/*
 *	PayPal Express Gateway for CubeCart
 */
 
include("../../../includes/ini.inc.php");
include("../../../includes/global.inc.php");
require_once("../../../classes/db.inc.php");
$db = new db();
include_once("../../../includes/functions.inc.php");
$config = fetchDbConfig("config");
include_once("../../../includes/sslSwitch.inc.php");
include_once("../../../includes/session.inc.php");
include_once("../../../language/".$config['defaultLang']."/lang.inc.php");
include("../../../includes/currencyVars.inc.php");
require_once("../../../classes/cart.php");
$cart = new cart();
$basket = $cart->cartContents($ccUserData[0]['basket']);

// set include path for paypal sdk
$includePath = ini_get('include_path');
$pearPath = $glob['rootDir'] . "/pear";
if(!stristr($includePath, $pearPath)) ini_set('include_path',$pearPath . PATH_SEPARATOR . $includePath);

require_once ('Services/PayPal.php');
require_once ('Services/PayPal/Profile/Handler/Array.php');
require_once ('Services/PayPal/Profile/API.php');

// set PayPal log level and directory
require_once('Log.php');

$module = fetchDbConfig("ExpressCheckout");

if($module['debug'])
	define('PAYPAL_LOG_LEVEL', PEAR_LOG_DEBUG);
define('PAYPAL_LOG_DIR', $glob['rootDir'] . "/pear/tmp");

if($_GET['token']){
	//$certFile = $glob['rootDir']. $module['certificate'];
	$certFile = $glob['rootDir']. "/pear/cert_key_pem.txt";
	$certPass = '';
	$apiUsername = $module['username'];
	$apiPassword = $module['password'];
	$subject = '';
	$environment = $module['gateway'] ? "Live" : "Sandbox";

	$handler =& ProfileHandler_Array::getInstance(array(
		'username' => $apiUsername,
	    'certificateFile' => $certFile,
	    'subject' => $subject,
	    'environment' => $environment));

	$profile =& APIProfile::getInstance($apiUsername, $handler);
	$profile->setAPIPassword($apiPassword);

	$caller =& Services_PayPal::getCallerServices($profile);

	if(Services_PayPal::isError($caller))
	{
		//print $caller->getMessage();
		header("Location: ../../../confirmed.php?f=1");
		exit;
	}
	
	$ecd =& Services_PayPal::getType('GetExpressCheckoutDetailsRequestType');
	$ecd->setToken($_GET['token']);
	$response = $caller->GetExpressCheckoutDetails($ecd);

	if(Services_PayPal::isError($response)  || ($response->getAck() != 'Success' && $response->getAck() != 'SuccessWithWarning')) {
		//if(Services_PayPal::isError($response)) {
		//	print $response->getMessage();
		//}
		header("Location: ../../../confirmed.php?f=1");
		exit;
	} else {
		$details = $response->getGetExpressCheckoutDetailsResponseDetails();
		$payerInfo = $details->getPayerInfo();
		$pdt =& Services_PayPal::getType('PaymentDetailsType');

		$currency = $db->select("SELECT currency FROM ".$glob['dbprefix']."CubeCart_sessions WHERE sessId = ".$db->mySQLSafe($_SESSION['ccUser']));

		if($currency == TRUE && $currency[0]['currency'] != ''){
			$currencyID = $db->mySQLSafe($currency[0]['currency']);
		} else {
			$currencyID = $config['defaultCurrency'];
		}

		$orderTotal =& Services_PayPal::getType('BasicAmountType');
		$orderTotal->setval(number_format($basket['grandTotal'], 2));
		$orderTotal->setattr('currencyID', $currencyID);
		$pdt->setOrderTotal($orderTotal);
		
		if(($basket['subTotal'] + $basket['tax'] + $basket['shipCost']) == $basket['grandTotal']) {
			$itemTotal =& Services_PayPal::getType('BasicAmountType');
			$itemTotal->setval(number_format($basket['subTotal'], 2));
			$itemTotal->setattr('currencyID', $currencyID); // USD
			$pdt->setItemTotal($itemTotal);

			$taxTotal =& Services_PayPal::getType('BasicAmountType');
			$taxTotal->setval(number_format($basket['tax'], 2));
			$taxTotal->setattr('currencyID', $currencyID); // USD
			$pdt->setTaxTotal($taxTotal);

			$shippingTotal =& Services_PayPal::getType('BasicAmountType');
			$shippingTotal->setval(number_format($basket['shipCost'], 2));
			$shippingTotal->setattr('currencyID', $currencyID); // USD
			$pdt->setShippingTotal($shippingTotal);
		}
		
		$pdt->setInvoiceID($basket['cart_order_id']);
		
		$details =& Services_PayPal::getType('DoExpressCheckoutPaymentRequestDetailsType');
		$details->setPaymentAction('Sale');
		$details->setToken($_GET['token']);
		$details->setPayerID($payerInfo->getPayerID());
		$details->setPaymentDetails($pdt);

		$ecprt =& Services_PayPal::getType('DoExpressCheckoutPaymentRequestType');
		$ecprt->setDoExpressCheckoutPaymentRequestDetails($details);

		$response = $caller->DoExpressCheckoutPayment($ecprt);

		if(Services_PayPal::isError($response)  || ($response->getAck() != 'Success' && $response->getAck() != 'SuccessWithWarning')) {
			//if(Services_PayPal::isError($response)) {
			//	print $response->getMessage();
			//}
			header("Location: ../../../confirmed.php?f=1");
			exit;
		} else {
			$details = $response->getDoExpressCheckoutPaymentResponseDetails();
			$paymentInfo = $details->getPaymentInfo();
			$paymentStatus = $paymentInfo->getPaymentStatus();

			switch ($paymentStatus) {
				case 'Completed':
				case 'Pending':
					header("Location: ../../../confirmed.php");
					exit;
				default:
					header("Location: ../../../confirmed.php?f=1");
					exit;
			}
		}
	}
}
?>
