<?php

// Include required library files.
require_once 'includes/config.php';
require_once 'angelleye-paypal-php-lib/autoload.php';
// Create PayPal object.
$PayPalConfig = array('Sandbox' => $sandbox, 'DeveloperAccountEmail' => $developer_account_email, 'ApplicationID' => $application_id, 'DeviceID' => $device_id, 'IPAddress' => $_SERVER['REMOTE_ADDR'], 'APIUsername' => $api_username, 'APIPassword' => $api_password, 'APISignature' => $api_signature, 'APISubject' => $api_subject, 'PrintHeaders' => $print_headers, 'LogResults' => $log_results, 'LogPath' => $log_path);
$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
// Prepare request arrays
$PayRequestFields = array('ActionType' => '', 'CancelURL' => '', 'CurrencyCode' => '', 'FeesPayer' => '', 'IPNNotificationURL' => '', 'Memo' => '', 'Pin' => '', 'PreapprovalKey' => '', 'ReturnURL' => '', 'ReverseAllParallelPaymentsOnError' => '', 'SenderEmail' => '', 'TrackingID' => '');
$ClientDetailsFields = array('CustomerID' => '', 'CustomerType' => '', 'GeoLocation' => '', 'Model' => '', 'PartnerName' => '');
$FundingTypes = array('ECHECK', 'BALANCE', 'CREDITCARD');
// Funding constrainigs require advanced permissions levels.
$Receivers = array();
$Receiver = array('Amount' => '', 'Email' => '', 'AccountID' => '', 'InvoiceID' => '', 'PaymentType' => '', 'PaymentSubType' => '', 'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''), 'Primary' => '');
array_push($Receivers, $Receiver);
$SenderIdentifierFields = array('UseCredentials' => '');
$AccountIdentifierFields = array('Email' => '', 'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''));
$PayPalRequestData = array('PayRequestFields' => $PayRequestFields, 'ClientDetailsFields' => $ClientDetailsFields, 'FundingTypes' => $FundingTypes, 'Receivers' => $Receivers, 'SenderIdentifierFields' => $SenderIdentifierFields, 'AccountIdentifierFields' => $AccountIdentifierFields);
// Pass data into class for processing with PayPal and load the response array into $PayPalResult
$PayPalResult = $PayPal->Pay($PayPalRequestData);
// Write the contents of the response array to the screen for demo purposes.
echo '<pre />';
print_r($PayPalResult);
 /**
  * Perform PayPal Pre Approval request and return the result.
  * Prepare all config vars for PayPal Request
  * @params $EM_Booking
  * @returns array $PayPalResponse
  */
 function paypal_pre_approval($EM_Booking)
 {
     // Get Adaptive Payments Pay Key
     require_once 'lib/angelleye/PayPal/PayPal.php';
     require_once 'lib/angelleye/PayPal/Adaptive.php';
     // Create PayPal object.
     $PayPalConfig = array('IPAddress' => $_SERVER['REMOTE_ADDR'], 'APISubject' => '', 'LogResults' => false, 'LogPath' => $_SERVER['DOCUMENT_ROOT'] . '/logs/');
     // Differing values for Sandbox or Live
     if (get_option('em_' . $this->gateway . "_status") == 'test') {
         $PayPalConfig['DeveloperAccountEmail'] = get_option('em_' . $this->gateway . "_dev_email");
         $PayPalConfig['LogResults'] = true;
         $PayPalConfig['Sandbox'] = true;
         $PayPalConfig['ApplicationID'] = 'APP-80W284485P519543T';
         $PayPalConfig['APIUsername'] = get_option('em_' . $this->gateway . "_api_sb_username");
         $PayPalConfig['APIPassword'] = get_option('em_' . $this->gateway . "_api_sb_password");
         $PayPalConfig['APISignature'] = get_option('em_' . $this->gateway . "_api_sb_signature");
         $pp_account_email = get_option('em_' . $this->gateway . "_sb_email");
     } else {
         $PayPalConfig['Sandbox'] = false;
         $PayPalConfig['ApplicationID'] = get_option('em_' . $this->gateway . "_app_id");
         $PayPalConfig['APIUsername'] = get_option('em_' . $this->gateway . "_api_username");
         $PayPalConfig['APIPassword'] = get_option('em_' . $this->gateway . "_api_password");
         $PayPalConfig['APISignature'] = get_option('em_' . $this->gateway . "_api_signature");
         $pp_account_email = get_option('em_' . $this->gateway . "_email");
     }
     $PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
     if (get_option('em_' . $this->gateway . "_return")) {
         $return_url = get_option('em_' . $this->gateway . "_return");
     } else {
         $return_url = get_permalink(get_option("dbem_my_bookings_page")) . '?thanks=1';
     }
     // Optional
     /*
     $ClientDetailsFields = array(
     	'CustomerID' => '', 								// Your ID for the sender  127 char max.
     	'CustomerType' => '', 								// Your ID of the type of customer.  127 char max.
     	'GeoLocation' => '', 								// Sender's geographic location
     	'Model' => '', 										// A sub-identification of the application.  127 char max.
     	'PartnerName' => ''									// Your organization's name or ID
     );
     */
     // Funding constraints require advanced permissions levels.
     //$FundingTypes = array('ECHECK', 'BALANCE', 'CREDITCARD');
     $Receivers = array();
     $Receiver = array('Amount' => $EM_Booking->get_price(false, false, true), 'Email' => $pp_account_email, 'InvoiceID' => '', 'PaymentType' => '', 'PaymentSubType' => '', 'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''), 'Primary' => 'true');
     array_push($Receivers, $Receiver);
     /*
     		$Receiver = array(
     			'Amount' => '50.00', 											// Required.  Amount to be paid to the receiver.
     			'Email' => '*****@*****.**', 												// Receiver's email address. 127 char max.
     			'InvoiceID' => '', 											// The invoice number for the payment.  127 char max.
     			'PaymentType' => '', 										// Transaction type.  Values are:  GOODS, SERVICE, PERSONAL, CASHADVANCE, DIGITALGOODS
     			'PaymentSubType' => '', 									// The transaction subtype for the payment.
     			'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''), // Receiver's phone number.   Numbers only.
     			'Primary' => 'false'												// Whether this receiver is the primary receiver.  Values are boolean:  TRUE, FALSE
     		);
     		array_push($Receivers,$Receiver);
     */
     // This is the big one. Hook into this to add or modify Receivers. Without multiple receivers Chained payment request will fail.
     $Receivers = apply_filters('em_gateway_paypal_chained_receivers', $Receivers, $EM_Booking, $this);
     //if( count( $Receivers ) > 1
     // Filter to allow fees payer setting to be modified on booking by booking basis
     $fees_payer = apply_filters('em_gateway_paypal_chained_fees_payer', get_option('em_' . $this->gateway . "_fees_payer"), $Receivers, $EM_Booking, $this);
     // Prepare request arrays, only creating chained payment settings if more than one receiver
     $PayRequestFields = array('ActionType' => 'PAY', 'CancelURL' => '<![CDATA[' . get_option('em_' . $this->gateway . "_cancel_return") . ']]>', 'CurrencyCode' => get_option('dbem_bookings_currency', 'USD'), 'FeesPayer' => $fees_payer, 'IPNNotificationURL' => '<![CDATA[' . $this->get_payment_return_url() . ']]>', 'Memo' => '<![CDATA[Booking for ' . $EM_Booking->get_event()->event_name . ']]>', 'ReturnURL' => '<![CDATA[' . $return_url . ']]>', 'SenderEmail' => '', 'TrackingID' => $EM_Booking->booking_id);
     // Optional
     /*
     $SenderIdentifierFields = array(
     	'UseCredentials' => ''						// If TRUE, use credentials to identify the sender.  Default is false.
     );
     */
     // Optional
     /*
     $AccountIdentifierFields = array(
     	'Email' => '', 								// Sender's email address.  127 char max.
     	'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => '')								// Sender's phone number.  Numbers only.
     );
     */
     $PayPalRequestData = array('PayRequestFields' => $PayRequestFields, 'Receivers' => $Receivers);
     // Add hook for Request Data
     $PayPalRequestData = apply_filters('em_gateway_paypal_chained_paypal_request_data', $PayPalRequestData, $EM_Booking, $this);
     //error_log( print_r( $PayPalRequestData, true ) );
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->Pay($PayPalRequestData);
     return $PayPalResult;
 }