<?php

/*
 *	PayPal Direct Payment Gateway for CubeCart
 */

if($_GET['process']==1){
	// 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);

	// set PayPal log level and directory
	require_once('Log.php');
	
	if($module['debug'])
	
	define('PAYPAL_LOG_LEVEL', PEAR_LOG_DEBUG);
	define('PAYPAL_LOG_DIR', $glob['rootDir'] . "/pear/tmp");

	$firstName	 = $_POST["firstName"];
	$lastName	 = $_POST["lastName"];
	$orderAmount = $_POST["order_total"];
	$itemAmount	 = $_POST["item_total"];
	$taxAmount	 = $_POST["tax_total"];
	$shippingAmount	= $_POST["shipping_total"];
	$currencyID		= $_POST["currency_id"];
	$cardType	 = $_POST["cardType"];
	$cardNumber	 = $_POST["cardNumber"];
	$expirationMonth = $_POST["expirationMonth"];
	$expirationYear	 = $_POST["expirationYear"];
	$cvc2		 = $_POST["cvc2"];
	$emailAddress 	 = $_POST["emailAddress"];
	$addr1 		 = $_POST["addr1"];
	$addr2 		 = $_POST["addr2"];
	$city 		 = $_POST["city"];
	$st 		 = $_POST["state"];
	$country 	 = $_POST["country"];
	$postalCode 	 = $_POST["postalCode"];
	$orderID 	 = $_POST["cart_order_id"];
	//$billingOption	 = $CONFIG["CUBECART_BILLING_OPTION"];
	//$productName	 = $CONFIG["CUBECART_PRODUCT_NAME"];
	
	require_once ('Services/PayPal.php');
	require_once ('Services/PayPal/Profile/Handler/Array.php');
	require_once ('Services/PayPal/Profile/API.php');

	//$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;
	}

	$name =& Services_PayPal::getType('PersonNameType');
	$name->setFirstName($firstName);
	$name->setLastName($lastName);

	$address =& Services_PayPal::getType('AddressType');
	$address->setStreet1($addr1);
	$address->setStreet2($addr2);
	$address->setCityName($city);
	$address->setStateOrProvince($st);
	$address->setCountry($country);
	$address->setPostalCode($postalCode);

	$payer =& Services_PayPal::getType('PayerInfoType');
	$payer->setPayer($emailAddress);
	//$payer->setPayerID($order->customer['email_address']);
	//$payer->setPayerStatus('verified');
	$payer->setPayerName($name);
	$payer->setPayerCountry($country);
	$payer->setAddress($address);

	$cc =& Services_PayPal::getType('CreditCardDetailsType');
	$cc->setCreditCardType($cardType);
	$cc->setCreditCardNumber($cardNumber);
	$cc->setExpMonth($expirationMonth);
	$cc->setExpYear($expirationYear);
	$cc->setCVV2($cvc2);
	$cc->setCardOwner($payer);
	
	$pdt =& Services_PayPal::getType('PaymentDetailsType');
	$orderTotal =& Services_PayPal::getType('BasicAmountType');
	$orderTotal->setval(number_format($orderAmount, 2));
	$orderTotal->setattr('currencyID', $currencyID); // USD
	$pdt->setOrderTotal($orderTotal);
	
	if(($itemAmount + $taxAmount + $shippingAmount) == $orderAmount) {
		$itemTotal =& Services_PayPal::getType('BasicAmountType');
		$itemTotal->setval(number_format($itemAmount, 2));
		$itemTotal->setattr('currencyID', $currencyID); // USD
		$pdt->setItemTotal($itemTotal);
		
		$taxTotal =& Services_PayPal::getType('BasicAmountType');
		$taxTotal->setval(number_format($taxAmount, 2));
		$taxTotal->setattr('currencyID', $currencyID); // USD
		$pdt->setTaxTotal($taxTotal);
		
		$shippingTotal =& Services_PayPal::getType('BasicAmountType');
		$shippingTotal->setval(number_format($shippingAmount, 2));
		$shippingTotal->setattr('currencyID', $currencyID); // USD
		$pdt->setShippingTotal($shippingTotal);
	}
	
	 // START - adding info for shipping address
	$shipAddress =& Services_PayPal::getType('AddressType');
	$shipAddress->setName($basket['delInf']['firstName']."
	".$basket['delInf']['lastName']);
	$shipAddress->setStreet1($basket['delInf']['add_1']);
	$shipAddress->setStreet2($basket['delInf']['add_2']);
	$shipAddress->setCityName($basket['delInf']['town']);
	$shipAddress->setStateOrProvince($basket['delInf']['county']);
	$shipAddress->setCountry(countryIso($basket['delInf']['country']));
	$shipAddress->setPostalCode($basket['delInf']['postcode']);
	$pdt->setShipToAddress($shipAddress);
	// END - adding info for shipping address

	//$pdt->setOrderDescription($productName);
	$pdt->setInvoiceID($orderID);
	
	$details =& Services_PayPal::getType('DoDirectPaymentRequestDetailsType');
	$details->setPaymentAction("Sale");
	$details->setPaymentDetails($pdt);
	$details->setCreditCard($cc);
	$details->setIPAddress(getenv('REMOTE_ADDR'));
	$details->setMerchantSessionId(session_id());

	$ddp =& Services_PayPal::getType('DoDirectPaymentRequestType');
	$ddp->setDoDirectPaymentRequestDetails($details);

	$response = $caller->DoDirectPayment($ddp);

	if(Services_PayPal::isError($response) || ($response->getAck() != 'Success' && $response->getAck() != 'SuccessWithWarning')) {
		//if(Services_PayPal::isError($response))
		//    echo $response->getMessage();

		header("Location: confirmed.php?f=1");
		exit;
	} else {
		// check amount and currency?
		header("Location: confirmed.php");
		exit;
	}
}


$formTemplate = new XTemplate ("modules/gateway/DirectPayment/form.tpl");

$formTemplate->assign("VAL_FIRST_NAME",$ccUserData[0]['firstName']);
$formTemplate->assign("VAL_LAST_NAME",$ccUserData[0]['lastName']);
$formTemplate->assign("VAL_EMAIL_ADDRESS",$ccUserData[0]['email']);
$formTemplate->assign("VAL_ADD_1",$ccUserData[0]['add_1']);
$formTemplate->assign("VAL_ADD_2",$ccUserData[0]['add_2']);
$formTemplate->assign("VAL_CITY",$ccUserData[0]['town']);

// look up county
$isoLookup = $db->select("SELECT abbrev FROM `".$glob['dbprefix']."CubeCart_iso_counties`
WHERE `name` LIKE '%".ucfirst(str_replace(" ","",strtolower($ccUserData[0]['county'])))."%'");

if(strlen($ccUserData[0]['county'])==2){

	$countyIso = strtoupper($ccUserData[0]['county']);

} elseif($isoLookup == TRUE) {
	
	$countyIso = $isoLookup[0]['abbrev'];

} else {

	$countyIso = "XX";

}

$formTemplate->assign("VAL_COUNTY",$countyIso);
$formTemplate->assign("VAL_POST_CODE",$ccUserData[0]['postcode']);
$formTemplate->assign("VAL_CART_ORDER_ID",$basket['cart_order_id']);
$formTemplate->assign("VAL_ORDER_TOTAL",$basket['grandTotal']);
$formTemplate->assign("VAL_ITEM_TOTAL",$basket['subTotal']);
$formTemplate->assign("VAL_TAX_TOTAL",$basket['tax']);
$formTemplate->assign("VAL_SHIPPING_TOTAL",$basket['shipCost']);


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

if($currency == TRUE && $currency[0]['currency'] != ''){
	$formTemplate->assign("VAL_CURRENCY_ID", $currency[0]['currency']);
} else {
	$formTemplate->assign("VAL_CURRENCY_ID", $config['defaultCurrency']);
}

$acceptedCards = array("Visa" => "Visa", "MasterCard" => "Master Card", "Amex" => "American Express", "Discover" => "Discover");

foreach($acceptedCards as $cardType => $cardName) {
	$formTemplate->assign("VAL_CARD_TYPE",$cardType);
	
	if($cardType == "Visa")
		$formTemplate->assign("CARD_SELECTED","selected='selected'");
	else
		$formTemplate->assign("CARD_SELECTED","");
	$formTemplate->assign("VAL_CARD_NAME",$cardName);
	$formTemplate->parse("form.repeat_cards");
}

$countries = $db->select("SELECT id, iso, printable_name FROM ".$glob['dbprefix']."CubeCart_iso_countries ORDER BY printable_name"); 
	
	for($i=0; $i<count($countries); $i++){
				
			
		if($countries[$i]['id'] == $ccUserData[0]['country']){
			$formTemplate->assign("COUNTRY_SELECTED","selected='selected'");
		} else {
			$formTemplate->assign("COUNTRY_SELECTED","");
		}
	
		$formTemplate->assign("VAL_COUNTRY_ISO",$countries[$i]['iso']);

		$countryName = "";
		$countryName = $countries[$i]['printable_name'];

		if(strlen($countryName)>20){

			$countryName = substr($countryName,0,20)."&hellip;";

		}

		$formTemplate->assign("VAL_COUNTRY_NAME",$countryName);
		$formTemplate->parse("form.repeat_countries");
	}

$formTemplate->assign("LANG_CC_INFO_TITLE",$lang['module']['directPayment']['cc_info_title']);
$formTemplate->assign("LANG_FIRST_NAME",$lang['module']['directPayment']['first_name']); 
$formTemplate->assign("LANG_LAST_NAME",$lang['module']['directPayment']['last_name']); 
$formTemplate->assign("LANG_CARD_TYPE",$lang['module']['directPayment']['card_type']);
$formTemplate->assign("LANG_CARD_NUMBER",$lang['module']['directPayment']['card_number']);
$formTemplate->assign("LANG_EXPIRES",$lang['module']['directPayment']['expires']);
$formTemplate->assign("LANG_MMYYYY",$lang['module']['directPayment']['mmyyyy']);
$formTemplate->assign("LANG_SECURITY_CODE",$lang['module']['directPayment']['security_code']);
$formTemplate->assign("LANG_CUST_INFO_TITLE",$lang['module']['directPayment']['customer_info']);
$formTemplate->assign("LANG_EMAIL",$lang['module']['directPayment']['email']);
$formTemplate->assign("LANG_ADDRESS",$lang['module']['directPayment']['address']);
$formTemplate->assign("LANG_CITY",$lang['module']['directPayment']['city']);
$formTemplate->assign("LANG_STATE",$lang['module']['directPayment']['state']);
$formTemplate->assign("LANG_ZIPCODE",$lang['module']['directPayment']['zipcode']);
$formTemplate->assign("LANG_COUNTRY",$lang['module']['directPayment']['country']);
$formTemplate->assign("LANG_OPTIONAL",$lang['module']['directPayment']['optional']);

$formTemplate->parse("form");
$formTemplate = $formTemplate->text("form");
?>
