require_once '../includes/config.php';
require_once '../includes/paypal.class.php';
// Create PayPal object.
$PayPalConfig = array('Sandbox' => $sandbox, 'APIUsername' => $api_username, 'APIPassword' => $api_password, 'APISignature' => $api_signature);
$PayPal = new PayPal($PayPalConfig);
// Prepare request arrays
$SECFields = array('token' => '', 'maxamt' => '', 'returnurl' => '', 'cancelurl' => '', 'callback' => '', 'callbacktimeout' => '', 'callbackversion' => '', 'reqconfirmshipping' => '', 'noshipping' => '', 'allownote' => '', 'addroverride' => '', 'localecode' => '', 'pagestyle' => '', 'hdrimg' => '', 'hdrbordercolor' => '', 'hdrbackcolor' => '', 'payflowcolor' => '', 'skipdetails' => '', 'email' => '', 'solutiontype' => '', 'landingpage' => '', 'channeltype' => '', 'giropaysuccessurl' => '', 'giropaycancelurl' => '', 'banktxnpendingurl' => '', 'brandname' => '', 'customerservicenumber' => '', 'giftmessageenable' => '', 'giftreceiptenable' => '', 'giftwrapenable' => '', 'giftwrapname' => '', 'giftwrapamount' => '', 'buyeremailoptionenable' => '', 'surveyquestion' => '', 'surveyenable' => '', 'totaltype' => '', 'notetobuyer' => '', 'buyerid' => '', 'buyerusername' => '', 'buyerregistrationdate' => '', 'allowpushfunding' => '', 'taxidtype' => '', 'taxid' => '');
// 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' => '', 'currencycode' => '', 'itemamt' => '', 'shippingamt' => '', 'shippingdiscamt' => '', 'insuranceamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'taxamt' => '', 'desc' => '', 'custom' => '', 'invnum' => '', 'notifyurl' => '', 'shiptoname' => '', 'shiptostreet' => '', 'shiptostreet2' => '', 'shiptocity' => '', 'shiptostate' => '', 'shiptozip' => '', 'shiptocountrycode' => '', 'shiptophonenum' => '', 'notetext' => '', 'allowedpaymentmethod' => '', 'paymentaction' => '', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '');
$PaymentOrderItems = array();
$Item = array('name' => '', 'desc' => '', 'amt' => '', 'number' => '', 'qty' => '', 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
array_push($PaymentOrderItems, $Item);
$Payment['order_items'] = $PaymentOrderItems;
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);
$BillingAgreements = array();
$Item = array('l_billingtype' => '', 'l_billingagreementdescription' => '', 'l_paymenttype' => '', 'l_billingagreementcustom' => '');
array_push($BillingAgreements, $Item);
$PayPalRequestData = array('SECFields' => $SECFields, 'SurveyChoices' => $SurveyChoices, 'Payments' => $Payments, 'BuyerDetails' => $BuyerDetails, 'ShippingOptions' => $ShippingOptions, 'BillingAgreements' => $BillingAgreements);
// Pass data into class for processing with PayPal and load the response array into $PayPalResult
$PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData);
// Write the contents of the response array to the screen for demo purposes.
echo '<a href="' . $PayPalResult['REDIRECTURL'] . '">Click here to continue.</a><br /><br />';
echo '<pre />';
print_r($PayPalResult);
 /**
  * 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)
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href="%s">Return to homepage &rarr;</a>', 'wc-paypal-express'), home_url()), "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('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 PayPal($PayPalConfig);
     /*
      * Prepare PayPal request data.
      */
     $SECFields = array('token' => '', 'maxamt' => number_format($paymentAmount + $paymentAmount * 0.5, 2, '.', ''), 'returnurl' => urldecode($returnURL), 'cancelurl' => urldecode($cancelURL), 'callback' => '', 'callbacktimeout' => '', 'callbackversion' => '', 'reqconfirmshipping' => '', 'noshipping' => '', 'allownote' => '', 'addroverride' => '', 'localecode' => '', 'pagestyle' => '', 'hdrimg' => '', 'hdrbordercolor' => '', 'hdrbackcolor' => '', 'payflowcolor' => '', 'skipdetails' => '', 'email' => '', 'solutiontype' => $this->paypal_account_optional == 'yes' ? 'Sole' : '', 'landingpage' => $this->landing_page == 'login' ? 'Login' : 'Billing', 'channeltype' => '', 'giropaysuccessurl' => '', 'giropaycancelurl' => '', 'banktxnpendingurl' => '', 'brandname' => '', 'customerservicenumber' => '', 'giftmessageenable' => '', 'giftreceiptenable' => '', 'giftwrapenable' => '', 'giftwrapname' => '', 'giftwrapamount' => '', 'buyeremailoptionenable' => '', 'surveyquestion' => '', 'surveyenable' => '', 'totaltype' => '', 'notetobuyer' => '', 'buyerid' => '', 'buyerusername' => '', 'buyerregistrationdate' => '', 'allowpushfunding' => '', 'taxidtype' => '', 'taxid' => '');
     // Basic array of survey choices.  Nothing but the values should go in here.
     $SurveyChoices = array('Choice 1', 'Choice2', 'Choice3', 'etc');
     /*
      * Get tax amount.
      */
     if (get_option('woocommerce_prices_include_tax') == 'yes') {
         $shipping = WC()->cart->shipping_total + WC()->cart->shipping_tax_total;
         $tax = '0.00';
     } else {
         $shipping = WC()->cart->shipping_total;
         $tax = WC()->cart->get_taxes_total();
     }
     $Payments = array();
     $Payment = array('amt' => number_format(WC()->cart->total, 2, '.', ''), 'currencycode' => get_option('woocommerce_currency'), 'shippingamt' => number_format($shipping, 2, '.', ''), 'shippingdiscamt' => '', 'insuranceamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'taxamt' => $tax, 'desc' => '', 'custom' => '', 'invnum' => '', 'notifyurl' => '', 'shiptoname' => '', 'shiptostreet' => '', 'shiptostreet2' => '', 'shiptocity' => '', 'shiptostate' => '', 'shiptozip' => '', 'shiptocountrycode' => '', 'shiptophonenum' => '', 'notetext' => '', 'allowedpaymentmethod' => '', 'paymentaction' => 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '');
     $PaymentOrderItems = array();
     $ctr = $total_items = $total_discount = $total_tax = $order_total = 0;
     foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
         /*
          * Get product data from WooCommerce
          */
         $_product = $values['data'];
         $qty = absint($values['quantity']);
         $sku = $_product->get_sku();
         $values['name'] = html_entity_decode($_product->get_title(), ENT_NOQUOTES, 'UTF-8');
         /*
          * Append variation data to name.
          */
         if ($_product->product_type == 'variation') {
             $meta = WC()->cart->get_item_data($values, true);
             if (empty($sku)) {
                 $sku = $_product->parent->get_sku();
             }
             if (!empty($meta)) {
                 $values['name'] .= " - " . str_replace(", \n", " - ", $meta);
             }
         }
         /*
          * Set price based on tax option.
          */
         if (get_option('woocommerce_prices_include_tax') == 'yes') {
             $product_price = number_format($_product->get_price_including_tax(), 2, '.', '');
         } else {
             $product_price = number_format($_product->get_price_excluding_tax(), 2, '.', '');
         }
         $Item = array('name' => $values['name'], 'desc' => '', 'amt' => number_format($product_price, 2, '.', ''), 'number' => $sku, 'qty' => $qty, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
         array_push($PaymentOrderItems, $Item);
         $total_items += $product_price * $values['quantity'];
         $ctr++;
     }
     /*
      * Get discount(s)
      */
     if (WC()->cart->get_cart_discount_total()) {
         foreach (WC()->cart->get_coupons('cart') as $code => $coupon) {
             $Item = array('name' => 'Cart Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', ''));
             array_push($PaymentOrderItems, $Item);
         }
         $total_discount -= WC()->cart->get_cart_discount_total();
     }
     if (WC()->cart->get_order_discount_total()) {
         foreach (WC()->cart->get_coupons('order') as $code => $coupon) {
             $Item = array('name' => 'Order Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', ''));
             array_push($PaymentOrderItems, $Item);
         }
         $total_discount -= WC()->cart->get_order_discount_total();
     }
     /*
      * Now that all the order items are gathered, including discounts,
      * we'll push them back into the Payment.
      */
     $Payment['order_items'] = $PaymentOrderItems;
     /*
      * Now that we've looped and calculated item totals
      * we can fill in the ITEMAMT
      */
     $Payment['itemamt'] = $total_items + $total_discount;
     // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
     /*
      * 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);
     $BillingAgreements = array();
     $Item = array('l_billingtype' => '', 'l_billingagreementdescription' => '', 'l_paymenttype' => '', 'l_billingagreementcustom' => '');
     array_push($BillingAgreements, $Item);
     $PayPalRequestData = array('SECFields' => $SECFields, 'SurveyChoices' => $SurveyChoices, 'Payments' => $Payments);
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData);
     /*
      * Log API result
      */
     $this->add_log('Test Mode: ' . $this->testmode);
     $this->add_log('Endpoint: ' . $this->API_Endpoint);
     $this->add_log('Result: ' . print_r($PayPalResult, 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;
 }