/**
  * do_payment
  *
  * Makes the request to PayPal's DoDirectPayment API
  *
  * @access public
  * @param mixed $order
  * @param mixed $card_number
  * @param mixed $card_type
  * @param mixed $card_exp_month
  * @param mixed $card_exp_year
  * @param mixed $card_csc
  * @param string $centinelPAResStatus (default: '')
  * @param string $centinelEnrolled (default: '')
  * @param string $centinelCavv (default: '')
  * @param string $centinelEciFlag (default: '')
  * @param string $centinelXid (default: '')
  * @return void
  */
 function do_payment($order, $card_number, $card_type, $card_exp_month, $card_exp_year, $card_csc, $centinelPAResStatus = '', $centinelEnrolled = '', $centinelCavv = '', $centinelEciFlag = '', $centinelXid = '')
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         $pc_session_expired_error = apply_filters('angelleye_pc_session_expired_error', sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'));
         wc_add_notice($pc_session_expired_error, "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once '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);
     if (empty($GLOBALS['wp_rewrite'])) {
         $GLOBALS['wp_rewrite'] = new WP_Rewrite();
     }
     $card_exp = $card_exp_month . $card_exp_year;
     /**
      * Generate PayPal request
      */
     $DPFields = array('paymentaction' => $this->payment_action == 'Authorization' ? 'Authorization' : 'Sale', 'ipaddress' => $this->get_user_ip(), 'returnfmfdetails' => '');
     $CCDetails = array('creditcardtype' => $card_type, 'acct' => $card_number, 'expdate' => $card_exp, 'cvv2' => $card_csc, 'startdate' => '', 'issuenumber' => '');
     $PayerInfo = array('email' => $order->billing_email, 'firstname' => $order->billing_first_name, 'lastname' => $order->billing_last_name);
     $BillingAddress = array('street' => $order->billing_address_1, 'street2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'countrycode' => $order->billing_country, 'zip' => $order->billing_postcode, 'phonenum' => $order->billing_phone);
     $ShippingAddress = array('shiptoname' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'shiptostreet' => $order->shipping_address_1, 'shiptostreet2' => $order->shipping_address_2, 'shiptocity' => $order->shipping_city, 'shiptostate' => $order->shipping_state, 'shiptozip' => $order->shipping_postcode, 'shiptocountry' => $order->shipping_country, 'shiptophonenum' => $order->shipping_phone);
     $PaymentDetails = array('amt' => number_format($order->get_total(), 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'insuranceamt' => '', 'shipdiscamt' => '0.00', 'handlingamt' => '0.00', 'desc' => '', 'custom' => $order->customer_note ? substr(preg_replace("/[^A-Za-z0-9 ]/", "", $order->customer_note), 0, 256) : '', 'invnum' => $invoice_number = $this->invoice_id_prefix . preg_replace("/[^0-9,.]/", "", $order->id), 'notifyurl' => '', 'recurring' => '');
     $PaymentData = AngellEYE_Gateway_Paypal::calculate($order, $this->send_items);
     $OrderItems = array();
     if ($this->send_items) {
         foreach ($PaymentData['order_items'] as $item) {
             $Item = array('l_name' => $item['name'], 'l_desc' => '', 'l_amt' => $item['amt'], 'l_number' => $item['number'], 'l_qty' => $item['qty'], 'l_taxamt' => '', 'l_ebayitemnumber' => '', 'l_ebayitemauctiontxnid' => '', 'l_ebayitemorderid' => '');
             array_push($OrderItems, $Item);
         }
     }
     /**
      * Shipping/tax/item amount
      */
     $PaymentDetails['taxamt'] = $PaymentData['taxamt'];
     $PaymentDetails['shippingamt'] = $PaymentData['shippingamt'];
     $PaymentDetails['itemamt'] = $PaymentData['itemamt'];
     /**
      * 3D Secure Params
      */
     if ($this->enable_3dsecure) {
         $Secure3D = array('authstatus3d' => $centinelPAResStatus, 'mpivendor3ds' => $centinelEnrolled, 'cavv' => $centinelCavv, 'eci3ds' => $centinelEciFlag, 'xid' => $centinelXid);
     } else {
         $Secure3D = array();
     }
     $PayPalRequestData = array('DPFields' => $DPFields, 'CCDetails' => $CCDetails, 'PayerInfo' => $PayerInfo, 'BillingAddress' => $BillingAddress, 'ShippingAddress' => $ShippingAddress, 'PaymentDetails' => $PaymentDetails, 'OrderItems' => $OrderItems, 'Secure3D' => $Secure3D);
     if ($this->debug) {
         $log = $PayPalRequestData;
         $log['CCDetails']['acct'] = '****';
         $log['CCDetails']['cvv2'] = '****';
         $this->log->add('paypal-pro', 'Do payment request ' . print_r($log, true));
     }
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
     if ($this->debug) {
         $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
         $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
         $this->log->add('paypal-pro', 'Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
         $this->log->add('paypal-pro', 'Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     }
     if (empty($PayPalResult['RAWRESPONSE'])) {
         $pc_empty_response = apply_filters('angelleye_pc_empty_response', __('Empty PayPal response.', 'paypal-for-woocommerce'), $PayPalResult);
         throw new Exception($pc_empty_response);
     }
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         // Add order note
         $order->add_order_note(sprintf(__('PayPal Pro payment completed (Transaction ID: %s, Correlation ID: %s)', 'paypal-for-woocommerce'), $PayPalResult['TRANSACTIONID'], $PayPalResult['CORRELATIONID']));
         //$order->add_order_note("PayPal Results: ".print_r($PayPalResult,true));
         /* Checkout Note */
         if (isset($_POST) && !empty($_POST['order_comments'])) {
             // Update post 37
             $checkout_note = array('ID' => $order->id, 'post_excerpt' => $_POST['order_comments']);
             wp_update_post($checkout_note);
         }
         /**
          * Add order notes for AVS result
          */
         $avs_response_code = isset($PayPalResult['AVSCODE']) ? $PayPalResult['AVSCODE'] : '';
         $avs_response_message = $PayPal->GetAVSCodeMessage($avs_response_code);
         $avs_response_order_note = __('Address Verification Result', 'paypal-for-woocommerce');
         $avs_response_order_note .= "\n";
         $avs_response_order_note .= $avs_response_code;
         $avs_response_order_note .= $avs_response_message != '' ? ' - ' . $avs_response_message : '';
         $order->add_order_note($avs_response_order_note);
         /**
          * Add order notes for CVV2 result
          */
         $cvv2_response_code = isset($PayPalResult['CVV2MATCH']) ? $PayPalResult['CVV2MATCH'] : '';
         $cvv2_response_message = $PayPal->GetCVV2CodeMessage($cvv2_response_code);
         $cvv2_response_order_note = __('Card Security Code Result', 'paypal-for-woocommerce');
         $cvv2_response_order_note .= "\n";
         $cvv2_response_order_note .= $cvv2_response_code;
         $cvv2_response_order_note .= $cvv2_response_message != '' ? ' - ' . $cvv2_response_message : '';
         $order->add_order_note($cvv2_response_order_note);
         // Payment complete
         $order->payment_complete($PayPalResult['TRANSACTIONID']);
         // Remove cart
         WC()->cart->empty_cart();
         // Return thank you page redirect
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
     } else {
         // Get error message
         $error_code = isset($PayPalResult['ERRORS'][0]['L_ERRORCODE']) ? $PayPalResult['ERRORS'][0]['L_ERRORCODE'] : '';
         $long_message = isset($PayPalResult['ERRORS'][0]['L_LONGMESSAGE']) ? $PayPalResult['ERRORS'][0]['L_LONGMESSAGE'] : '';
         $error_message = $error_code . '-' . $long_message;
         // Notice admin if has any issue from PayPal
         if ($this->error_email_notify) {
             $admin_email = get_option("admin_email");
             $message = __("DoDirectPayment API call failed.", "paypal-for-woocommerce") . "\n\n";
             $message .= __('Error Code: ', 'paypal-for-woocommerce') . $error_code . "\n";
             $message .= __('Detailed Error Message: ', 'paypal-for-woocommerce') . $long_message . "\n";
             $message .= __('Order ID: ') . $order->id . "\n";
             $message .= __('Customer Name: ') . $order->billing_first_name . ' ' . $order->billing_last_name . "\n";
             $message .= __('Customer Email: ') . $order->billing_email . "\n";
             $pc_error_email_message = apply_filters('angelleye_pc_error_email_notify_message', $message, $error_code, $long_message);
             $pc_error_email_subject = apply_filters('angelleye_pc_error_email_notify_subject', "PayPal Pro Error Notification", $error_code, $long_message);
             wp_mail($admin_email, $pc_error_email_subject, $pc_error_email_message);
         }
         if ($this->debug) {
             $this->log->add('paypal-pro', 'Error ' . print_r($PayPalResult['ERRORS'], true));
         }
         $order->update_status('failed', sprintf(__('PayPal Pro payment failed (Correlation ID: %s). Payment was rejected due to an error: %s', 'paypal-for-woocommerce'), $PayPalResult['CORRELATIONID'], '(' . $PayPalResult['L_ERRORCODE0'] . ') ' . '"' . $error_message . '"'));
         // Generate error message based on Error Display Type setting
         if ($this->error_display_type == 'detailed') {
             $pc_display_type_error = __($error_message, 'paypal-for-woocommerce');
             $pc_display_type_notice = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $error_message;
         } else {
             $pc_display_type_error = __('There was a problem connecting to the payment gateway.', 'paypal-for-woocommerce');
             $pc_display_type_notice = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $error_message;
         }
         $pc_display_type_error = apply_filters('angelleye_pc_display_type_error', $pc_display_type_error, $error_code, $long_message);
         $pc_display_type_notice = apply_filters('angelleye_pc_display_type_notice', $pc_display_type_notice, $error_code, $long_message);
         wc_add_notice($pc_display_type_notice, "error");
         throw new Exception($pc_display_type_error);
         return;
     }
 }
 /**
  * do_payment
  *
  * Makes the request to PayPal's DoDirectPayment API
  *
  * @access public
  * @param mixed $order
  * @param mixed $card_number
  * @param mixed $card_type
  * @param mixed $card_exp_month
  * @param mixed $card_exp_year
  * @param mixed $card_csc
  * @param string $centinelPAResStatus (default: '')
  * @param string $centinelEnrolled (default: '')
  * @param string $centinelCavv (default: '')
  * @param string $centinelEciFlag (default: '')
  * @param string $centinelXid (default: '')
  * @return void
  */
 function do_payment($order, $card_number, $card_type, $card_exp_month, $card_exp_year, $card_csc, $centinelPAResStatus = '', $centinelEnrolled = '', $centinelCavv = '', $centinelEciFlag = '', $centinelXid = '')
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         $pc_session_expired_error = apply_filters('angelleye_pc_session_expired_error', sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'));
         wc_add_notice($pc_session_expired_error, "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once '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);
     if (empty($GLOBALS['wp_rewrite'])) {
         $GLOBALS['wp_rewrite'] = new WP_Rewrite();
     }
     $card_exp = $card_exp_month . $card_exp_year;
     /**
      * Generate PayPal request
      */
     $DPFields = array('paymentaction' => $this->payment_action == 'Authorization' ? 'Auth' : 'Sale', 'ipaddress' => $this->get_user_ip(), 'returnfmfdetails' => '');
     $CCDetails = array('creditcardtype' => $card_type, 'acct' => $card_number, 'expdate' => $card_exp, 'cvv2' => $card_csc, 'startdate' => '', 'issuenumber' => '');
     $PayerInfo = array('email' => $order->billing_email, 'firstname' => $order->billing_first_name, 'lastname' => $order->billing_last_name);
     $BillingAddress = array('street' => $order->billing_address_1, 'street2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'countrycode' => $order->billing_country, 'zip' => $order->billing_postcode, 'phonenum' => $order->billing_phone);
     $ShippingAddress = array('shiptoname' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'shiptostreet' => $order->shipping_address_1, 'shiptostreet2' => $order->shipping_address_2, 'shiptocity' => $order->shipping_city, 'shiptostate' => $order->shipping_state, 'shiptozip' => $order->shipping_postcode, 'shiptocountry' => $order->shipping_country, 'shiptophonenum' => $order->shipping_phone);
     $PaymentDetails = array('amt' => number_format($order->get_total(), 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'insuranceamt' => '', 'shipdiscamt' => '0.00', 'handlingamt' => '0.00', 'desc' => '', 'custom' => $order->customer_note ? wptexturize($order->customer_note) : '', 'invnum' => $invoice_number = $this->invoice_id_prefix . preg_replace("/[^0-9,.]/", "", $order->id), 'notifyurl' => '', 'recurring' => '');
     $OrderItems = array();
     $item_loop = 0;
     if (sizeof($order->get_items()) > 0) {
         $ITEMAMT = $TAXAMT = 0;
         $inc_tax = get_option('woocommerce_prices_include_tax') == 'yes' ? true : false;
         foreach ($order->get_items() as $item) {
             $_product = $order->get_product_from_item($item);
             if ($item['qty']) {
                 $sku = $_product->get_sku();
                 if ($_product->product_type == 'variation') {
                     if (empty($sku)) {
                         $sku = $_product->parent->get_sku();
                     }
                     //$this->log->add('paypal-pro', print_r($item['item_meta'], true));
                     $item_meta = new WC_Order_Item_Meta($item['item_meta']);
                     $meta = $item_meta->display(true, true);
                     $item['name'] = html_entity_decode($item['name'], ENT_NOQUOTES, 'UTF-8');
                     if (!empty($meta)) {
                         $item['name'] .= " - " . str_replace(", \n", " - ", $meta);
                     }
                 }
                 $Item = array('l_name' => $item['name'], 'l_desc' => '', 'l_amt' => round($item['line_subtotal'] / $item['qty'], 2), 'l_number' => $sku, 'l_qty' => $item['qty'], 'l_taxamt' => '', 'l_ebayitemnumber' => '', 'l_ebayitemauctiontxnid' => '', 'l_ebayitemorderid' => '');
                 array_push($OrderItems, $Item);
                 $ITEMAMT += round($item['line_subtotal'] / $item['qty'], 2) * $item['qty'];
                 $item_loop++;
             }
         }
         if (!$this->is_wc_version_greater_2_3()) {
             //Cart Discount
             if ($order->get_cart_discount() > 0) {
                 foreach (WC()->cart->get_coupons('cart') as $code => $coupon) {
                     $Item = array('l_name' => 'Cart Discount', 'l_desc' => '', 'l_amt' => '-' . WC()->cart->coupon_discount_amounts[$code], 'l_number' => $code, 'l_qty' => '1', 'l_taxamt' => '', 'l_ebayitemnumber' => '', 'l_ebayitemauctiontxnid' => '', 'l_ebayitemorderid' => '');
                     array_push($OrderItems, $Item);
                 }
                 $ITEMAMT = $ITEMAMT - $order->get_cart_discount();
             }
             //Order Discount
             if ($order->get_order_discount() > 0) {
                 foreach (WC()->cart->get_coupons('order') as $code => $coupon) {
                     $Item = array('l_name' => 'Order Discount', 'l_desc' => '', 'l_amt' => '-' . WC()->cart->coupon_discount_amounts[$code], 'l_number' => $code, 'l_qty' => '1', 'l_taxamt' => '', 'l_ebayitemnumber' => '', 'l_ebayitemauctiontxnid' => '', 'l_ebayitemorderid' => '');
                     array_push($OrderItems, $Item);
                 }
                 $ITEMAMT = $ITEMAMT - $order->get_order_discount();
             }
         } else {
             if ($order->get_total_discount() > 0) {
                 $Item = array('name' => 'Total Discount', 'qty' => 1, 'amt' => -number_format($order->get_total_discount(), 2, '.', ''));
                 array_push($OrderItems, $Item);
                 $ITEMAMT -= number_format($order->get_total_discount(), 2, '.', '');
             }
         }
         /**
          * Get shipping and tax.
          */
         if (get_option('woocommerce_prices_include_tax') == 'yes') {
             $shipping = $order->get_total_shipping() + $order->get_shipping_tax();
             $tax = 0;
         } else {
             $shipping = $order->get_total_shipping();
             $tax = $order->get_total_tax();
         }
         if ('yes' === get_option('woocommerce_calc_taxes') && 'yes' === get_option('woocommerce_prices_include_tax')) {
             $tax = $order->get_total_tax();
         }
         if ($tax > 0) {
             $PaymentDetails['taxamt'] = number_format($tax, 2, '.', '');
             // Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax.
         }
         if ($shipping > 0) {
             $PaymentDetails['shippingamt'] = number_format($shipping, 2, '.', '');
             // Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
         }
     }
     /**
      * Add custom Woo cart fees as line items
      */
     $item_loop = 0;
     foreach (WC()->cart->get_fees() as $fee) {
         $Item = array('name' => $fee->name, 'desc' => '', 'amt' => number_format($fee->amount, 2, '.', ''), 'number' => $fee->id, 'qty' => 1, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
         array_push($OrderItems, $Item);
         $ITEMAMT += $fee->amount * $Item['qty'];
         $item_loop++;
     }
     if (!$this->send_items) {
         $OrderItems = array();
         $PaymentDetails['itemamt'] = number_format($ITEMAMT, 2, '.', '');
         // Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
     } else {
         $PaymentDetails['itemamt'] = number_format($ITEMAMT, 2, '.', '');
         // Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
     }
     /**
      * 3D Secure Params
      */
     if ($this->enable_3dsecure) {
         $Secure3D = array('authstatus3d' => $centinelPAResStatus, 'mpivendor3ds' => $centinelEnrolled, 'cavv' => $centinelCavv, 'eci3ds' => $centinelEciFlag, 'xid' => $centinelXid);
     } else {
         $Secure3D = array();
     }
     $PayPalRequestData = array('DPFields' => $DPFields, 'CCDetails' => $CCDetails, 'PayerInfo' => $PayerInfo, 'BillingAddress' => $BillingAddress, 'ShippingAddress' => $ShippingAddress, 'PaymentDetails' => $PaymentDetails, 'OrderItems' => $OrderItems, 'Secure3D' => $Secure3D);
     if ($this->debug) {
         $log = $PayPalRequestData;
         $log['CCDetails']['acct'] = '****';
         $log['CCDetails']['cvv2'] = '****';
         $this->log->add('paypal-pro', 'Do payment request ' . print_r($log, true));
     }
     // Rounding amendment
     if (trim(number_format(WC()->cart->total, 2, '.', '')) !== trim(number_format($ITEMAMT, 2, '.', '') + number_format($tax, 2, '.', '') + number_format($shipping, 2, '.', ''))) {
         $diffrence_amount = $this->get_diffrent(WC()->cart->total, $ITEMAMT + $tax + number_format($shipping, 2, '.', ''));
         if ($shipping > 0) {
             $PayPalRequestData['PaymentDetails']['shippingamt'] = number_format($shipping + $diffrence_amount, 2, '.', '');
         } elseif ($tax > 0) {
             $PayPalRequestData['PaymentDetails']['taxamt'] = number_format($tax + $diffrence_amount, 2, '.', '');
         } else {
             $PayPalRequestData['PaymentDetails']['itemamt'] = number_format($PayPalRequestData['PaymentDetails']['itemamt'] + $diffrence_amount, 2);
         }
     }
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
     if ($this->debug) {
         $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
         $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
         $this->log->add('paypal-pro', 'Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
         $this->log->add('paypal-pro', 'Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     }
     if (empty($PayPalResult['RAWRESPONSE'])) {
         $pc_empty_response = apply_filters('angelleye_pc_empty_response', __('Empty PayPal response.', 'paypal-for-woocommerce'), $PayPalResult);
         throw new Exception($pc_empty_response);
     }
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         // Add order note
         $order->add_order_note(sprintf(__('PayPal Pro payment completed (Transaction ID: %s, Correlation ID: %s)', 'paypal-for-woocommerce'), $PayPalResult['TRANSACTIONID'], $PayPalResult['CORRELATIONID']));
         //$order->add_order_note("PayPal Results: ".print_r($PayPalResult,true));
         /**
          * Add order notes for AVS result
          */
         $avs_response_code = isset($PayPalResult['AVSCODE']) ? $PayPalResult['AVSCODE'] : '';
         $avs_response_message = $PayPal->GetAVSCodeMessage($avs_response_code);
         $avs_response_order_note = __('Address Verification Result', 'paypal-for-woocommerce');
         $avs_response_order_note .= "\n";
         $avs_response_order_note .= $avs_response_code;
         $avs_response_order_note .= $avs_response_message != '' ? ' - ' . $avs_response_message : '';
         $order->add_order_note($avs_response_order_note);
         /**
          * Add order notes for CVV2 result
          */
         $cvv2_response_code = isset($PayPalResult['CVV2MATCH']) ? $PayPalResult['CVV2MATCH'] : '';
         $cvv2_response_message = $PayPal->GetCVV2CodeMessage($cvv2_response_code);
         $cvv2_response_order_note = __('Card Security Code Result', 'paypal-for-woocommerce');
         $cvv2_response_order_note .= "\n";
         $cvv2_response_order_note .= $cvv2_response_code;
         $cvv2_response_order_note .= $cvv2_response_message != '' ? ' - ' . $cvv2_response_message : '';
         $order->add_order_note($cvv2_response_order_note);
         // Payment complete
         $order->payment_complete($PayPalResult['TRANSACTIONID']);
         // Remove cart
         WC()->cart->empty_cart();
         // Return thank you page redirect
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
     } else {
         // Get error message
         $error_code = isset($PayPalResult['ERRORS'][0]['L_ERRORCODE']) ? $PayPalResult['ERRORS'][0]['L_ERRORCODE'] : '';
         $long_message = isset($PayPalResult['ERRORS'][0]['L_LONGMESSAGE']) ? $PayPalResult['ERRORS'][0]['L_LONGMESSAGE'] : '';
         $error_message = $error_code . '-' . $long_message;
         // Notice admin if has any issue from PayPal
         if ($this->error_email_notify) {
             $admin_email = get_option("admin_email");
             $message = __("DoDirectPayment API call failed.", "paypal-for-woocommerce") . "\n\n";
             $message .= __('Error Code: ', 'paypal-for-woocommerce') . $error_code . "\n";
             $message .= __('Detailed Error Message: ', 'paypal-for-woocommerce') . $long_message . "\n";
             $message .= __('Order ID: ') . $order->id . "\n";
             $message .= __('Customer Name: ') . $order->billing_first_name . ' ' . $order->billing_last_name . "\n";
             $message .= __('Customer Email: ') . $order->billing_email . "\n";
             $pc_error_email_message = apply_filters('angelleye_pc_error_email_notify_message', $message, $error_code, $long_message);
             $pc_error_email_subject = apply_filters('angelleye_pc_error_email_notify_subject', "PayPal Pro Error Notification", $error_code, $long_message);
             wp_mail($admin_email, $pc_error_email_subject, $pc_error_email_message);
         }
         if ($this->debug) {
             $this->log->add('paypal-pro', 'Error ' . print_r($PayPalResult['ERRORS'], true));
         }
         $order->update_status('failed', sprintf(__('PayPal Pro payment failed (Correlation ID: %s). Payment was rejected due to an error: %s', 'paypal-for-woocommerce'), $PayPalResult['CORRELATIONID'], '(' . $PayPalResult['L_ERRORCODE0'] . ') ' . '"' . $error_message . '"'));
         // Generate error message based on Error Display Type setting
         if ($this->error_display_type == 'detailed') {
             $pc_display_type_error = __($error_message, 'paypal-for-woocommerce');
             $pc_display_type_notice = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $error_message;
         } else {
             $pc_display_type_error = __('There was a problem connecting to the payment gateway.', 'paypal-for-woocommerce');
             $pc_display_type_notice = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $error_message;
         }
         $pc_display_type_error = apply_filters('angelleye_pc_display_type_error', $pc_display_type_error, $error_code, $long_message);
         $pc_display_type_notice = apply_filters('angelleye_pc_display_type_notice', $pc_display_type_notice, $error_code, $long_message);
         wc_add_notice($pc_display_type_notice, "error");
         throw new Exception($pc_display_type_error);
         return;
     }
 }