/**
 * Copy the billing, shipping or all addresses from one order to another (including custom order types, like the
 * WC_Subscription order type).
 *
 * @param WC_Order $to_order The WC_Order object to copy the address to.
 * @param WC_Order $from_order The WC_Order object to copy the address from.
 * @param string $address_type The address type to copy, can be 'shipping', 'billing' or 'all'
 * @return WC_Order The WC_Order object with the new address set.
 * @since  2.0
 */
function wcs_copy_order_address($from_order, $to_order, $address_type = 'all')
{
    if (in_array($address_type, array('shipping', 'all'))) {
        $to_order->set_address(array('first_name' => $from_order->shipping_first_name, 'last_name' => $from_order->shipping_last_name, 'company' => $from_order->shipping_company, 'address_1' => $from_order->shipping_address_1, 'address_2' => $from_order->shipping_address_2, 'city' => $from_order->shipping_city, 'state' => $from_order->shipping_state, 'postcode' => $from_order->shipping_postcode, 'country' => $from_order->shipping_country), 'shipping');
    }
    if (in_array($address_type, array('billing', 'all'))) {
        $to_order->set_address(array('first_name' => $from_order->billing_first_name, 'last_name' => $from_order->billing_last_name, 'company' => $from_order->billing_company, 'address_1' => $from_order->billing_address_1, 'address_2' => $from_order->billing_address_2, 'city' => $from_order->billing_city, 'state' => $from_order->billing_state, 'postcode' => $from_order->billing_postcode, 'country' => $from_order->billing_country, 'email' => $from_order->billing_email, 'phone' => $from_order->billing_phone), 'billing');
    }
    return apply_filters('woocommerce_subscriptions_copy_order_address', $to_order, $from_order, $address_type);
}
 /**
  * Update address.
  *
  * @param WC_Order $order
  * @param array $posted
  * @param string $type
  */
 protected function update_address($order, $posted, $type = 'billing')
 {
     $fields = $order->get_address($type);
     foreach (array_keys($fields) as $field) {
         if (isset($posted[$field])) {
             $fields[$field] = $posted[$field];
         }
     }
     // Set address.
     $order->set_address($fields, $type);
     // Update user meta.
     if ($order->get_user_id()) {
         foreach ($fields as $key => $value) {
             update_user_meta($order->get_user_id(), $type . '_' . $key, $value);
         }
     }
 }
 /**
  * Helper method to set/update the billing & shipping addresses for an order.
  *
  * @since 2.5.0
  * @param WC_Order $order
  * @param array $data
  */
 protected function set_order_addresses($order, $data)
 {
     $address_fields = array('first_name', 'last_name', 'company', 'email', 'phone', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country');
     $billing_address = $shipping_address = array();
     // billing address.
     if (isset($data['billing_address']) && is_array($data['billing_address'])) {
         foreach ($address_fields as $field) {
             if (isset($data['billing_address'][$field])) {
                 $billing_address[$field] = wc_clean($data['billing_address'][$field]);
             }
         }
         unset($address_fields['email']);
         unset($address_fields['phone']);
     }
     // shipping address.
     if (isset($data['shipping_address']) && is_array($data['shipping_address'])) {
         foreach ($address_fields as $field) {
             if (isset($data['shipping_address'][$field])) {
                 $shipping_address[$field] = wc_clean($data['shipping_address'][$field]);
             }
         }
     }
     $order->set_address($billing_address, 'billing');
     $order->set_address($shipping_address, 'shipping');
     // update user meta
     if ($order->get_user_id()) {
         foreach ($billing_address as $key => $value) {
             update_user_meta($order->get_user_id(), 'billing_' . $key, $value);
         }
         foreach ($shipping_address as $key => $value) {
             update_user_meta($order->get_user_id(), 'shipping_' . $key, $value);
         }
     }
 }
//Add callback to Hyggligs system to validate Order
require '../../../../wp-load.php';
$store_Post = $_POST;
$order_id = $_POST['orderReference'];
$order = new WC_Order($order_id);
$options = get_option('woocommerce_hygglig_checkout_settings');
$log = new WC_Logger();
//Live or test
if ($options['testmode'] == 'yes') {
    $url = "http://sandbox.hygglig.com/";
} else {
    $url = "https://www.hygglig.com/";
}
// Billing
if (strlen($order->get_formatted_billing_address()) < 10) {
    $order->set_address(array('first_name' => $_POST['firstName'], 'last_name' => $_POST['lastName'], 'address_1' => $_POST['address'], 'city' => $_POST['city'], 'postcode' => $_POST['postalCode'], 'email' => $_POST['email'], 'phone' => $_POST['phoneNumber']));
}
// Shipping
if (strlen($order->get_formatted_shipping_address()) < 10) {
    $order->set_address(array('first_name' => $_POST['firstName'], 'last_name' => $_POST['lastName'], 'address_1' => $_POST['address'], 'city' => $_POST['city'], 'postcode' => $_POST['postalCode']), 'shipping');
}
$order->payment_complete($_POST['orderNumber']);
update_post_meta($order_id, '_payment_method', 'Hygglig');
update_post_meta($order_id, '_payment_method_title', 'Hygglig');
if ($options['debug'] == 'yes') {
    $log->add('marginalen', "Payment for Order #" . $order_id . " completed. Stocks reduced.");
}
// Store user id in order so the user can keep track of track it in My account
if (email_exists($order->billing_email)) {
    if ($options['debug'] == 'yes') {
        $log->add('marginalen', 'Billing email: ' . $order->billing_email);
 public function update_cart_by_woocart($order_id, $data)
 {
     global $wp;
     global $wpdb, $woocommerce, $pwa;
     $xml = simplexml_load_string($data);
     $order = new WC_Order($order_id);
     $billing_address = array('first_name' => (string) $xml->ProcessedOrder->BuyerInfo->BuyerName, 'last_name' => '', 'company' => '', 'email' => (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress, 'phone' => '', 'address_1' => '', 'address_2' => '', 'city' => '', 'state' => '', 'postcode' => '', 'country' => '');
     $shipping_address = array('first_name' => (string) $xml->ProcessedOrder->ShippingAddress->Name, 'last_name' => '', 'company' => '', 'email' => '', 'phone' => '', 'address_1' => (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne, 'address_2' => (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo, 'city' => (string) $xml->ProcessedOrder->ShippingAddress->City, 'state' => (string) $xml->ProcessedOrder->ShippingAddress->State, 'postcode' => (string) $xml->ProcessedOrder->ShippingAddress->PostalCode, 'country' => (string) $xml->ProcessedOrder->ShippingAddress->CountryCode);
     $order->set_address($shipping_address, 'shipping');
     add_post_meta($order_id, '_payment_method', 'pwa');
     add_post_meta($order_id, '_payment_method_title', 'Pay with Amazon');
     $total_amount = 0;
     $subtotal_amount = 0;
     $shipping_amount = 0;
     $ClientRequestId = 0;
     try {
         foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
             // XML DATA
             $ClientRequestId = (int) $item->ClientRequestId;
             foreach ($item->ItemCharges->Component as $amount_type) {
                 $item_charge_type = (string) $amount_type->Type;
                 if ($item_charge_type == 'Shipping') {
                     $Shipping = (string) $amount_type->Charge->Amount;
                 }
             }
             $shipping_amount = $shipping_amount + $Shipping;
         }
     } catch (Exception $e) {
         $param['message'] = 'IOPN Notifications : Caught exception : ' . $e->getMessage() . '.';
         $this->generate_log($param);
     }
     if ($ClientRequestId == 0) {
         $order->set_address($billing_address, 'billing');
     }
     // CART DATA
     $cartdata = '';
     $user_id = 0;
     $prefix = $wpdb->prefix;
     $carts = $wpdb->get_results("SELECT * FROM `" . $prefix . "pwa_before_cart_save` WHERE id = {$ClientRequestId} ");
     foreach ($carts as $key => $value) {
         $cartdata = maybe_unserialize($value->cart_data);
         $user_id = $value->user_id;
     }
     update_post_meta($order_id, '_customer_user', $user_id);
     // ENTRY
     try {
         foreach ($cartdata->cart_contents as $key => $value) {
             $product_id = $value['product_id'];
             $cart_product = get_product($product_id);
             $product = array();
             $product['order_item_name'] = $cart_product->get_title();
             $product['order_item_type'] = 'line_item';
             $order_item_id = wc_add_order_item($order_id, $product);
             wc_add_order_item_meta($order_item_id, '_qty', $value['quantity']);
             wc_add_order_item_meta($order_item_id, '_product_id', $product_id);
             wc_add_order_item_meta($order_item_id, '_line_total', $value['line_total']);
             wc_add_order_item_meta($order_item_id, '_line_subtotal', $value['line_subtotal']);
             wc_add_order_item_meta($order_item_id, '_line_tax', $value['line_tax']);
             wc_add_order_item_meta($order_item_id, '_line_subtotal_tax', $value['line_subtotal_tax']);
             wc_add_order_item_meta($order_item_id, '_line_tax_data', maybe_serialize($value['line_tax_data']));
             foreach ($value['line_tax_data']['total'] as $tax_rate_id => $tax_data) {
                 $tax_class = $wpdb->get_results("SELECT * FROM `" . $prefix . "woocommerce_tax_rates` WHERE tax_rate_id = {$tax_rate_id} ");
                 wc_add_order_item_meta($order_item_id, '_tax_class', $tax_class[0]->tax_rate_class);
             }
             if ($value['variation_id'] > 0) {
                 wc_add_order_item_meta($order_item_id, '_variation_id', $value['variation_id']);
             }
             foreach ($value['variation'] as $attrib_key => $attrib_value) {
                 $meta_key = str_replace('attribute_', '', $attrib_key);
                 wc_add_order_item_meta($order_item_id, $meta_key, $attrib_value);
             }
             $this->reduce_order_stock($product_id, $value['quantity']);
             $total_amount = $total_amount + $value['line_total'] + $value['line_tax'];
             $subtotal_amount = $subtotal_amount + $value['line_subtotal'];
         }
     } catch (Exception $e) {
         $param['message'] = 'IOPN Notifications : Caught exception : ' . $e->getMessage() . '.';
         $this->generate_log($param);
     }
     add_post_meta($order_id, '_order_total', $total_amount + $shipping_amount);
     add_post_meta($order_id, '_order_shipping', $shipping_amount);
     add_post_meta($order_id, '_cart_discount', $cartdata->discount_cart);
     add_post_meta($order_id, '_cart_discount_tax', $cartdata->discount_cart_tax);
     add_post_meta($order_id, '_order_tax', $cartdata->tax_total);
     $shipitem = array();
     $shipitem['order_item_name'] = (string) $xml->ProcessedOrder->ShippingServiceLevel;
     $shipitem['order_item_type'] = 'shipping';
     $order_shipping_id = wc_add_order_item($order_id, $shipitem);
     wc_add_order_item_meta($order_shipping_id, 'method_id', str_replace(' ', '_', strtolower((string) $xml->ProcessedOrder->ShippingServiceLevel)));
     wc_add_order_item_meta($order_shipping_id, 'cost', $shipping_amount);
     if (!empty($cartdata->taxes)) {
         foreach ($cartdata->taxes as $key => $value) {
             $order->add_tax($key, $value);
         }
     }
     if (!empty($cartdata->applied_coupons)) {
         foreach ($cartdata->applied_coupons as $key => $value) {
             $order->add_coupon($value, $cartdata->coupon_discount_amounts[$value], $cartdata->coupon_discount_tax_amounts[$value]);
         }
     }
     // Send notification mails to seller and customer for order
     $mail_class = new WC_Emails();
     $mail_class->emails['WC_Email_New_Order']->trigger($order_id);
     // Acknowledge the order in seller central using MWS FEED API
     $pwa->pwa_acknowledge_feed($order_id);
 }
 public function update_cart_by_xml($order_id, $orderdetail)
 {
     global $wpdb, $woocommerce;
     $AmazonOrderID = (string) $orderdetail->OrderReport->AmazonOrderID;
     $order = new WC_Order($order_id);
     $billing_address = array('first_name' => (string) $orderdetail->OrderReport->BillingData->BuyerName, 'last_name' => '', 'company' => '', 'email' => (string) $orderdetail->OrderReport->BillingData->BuyerEmailAddress, 'phone' => (string) $orderdetail->OrderReport->BillingData->BuyerPhoneNumber, 'address_1' => '', 'address_2' => '', 'city' => '', 'state' => '', 'postcode' => '', 'country' => '');
     $shipping_address = array('first_name' => (string) $orderdetail->OrderReport->FulfillmentData->Address->Name, 'last_name' => '', 'company' => '', 'email' => '', 'phone' => (string) $orderdetail->OrderReport->FulfillmentData->Address->PhoneNumber, 'address_1' => (string) $orderdetail->OrderReport->FulfillmentData->Address->AddressFieldOne, 'address_2' => (string) $orderdetail->OrderReport->FulfillmentData->Address->AddressFieldTwo, 'city' => (string) $orderdetail->OrderReport->FulfillmentData->Address->City, 'state' => (string) $orderdetail->OrderReport->FulfillmentData->Address->State, 'postcode' => (string) $orderdetail->OrderReport->FulfillmentData->Address->PostalCode, 'country' => (string) $orderdetail->OrderReport->FulfillmentData->Address->CountryCode);
     $order->set_address($shipping_address, 'shipping');
     add_post_meta($order_id, '_payment_method', 'pwa');
     add_post_meta($order_id, '_payment_method_title', 'Pay with Amazon');
     $total_amount = 0;
     $shipping_amount = 0;
     $total_promo = 0;
     foreach ($orderdetail->OrderReport->Item as $item) {
         $SKU = (string) $item->SKU;
         $Title = (string) $item->Title;
         $Quantity = (int) $item->Quantity;
         foreach ($item->ItemPrice->Component as $amount_type) {
             $item_charge_type = (string) $amount_type->Type;
             if ($item_charge_type == 'Principal') {
                 $Principal = (double) $amount_type->Amount;
             }
             if ($item_charge_type == 'Shipping') {
                 $Shipping = (double) $amount_type->Amount;
             }
             if ($item_charge_type == 'Tax') {
                 $Tax = (double) $amount_type->Amount;
             }
             if ($item_charge_type == 'ShippingTax') {
                 $ShippingTax = (double) $amount_type->Amount;
             }
         }
         if (!empty($item->Promotion)) {
             foreach ($item->Promotion->Component as $promotion_amount_type) {
                 $promotion_type = (string) $promotion_amount_type->Type;
                 if ($promotion_type == 'Shipping') {
                     $Shipping_Promotions = (double) $promotion_amount_type->Amount;
                 }
                 if ($promotion_type == 'Principal') {
                     $Principal_Promotions = (double) $promotion_amount_type->Amount;
                 }
             }
         }
         $product = array();
         $product['order_item_name'] = $Title;
         $product['order_item_type'] = 'line_item';
         $order_item_id = wc_add_order_item($order_id, $product);
         wc_add_order_item_meta($order_item_id, '_qty', $Quantity);
         wc_add_order_item_meta($order_item_id, '_line_total', $Principal + $Shipping_Promotions + $Principal_Promotions);
         wc_add_order_item_meta($order_item_id, '_line_subtotal', $Principal);
         wc_add_order_item_meta($order_item_id, '_line_subtotal_tax', 0);
         wc_add_order_item_meta($order_item_id, '_line_tax', 0);
         /*
          * Total Item Charge = (Principal - PrincipalPromo) + (Shipping - ShippingPromo) + Tax + ShippingTax
          */
         $total_amount += $Principal + $Principal_Promotions + ($Shipping + $Shipping_Promotions);
         $shipping_amount += $Shipping + $Shipping_Promotions;
         $total_promo += $Principal_Promotions + $Shipping_Promotions;
         $ClientRequestId = 0;
         foreach ($item->CustomizationInfo as $info) {
             $info_type = (string) $info->Type;
             if ($info_type == 'url') {
                 $info_array = explode(',', $info->Data);
                 $customerId_array = explode('=', $info_array[0]);
                 $ClientRequestId = $customerId_array[1];
             }
         }
         if ($ClientRequestId == 0) {
             $order->set_address($billing_address, 'billing');
         } else {
             if (UPDATE_ODER_FROM == 'xmlcart') {
                 unset($billing_address['email']);
                 $order->set_address($billing_address, 'billing');
                 update_post_meta($order_id, '_customer_user', $ClientRequestId);
             }
             //update_post_meta($order_id, '_customer_user' , $ClientRequestId);
         }
         $product = $wpdb->get_results("select post_id from {$wpdb->postmeta} where meta_key = '_sku' and meta_value = '{$SKU}' ");
         if (!empty($product)) {
             $product_id = $product[0]->post_id;
             if ($product_id != '') {
                 wc_add_order_item_meta($order_item_id, '_product_id', $product_id);
                 $this->reduce_order_stock($product_id, $Quantity);
             }
         }
     }
     add_post_meta($order_id, '_order_total', $total_amount);
     add_post_meta($order_id, '_order_shipping', $shipping_amount);
     add_post_meta($order_id, '_cart_discount', abs($total_promo));
     $shipitem = array();
     $shipitem['order_item_name'] = (string) $orderdetail->OrderReport->FulfillmentData->FulfillmentServiceLevel;
     $shipitem['order_item_type'] = 'shipping';
     $order_shipping_id = wc_add_order_item($order_id, $shipitem);
     wc_add_order_item_meta($order_shipping_id, 'method_id', str_replace(' ', '_', strtolower((string) $orderdetail->OrderReport->FulfillmentData->FulfillmentServiceLevel)));
     wc_add_order_item_meta($order_shipping_id, 'cost', $shipping_amount);
     // Send notification mails to seller and customer for order
     //$mail_class = new WC_Emails();
     //$mail_class->emails['WC_Email_New_Order']->trigger($order_id);
     // Acknowledge the order in seller central using MWS FEED API
     $param['AmazonOrderID'] = $AmazonOrderID;
     $param['MerchantOrderID'] = $order_id;
     $param['StatusCode'] = 'Success';
     $this->submit_acknowledge_feed($param);
 }
 /**
  * Update order data
  *
  * Based on WC_API_Customers::update_customer_data()
  *
  * @since 3.0.0
  * @param \WC_Order $order
  * @param array $data
  * @param array $options
  */
 private function update_order_data(WC_Order $order, $data, $options)
 {
     if (isset($data['date']) && $data['date']) {
         wp_update_post(array('ID' => $order->id, 'post_date' => date('Y-m-d H:i:s', $data['date'])));
     }
     $merging = $options['merge'] && isset($data['id']) && $data['id'];
     $this->process_terms($order->id, $data['terms']);
     // set order addresses
     $order->set_address($data['billing_address'], 'billing');
     $order->set_address($data['shipping_address'], 'shipping');
     // clear any previously set refunded order item ids
     $this->refunded_item_order_ids = array();
     // set order lines
     foreach ($this->line_types as $line_type => $line) {
         // don't set lines if they're empty. This ensures partial updates/merges
         // are supported and won't wipe out order lines
         if (!empty($data[$line]) && is_array($data[$line])) {
             $this->process_items($order, $data[$line], $line_type, $merging);
         }
     }
     // set order currency
     if (isset($data['currency'])) {
         update_post_meta($order->id, '_order_currency', $data['currency']);
     }
     // grant downloadable product permissions
     if (isset($data['download_permissions_granted']) && $data['download_permissions_granted']) {
         wc_downloadable_product_permissions($order->id);
     }
     // set order meta
     if (isset($data['order_meta']) && is_array($data['order_meta'])) {
         $this->set_order_meta($order->id, $data['order_meta']);
     }
     // set the paying customer flag on the user meta if applicable
     $paid_statuses = array('processing', 'completed', 'refunded');
     if ($data['customer_id'] && in_array($data['status'], $paid_statuses)) {
         update_user_meta($data['customer_id'], "paying_customer", 1);
     }
     // process refunds
     if (!empty($data['refunds'])) {
         // remove previous refunds
         foreach ($order->get_refunds() as $refund) {
             wc_delete_shop_order_transients($refund->id);
             wp_delete_post($refund->id, true);
         }
         foreach ($data['refunds'] as $refund_data) {
             // try mapping temp refunded item ids to real order item ids
             if (!empty($refund_data['line_items'])) {
                 foreach ($refund_data['line_items'] as $key => $refunded_item) {
                     if (isset($refunded_item['refunded_item_temp_id'])) {
                         $temp_id = $refunded_item['refunded_item_temp_id'];
                         // get the real order item id for this refunded itme
                         $order_item_id = $this->get_array_key_value($this->refunded_item_order_ids, $temp_id);
                         if ($order_item_id) {
                             $refund_data['line_items'][$order_item_id] = $refunded_item;
                             unset($refund_data['line_items'][$key]);
                         }
                     }
                 }
             }
             wc_create_refund(array('order_id' => $order->id, 'amount' => $refund_data['amount'], 'reason' => $refund_data['reason'], 'line_items' => $refund_data['line_items'], 'date' => $refund_data['date']));
         }
     }
     wc_delete_shop_order_transients($order->id);
     /**
      * Triggered after order data has been updated via CSV
      *
      * This will be triggered for both new and updated orders
      *
      * @since 3.0.0
      * @param int $id Order ID
      * @param array $data Order data
      * @param array $options Import options
      */
     do_action('wc_csv_import_suite_update_order_data', $order->id, $data, $options);
 }
 public function update_detail($order_id, $data)
 {
     global $wpdb, $woocommerce, $pwa;
     $xml = simplexml_load_string($data);
     $order = new WC_Order($order_id);
     $billing_address = array('phone' => (string) $xml->ProcessedOrder->ShippingAddress->PhoneNumber);
     $shipping_address = array('phone' => (string) $xml->ProcessedOrder->ShippingAddress->PhoneNumber);
     $order->set_address($billing_address, 'billing');
     $order->set_address($shipping_address, 'shipping');
 }