/**
  * CallSetExpressCheckout
  *
  * Makes a request to PayPal's SetExpressCheckout API
  * to setup the checkout and obtain a token.
  *
  * @paymentAmount (double) Total payment amount of the order.
  * @returnURL (string) URL for PayPal to send the buyer to after review and continue from PayPal.
  * @cancelURL (string) URL for PayPal to send the buyer to if they cancel the payment.
  */
 function CallSetExpressCheckout($paymentAmount, $returnURL, $cancelURL, $usePayPalCredit = false, $posted)
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         $ms = sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"');
         $set_ec_message = apply_filters('angelleye_set_ec_message', $ms);
         wc_add_notice($set_ec_message, "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once PAYPAL_FOR_WOOCOMMERCE_PLUGIN_DIR . '/classes/lib/angelleye/paypal-php-library/includes/paypal.class.php';
     }
     /*
      * Create PayPal object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature);
     $PayPal = new Angelleye_PayPal($PayPalConfig);
     /**
      * Prepare PayPal request data.
      */
     /**
      * If Gift Wrap options are enabled, then MAXAMT is required
      * in SetExpressCheckout.
      *
      * https://github.com/angelleye/paypal-woocommerce/issues/142
      */
     if ($this->gift_wrap_enabled == 'yes') {
         $maxAmount = $paymentAmount * 2;
         $maxAmount = $maxAmount + $this->gift_wrap_amount;
         $maxAmount = AngellEYE_Gateway_Paypal::number_format($maxAmount);
     } else {
         $maxAmount = '';
     }
     //prefill email
     if (isset($posted['billing_email'])) {
         $customer_email = $posted['billing_email'];
     } elseif (is_user_logged_in()) {
         global $current_user;
         get_currentuserinfo();
         $customer_email = $current_user->user_email;
     } else {
         $customer_email = '';
     }
     $SECFields = array('token' => '', 'maxamt' => $maxAmount, 'returnurl' => urldecode($returnURL), 'cancelurl' => urldecode($cancelURL), 'callback' => '', 'callbacktimeout' => '', 'callbackversion' => '', 'reqconfirmshipping' => '', 'noshipping' => '', 'allownote' => 1, 'addroverride' => '', 'localecode' => $this->use_wp_locale_code == 'yes' && get_locale() != '' ? get_locale() : '', 'pagestyle' => '', 'hdrimg' => $this->checkout_logo_hdrimg, 'logoimg' => $this->checkout_logo, 'hdrbordercolor' => '', 'hdrbackcolor' => '', 'payflowcolor' => '', 'skipdetails' => $this->skip_final_review == 'yes' ? '1' : '0', 'email' => $customer_email, 'channeltype' => '', 'giropaysuccessurl' => '', 'giropaycancelurl' => '', 'banktxnpendingurl' => '', 'brandname' => $this->brand_name, 'customerservicenumber' => $this->customer_service_number, 'buyeremailoptionenable' => '', 'surveyquestion' => '', 'surveyenable' => '', 'totaltype' => '', 'notetobuyer' => '', 'buyerid' => '', 'buyerusername' => '', 'buyerregistrationdate' => '', 'allowpushfunding' => '', 'taxidtype' => '', 'taxid' => '');
     /**
      * If Gift Wrap options are enabled, add them to SEC
      */
     if (strtolower($this->gift_wrap_enabled) == 'yes') {
         $SECFields['giftwrapenable'] = '1';
         // Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
         $SECFields['giftmessageenable'] = $this->gift_message_enabled ? '1' : '';
         // Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
         $SECFields['giftreceiptenable'] = $this->gift_receipt_enabled ? '1' : '';
         // Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
         $SECFields['giftwrapname'] = $this->gift_wrap_name;
         // Label for the gift wrap option such as "Box with ribbon".  25 char max.
         $SECFields['giftwrapamount'] = $this->gift_wrap_amount;
         // Amount charged for gift-wrap service.
     }
     /**
      * If PayPal Credit is being used, override the necessary parameters
      */
     if ($usePayPalCredit) {
         $SECFields['solutiontype'] = 'Sole';
         $SECFields['landingpage'] = 'Billing';
         $SECFields['userselectedfundingsource'] = 'BML';
     } elseif (strtolower($this->paypal_account_optional) == 'yes' && strtolower($this->landing_page) == 'billing') {
         $SECFields['solutiontype'] = 'Sole';
         $SECFields['landingpage'] = 'Billing';
         $SECFields['userselectedfundingsource'] = 'CreditCard';
     } elseif (strtolower($this->paypal_account_optional) == 'yes' && strtolower($this->landing_page) == 'login') {
         $SECFields['solutiontype'] = 'Sole';
         $SECFields['landingpage'] = 'Login';
     }
     // Basic array of survey choices.  Nothing but the values should go in here.
     $SurveyChoices = array('Choice 1', 'Choice2', 'Choice3', 'etc');
     $Payments = array();
     $Payment = array('amt' => AngellEYE_Gateway_Paypal::number_format(WC()->cart->total), 'currencycode' => get_woocommerce_currency(), 'shippingamt' => '', 'shippingdiscamt' => '', 'insuranceamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'taxamt' => '', 'desc' => '', 'custom' => '', 'invnum' => '', 'notifyurl' => '', 'shiptoname' => '', 'shiptostreet' => '', 'shiptostreet2' => '', 'shiptocity' => '', 'shiptostate' => '', 'shiptozip' => '', 'shiptocountrycode' => '', 'shiptophonenum' => '', 'notetext' => isset($posted['order_comments']) ? $posted['order_comments'] : '', 'allowedpaymentmethod' => '', 'paymentaction' => $this->payment_action == 'Authorization' ? 'Authorization' : 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '');
     /**
      * If checkout like regular payment
      */
     if (!empty($posted) && WC()->cart->needs_shipping()) {
         $SECFields['addroverride'] = 1;
         if (@$posted['ship_to_different_address']) {
             $Payment['shiptoname'] = $posted['shipping_first_name'] . ' ' . $posted['shipping_last_name'];
             $Payment['shiptostreet'] = $posted['shipping_address_1'];
             $Payment['shiptostreet2'] = @$posted['shipping_address_2'];
             $Payment['shiptocity'] = @$posted['shipping_city'];
             $Payment['shiptostate'] = @$posted['shipping_state'];
             $Payment['shiptozip'] = @$posted['shipping_postcode'];
             $Payment['shiptocountrycode'] = @$posted['shipping_country'];
             $Payment['shiptophonenum'] = @$posted['shipping_phone'];
         } else {
             $Payment['shiptoname'] = $posted['billing_first_name'] . ' ' . $posted['billing_last_name'];
             $Payment['shiptostreet'] = $posted['billing_address_1'];
             $Payment['shiptostreet2'] = @$posted['billing_address_2'];
             $Payment['shiptocity'] = @$posted['billing_city'];
             $Payment['shiptostate'] = @$posted['billing_state'];
             $Payment['shiptozip'] = @$posted['billing_postcode'];
             $Payment['shiptocountrycode'] = @$posted['billing_country'];
             $Payment['shiptophonenum'] = @$posted['billing_phone'];
         }
     } elseif (is_user_logged_in() && WC()->cart->needs_shipping()) {
         $Payment['shiptostreet'] = WC()->customer->get_shipping_address();
         $Payment['shiptostreet2'] = WC()->customer->get_shipping_address_2();
         $Payment['shiptocity'] = WC()->customer->get_shipping_city();
         $Payment['shiptostate'] = WC()->customer->get_shipping_state();
         $Payment['shiptozip'] = WC()->customer->get_shipping_postcode();
         $Payment['shiptocountrycode'] = WC()->customer->get_shipping_country();
     }
     $SECFields = AngellEYE_Gateway_Paypal::angelleye_paypal_for_woocommerce_needs_shipping($SECFields);
     $PaymentData = AngellEYE_Gateway_Paypal::calculate(null, true);
     $PaymentOrderItems = array();
     $ctr = $total_items = $total_discount = $total_tax = $order_total = 0;
     if ($this->send_items) {
         foreach ($PaymentData['order_items'] as $item) {
             $Item = array('name' => $item['name'], 'desc' => '', 'amt' => $item['amt'], 'number' => $item['number'], 'qty' => $item['qty'], 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
             array_push($PaymentOrderItems, $Item);
         }
         $Payment['order_items'] = $PaymentOrderItems;
     } else {
         $Payment['order_items'] = array();
     }
     /**
      * Shipping/tax/item amount
      */
     $Payment['taxamt'] = $PaymentData['taxamt'];
     $Payment['shippingamt'] = $PaymentData['shippingamt'];
     $Payment['itemamt'] = $PaymentData['itemamt'];
     /*
      * Then we load the payment into the $Payments array
      */
     array_push($Payments, $Payment);
     $BuyerDetails = array('buyerid' => '', 'buyerusername' => '', 'buyerregistrationdate' => '');
     // For shipping options we create an array of all shipping choices similar to how order items works.
     $ShippingOptions = array();
     $Option = array('l_shippingoptionisdefault' => '', 'l_shippingoptionname' => '', 'l_shippingoptionlabel' => '', 'l_shippingoptionamount' => '');
     array_push($ShippingOptions, $Option);
     global $pp_settings, $pp_pro, $pp_payflow;
     $PayPalRequestData = array('SECFields' => $SECFields, 'SurveyChoices' => $SurveyChoices, 'Payments' => $Payments);
     $PayPalRequestData = AngellEYE_Gateway_Paypal::angelleye_paypal_for_woocommerce_paypal_billing_agreement($PayPalRequestData);
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData);
     /**
      *  cURL Error Handling #146 
      *  @since    1.1.8
      */
     AngellEYE_Gateway_Paypal::angelleye_paypal_for_woocommerce_curl_error_handler($PayPalResult, $methos_name = 'SetExpressCheckout', $gateway = 'PayPal Express Checkout', $this->error_email_notify);
     /*
      * Log API result
      */
     $this->add_log('Test Mode: ' . $this->testmode);
     $this->add_log('Endpoint: ' . $this->API_Endpoint);
     $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
     $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
     $this->add_log('Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
     $this->add_log('Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     /*
      * Error handling
      */
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         $token = urldecode($PayPalResult["TOKEN"]);
         $this->set_session('TOKEN', $token);
     }
     /*
      * Return the class library result array.
      */
     return $PayPalResult;
 }