<?php
		
	/************************************************/
	/* JetPay Merchant Transaction Payment Pages    */
	/*              Version 1.09.01                 */
	/* For questions or assistance with this or any */
	/* pages in this package, please contact JetPay */
	/* Customer Service at 800-834-4405 option 2    */
	/* or email to assist@jetpay.com                */
	/* Development Team:                            */
	/* Dave Lantz - Lead Devlopment and Design      */
	/* Shez Virani - Technical Code Review          */
	/* David Wright - Email and Code Review         */
	/* These pages may not be reproduced or 		*/
	/* distributed with out the concent of JetPayLLC*/
	/* All Rights Reserved                          */
	/* Copyright 2006                               */
	/************************************************/

  require('includes/application_top.php');

// if the customer is not logged on, redirect them to the login page
  if (!tep_session_is_registered('customer_id')) {
    $navigation->set_snapshot(array('mode' => 'SSL', 'page' => FILENAME_CHECKOUT_PAYMENT));
//    tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
  }

  if (!tep_session_is_registered('sendto')) {
    tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'));
  }

  if ( (tep_not_null(MODULE_PAYMENT_INSTALLED)) && (!tep_session_is_registered('payment')) ) {
    tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'));
 }

// avoid hack attempts during the checkout procedure by checking the internal cartID
  if (isset($cart->cartID) && tep_session_is_registered('cartID')) {
    if ($cart->cartID != $cartID) {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', 'SSL'));
    }
  }

  require(DIR_WS_CLASSES . 'order_total.php');// CCGV

//  if (!tep_session_is_registered('payment')) tep_session_register('payment');
//  if (isset($HTTP_POST_VARS['payment'])) $payment = $HTTP_POST_VARS['payment'];

	ini_set('session.gc_probability','100');
			
	include_once("includes/gatewayapi/inc_gatewayapi.php");
	$_SESSION['amount'];
	$_SESSION['address1'];
    $_SESSION['address2'];
	$_SESSION['city'];
	$_SESSION['state'];
	$_SESSION['zip'];
	$_SESSION['country'];
	$_SESSION['name'];
	$_SESSION['email'];
	
/*	// random key generator for partial transaction id
	function getrand() {
	   	// random key paramters
   	   	$keyset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   		$length = 4;   // first 14 chars of transaction_id are date, last 4 random

	    // Random Key Generator
   		$randkey = "";
   		$max = strlen($keyset)-1;

   		for ($i=0; $i<$length; $i++) {
      		$randkey .= substr($keyset, rand(0,$max), 1);
   		}
   		return $randkey;
   }
	// end function getrand()*/

	// This section grabs all the information that was entered into the order form page and creates all the variables
	
	// Get values needed for xml string
	// get date for first part of transaction id and use getrand() for second part
	$date = date("YmdHis");   //puts in format YYYYMMDDhhmmss
	$rand_str = getrand();
	$transactionID = $date . $rand_str;
	$name = $_SESSION['jet_pay_cc_owner'];
//	echo "jet_pay_process_transaction:<br />"; echo "\nsession:<br />";print_r($_SESSION);echo "<br />\npost:<br />";print_r($_POST);die;
	// get cardnum and expdate
	$cardnum = $_SESSION['jet_pay_cc_number'];
	$cvv2 = $_SESSION['jet_pay_cc_cvv2'];

	// break down expiration date from MMYY to two variables
	$expmo = $_SESSION['jet_pay_cc_expires_month'];
	if($_SESSION['jet_pay_cc_expires_year']>=10){
	  $expyr=substr($_SESSION['jet_pay_cc_expires_year'],2,2);
	}else{
	  $expyr=$_SESSION['jet_pay_cc_expires_year'];
	}
//	$expyr = $_SESSION['jet_pay_cc_expires_year'];

	$amount = round($_SESSION['jet_pay_cc_total'],2);
	$amount = $amount * 100;

	// AVS Checking
	$address1 = $_SESSION['jet_pay_cc_address'];
	$address2 = $_SESSION['address2'];
	$city = $_SESSION['jet_pay_cc_city'];
	$state = $_SESSION['jet_pay_cc_state'];
	$zip = $_SESSION['jet_pay_cc_zip'];
	$country = $_SESSION['jet_pay_cc_zip_country'];

	// End of section for capturing data from order form page

	// Section where error checking occurs

	// Holds all the generated error messages
	$errorString = "";
	
	// Name field checking
	if ( $name == "" )
	{
		$errorString .= "We are sorry, please enter your name as it appers on your credit card.";
	}

	// Address field checking
	if ( $address1 == "" )
	{
		$errorString .= "We are sorry, please enter the billing address for this card.";
	}

	// City field checking
	if ( $city == "" )
	{
		$errorString .= "We are sorry, please enter the billing city for this card.<br>";
	}
	
	//State filed checking
	if( $state == "Select A State")
	{
		$errorString .= "We are sorry, please enter the billing state for this card.";
	}
		
	// Zip Code Checking
	if ( $zip == "" )
	{
		$errorString .= "We are sorry, please enter the billing zip/postal code for this card.<br>";
	}
	
	// Credit card number error checking
	$cardnum = StripNonNumeric ($cardnum);
	if ( $cardnum == "" )
	{
		$errorString .= "We are sorry, please enter your credit card number.";
	}
	else
	{
		if(!CheckLuhn10($cardnum))
		{
			$errorString .= "We are sorry, the credit card number entered is not valid.<br>";
		}
		else
		{
			if (cardTypeAccepted($cardnum))
			{
				//DONT DO ANYTHING
				//print "Credit Card Success.";
			}
			else
			{
				$errorString .= "We are sorry, we cannot accept this type of card. Please use a different one.";
				error_log($GatewaySettings . ' - ' . cardTypeAccepted($cardnum) . ' ' . $errorString);
			}
		}
	}
	// End credit card error checking

	// Expiration date error checking
	if ( $expmo == "" )
	{
		$errorString .= "We are sorry, please enter credit card expiration month.";
	}

	if ( $expyr == "" )
	{
		$errorString .= "We are sorry, please enter credit card expiration year.";
	}

	if ( $expmo !== "" && $expyr !== "" )
	{
		if ( checkMonthIsNotPast ( $expmo, $expyr ) )
		{
			//DO NOTHING
			//print "Expiration Date Success.";
		}
		else
		{
			$errorString .= "We are sorry, the credit card has expired.  Please try another card or enter correct expiration date.";
		}
	}
	// End expiration date error checking

	// CVV2/CVC2/CID Error Checking
	if ( $cvv2 == "" )
	{
		$errorString .= "We are sorry.  Please enter security code found on the credit card.";
	}
	else
	{
		$type = getCardType($cardnum);
		$length = strlen($cvv2);
		if ( $type == "Amex" )
		{
			if ( $length !== 4 )
			{
				$errorString .= "We are sorry.  Security code for American Express must be four digits long.";
			}
			else
			{
				//print "Security Code Success.";
			}
		}
		else
		{
			if ( $length !== 3 )
			{
				$errorString .= "We are sorry.  Security code must be three digits long.";
			}
			else
			{
				//print "Security Code Success.";
			}
		}
	}
	// End Security Code Error Checking
	
	// Amount Checking
/*	if ( $amount < $minTransAmount )
	{
		$errorString .= "We are sorry.  The amount is too low.";
	}
	elseif ( $amount > $maxTransAmount )
	{
		$errorString .= "We are sorry.  The amount is too over $maxTransAmount.";
	}*/
	// End Amount Error Checking
	
	// E-mail Error Checking

/*	print "error string is >$errorString<";*/

	//-------------------------------------------------------------------------
	//End Error Checking Section

	//XML Section
	//--------------------------------------------------------------------------
 	if ( $errorString == "" )
  	{
  		//Create XML String
     	$xmlString = "<JetPay>";
		$xmlString .= "<TransactionType>" . $transactionType . "</TransactionType>";
		$xmlString .= "<MerchantID>" . $tid . "</MerchantID>";
		$xmlString .= "<TransactionID>" . $transactionID . "</TransactionID>";
		$xmlString .= "<CardNum>" . $cardnum . "</CardNum>";
		$xmlString .= "<CVV2>" . $cvv2 . "</CVV2>";
		$xmlString .= "<CardExpMonth>" . $expmo . "</CardExpMonth>";
		$xmlString .= "<CardExpYear>" . $expyr . "</CardExpYear>";
		$xmlString .= "<CardName>" . $name . "</CardName>";
		$xmlString .= "<TotalAmount>" . $amount . "</TotalAmount>";
		$xmlString .= "<BillingAddress>" . $address1 . "</BillingAddress>";
		$xmlString .= "<BillingCity>" . $city . "</BillingCity>";
		$xmlString .= "<BillingStateProv>" . $state . "</BillingStateProv>";
		$xmlString .= "<BillingPostalCode>" . $zip . "</BillingPostalCode>";
		if(  isset( $_SESSION['auth_cavv'] ) && (strlen($_SESSION['auth_cavv'])>2) || isset($_SESSION['auth_xid']) && (strlen($_SESSION['auth_xid'])>2)  ){
			if($type=='Mastercard'){
				$xmlString .= '<Verification Type = "SC">';
			}elseif($type=='Visa'){
				$xmlString .= '<Verification Type = "VbV">';
			}
			$xmlString .= '<Cavv>' . $_SESSION['auth_cavv'] . '</Cavv>';
			$xmlString .= '<Xid>' . $_SESSION['auth_xid'] . '</Xid>';
			$xmlString .= '<Eci>' . $_SESSION['auth_eci'] . '</Eci>';
			$xmlString .= '</Verification>';
			$xmlString .= "<Version><Subscriber>" . $verSub . "</Subscriber></Version>";
		}
				
//		if(isset($_SESSION['auth_xid'])){
		
		$xmlString .= "</JetPay>";
	
//			echo nl2br($xmlString) . "<br />\n";


		//Send XML to JetPay
		$xmlResponse = sendXMLString($xmlString);
		//echo $xmlResponse . "<br />";
		//Check for curl error
		if ( $xmlResponse == "" )
		{
			tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("Transaction error.  Please try again."), 'SSL'));
		}
		else
		{
			// Parse XML response
			$xml_parser = xml_parser_create();
			// set to not change to uppercase
			xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
			// ignore white space
			xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
			// puts values in an array of xml tags (vals)
			xml_parse_into_struct($xml_parser, $xmlResponse, $vals, $index);
			xml_parser_free($xml_parser);
			
			$retTransID = "";
			$retActionCode = "";
			$retApproval = "";
			$retCVV2 = "";
			$retResponseText = "";
			$retAddressMatch = "";
			$retZipMatch ="";
			$retAVS = "";
			$retErrMsg = "";
			
			$numTags = $index[JetPayResponse][1];        // number of tags including JetPayResponse
			$numTags = 9;
		
			$return_message = 'Please try again.';
			for ($x=0; $x<$numTags; $x++)
			{
				$key = $vals[$x][tag];
											 
				switch ($key) 
				{
				  case "TransactionID":        
					$retTransID = $vals[$x][value];
					break;
				  case "ActionCode":           
					$retActionCode = $vals[$x][value];
					break;
				  case "Approval":             
					$retApproval = $vals[$x][value];
					break;
				  case "CVV2":             
					$retCVV2 = $vals[$x][value];
					break;
				  case "ResponseText":         
					 $retResponseText = $vals[$x][value];
					break;
				  case "AddressMatch":             
					$retAddressMatch = $vals[$x][value];
					$return_message = 'Address does not match';
					break;
				  case "ZipMatch":             
					$retZipMatch = $vals[$x][value];
					$return_message = 'Zip code does not match';
					break;
				  case "AVS":             
					$retAVS = $vals[$x][value];
					break;
				  case "JetPayResponse":
					// wrappers - can be ignored
					break;
				  case "ErrMsg":               
					$retErrMsg = $vals[$x][value];
					break;
				  default:                     
					// if other message could be error
					$retErrMsg = $vals[$x][value];
					break;
			   } // end switch
			} // end for loop

			tep_db_query("INSERT INTO jbrunner_osc1.jet_pay_payment_processing (transaction_id, action_code, approval_code, response_text, error_message, cvv2_approval, address_match, zip_match, avs, ip_address, amount, cc_number, cvv2, expmo, expyr, cardholder) VALUES ('$retTransID', '$retActionCode', '$retApproval', '$retResponseText', '$retErrMsg', '$retCVV2', '$retAddressMatch', '$retZipMatch', '$retAVS', '" . $_SERVER['REMOTE_ADDR'] . "', '$amount', $cardnum, $cvv2, $expmo, $expyr, '$name')");
			$_SESSION['transaction_id'] = $transactionID;
			$newAmount = number_format(($amount)/100, 2, '.', '');$amount/100;
			
			if ( $retActionCode == "000" )
			{
/*				header("Location: " . $GatewaySettings['PaymentApprovedPage'] . "?TransactionID=" . rawurlencode($retTransID) . "&ApprovalCode=" . rawurlencode($retApproval)
						. "&amount=" . rawurlencode($newAmount));*/
/*						print_r($_SESSION);
						print_r($_POST);*/

				tep_redirect(tep_href_link(FILENAME_CHECKOUT_PROCESS_OSC, '', 'SSL'));
			}
			else
			{
				//Function that takes retActionCode -> String based on code
//		echo 'url:' . $url . "<br />\n";
//		echo 'here'; echo $retActionCode;die;
				error_log($xmlString);
				tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode("Transaction error.  " . $return_message), 'SSL'));
				//header("Location: " . $GatewaySettings['PaymentDeniedPage'] . "?gateway_error=" . rawurlencode($retActionCode));
			}
		}
	}
  	else 
	{
//		echo date("Y-m-d h:G:s"); print_r($_SESSION); echo "<br />\n"; print_r($GLOBALS); echo die;
		tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT, 'error_message=' . urlencode($errorString), 'SSL'));
//		 //header("Location: " . $GatewaySettings['PaymentDeniedPage'] . "?gateway_error=" . rawurlencode($errorString));
	}

//echo 	$errorString;
	//---------------------------------------------------------------------------
	//End XML Section

?>
