/**
  * Add subscription related order item meta when a subscription product is added as an item to an order via Ajax.
  *
  * @param item_id int An order_item_id as returned by the insert statement of @see woocommerce_add_order_item()
  * @since 1.2.5
  * @version 1.4
  * @return void
  */
 public static function prefill_order_item_meta($item, $item_id)
 {
     $order_id = $_POST['order_id'];
     $product_id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
     if ($item_id && WC_Subscriptions_Product::is_subscription($product_id)) {
         $order = new WC_Order($order_id);
         $recurring_amount = WC_Subscriptions_Product::get_price($product_id);
         $sign_up_fee = WC_Subscriptions_Product::get_sign_up_fee($product_id);
         $free_trial_length = WC_Subscriptions_Product::get_trial_length($product_id);
         woocommerce_add_order_item_meta($item_id, '_subscription_period', WC_Subscriptions_Product::get_period($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_interval', WC_Subscriptions_Product::get_interval($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_length', WC_Subscriptions_Product::get_length($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_trial_length', $free_trial_length);
         woocommerce_add_order_item_meta($item_id, '_subscription_trial_period', WC_Subscriptions_Product::get_trial_period($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_recurring_amount', $recurring_amount);
         woocommerce_add_order_item_meta($item_id, '_subscription_sign_up_fee', $sign_up_fee);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_total', $recurring_amount);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_tax', 0);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_subtotal', $recurring_amount);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_subtotal_tax', 0);
         WC_Subscriptions_Manager::create_pending_subscription_for_order($order_id, $item['product_id']);
         switch ($order->status) {
             case 'completed':
             case 'processing':
                 woocommerce_update_order_item_meta($item_id, '_subscription_status', 'active');
                 break;
             case 'on-hold':
                 woocommerce_update_order_item_meta($item_id, '_subscription_status', 'on-hold');
                 break;
             case 'failed':
             case 'cancelled':
             case 'refunded':
                 woocommerce_add_order_item_meta($item_id, '_subscription_status', 'cancelled');
                 break;
         }
         // We need to override the line totals to $0 when there is a free trial
         if ($free_trial_length > 0 || $sign_up_fee > 0) {
             $line_total_keys = array('line_subtotal', 'line_total');
             // Make sure sign up fees are included in the total (or $0 if no sign up fee and a free trial)
             foreach ($line_total_keys as $line_total_key) {
                 $item[$line_total_key] = $sign_up_fee;
             }
             // If there is no free trial, make sure line totals include sign up fee and recurring fees
             if (0 == $free_trial_length) {
                 foreach ($line_total_keys as $line_total_key) {
                     $item[$line_total_key] += $recurring_amount;
                 }
             }
             foreach ($line_total_keys as $line_total_key) {
                 $item[$line_total_key] = number_format($item[$line_total_key], 2);
             }
         } else {
             $item['line_subtotal'] = $recurring_amount;
             $item['line_total'] = $recurring_amount;
         }
         woocommerce_update_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
         woocommerce_update_order_item_meta($item_id, '_line_total', $item['line_total']);
     }
     return $item;
 }
 /**
  * Creates a new order for renewing a subscription product based on the details of a previous order. 
  * 
  * @param $order WC_Order | int The WC_Order object or ID of the order for which the a new order should be created.
  * @param $meta_key string The ID of the subscription product in the order which needs to be added to the new order.
  * @since 1.0
  */
 public static function generate_renewal_order($original_order, $product_id)
 {
     global $wpdb;
     if (!is_object($original_order)) {
         $original_order = new WC_Order($original_order);
     }
     // Create the new order
     $renewal_order_data = array('post_type' => 'shop_order', 'post_title' => 'Renewal Order – ' . date('F j, Y @ h:i A'), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => $original_order->customer_note, 'post_author' => 1, 'post_password' => uniqid('order_'));
     $renewal_order_id = wp_insert_post($renewal_order_data);
     // Set the order as pending
     wp_set_object_terms($renewal_order_id, 'pending', 'shop_order_status');
     // Carry all the post meta from the old order over to the new order
     $order_meta_items = $wpdb->get_results("SELECT `meta_key`, `meta_value` FROM {$wpdb->postmeta} WHERE `post_id` = {$original_order->id}", 'ARRAY_A');
     foreach ($order_meta_items as $order_meta_item) {
         add_post_meta($renewal_order_id, $order_meta_item['meta_key'], maybe_unserialize($order_meta_item['meta_value']), true);
     }
     $outstanding_balance = self::get_outstanding_balance($original_order, $product_id);
     // If there are outstanding payment amounts, add them as a sign-up fee to the order, otherwise set the sign-up fee to 0
     if ($outstanding_balance > 0 && 'yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_add_outstanding_balance')) {
         $failed_payment_count = self::get_failed_payment_count($original_order, $product_id);
         $sign_up_fee_subtotal = 0;
         $sign_up_fee_subtotal_ex_tax = 0;
         // Calculate
         foreach ($original_order->get_items() as $item) {
             if ($item['id'] != $product_id) {
                 continue;
             }
             $base_price = WC_Subscriptions_Product::get_price($item['id']) * $item['qty'];
             // Row price
             if ($original_order->prices_include_tax) {
                 // Sub total is based on base prices (without discounts or shipping)
                 $sign_up_fee_subtotal += $base_price * $failed_payment_count;
                 $sign_up_fee_subtotal_ex_tax += ($base_price - $item['line_tax']) * $failed_payment_count;
             } else {
                 // Sub total is based on base prices (without discounts)
                 $sign_up_fee_subtotal += ($base_price + $item['line_tax']) * $failed_payment_count;
                 $sign_up_fee_subtotal_ex_tax += $base_price * $failed_payment_count;
             }
         }
         update_post_meta($renewal_order_id, '_sign_up_fee_total', $outstanding_balance);
         update_post_meta($renewal_order_id, '_sign_up_fee_subtotal', $sign_up_fee_subtotal);
         update_post_meta($renewal_order_id, '_sign_up_fee_subtotal_ex_tax', $sign_up_fee_subtotal_ex_tax);
         $sign_up_fee_taxes = get_post_meta($renewal_order_id, '_sign_up_fee_taxes', true);
         foreach ($original_order->get_taxes() as $key => $tax) {
             $sign_up_fee_taxes[$key]['cart_tax'] = $tax['cart_tax'] * $failed_payment_count;
             $sign_up_fee_taxes[$key]['shipping_tax'] = $tax['shipping_tax'] * $failed_payment_count;
         }
         update_post_meta($renewal_order_id, '_sign_up_fee_taxes', $sign_up_fee_taxes);
         update_post_meta($renewal_order_id, '_sign_up_fee_tax_total', $original_order->get_total_tax() * $failed_payment_count);
         update_post_meta($renewal_order_id, '_sign_up_fee_discount_cart', $original_order->cart_discount * $failed_payment_count);
         update_post_meta($renewal_order_id, '_sign_up_fee_discount_total', $original_order->order_discount * $failed_payment_count);
     } else {
         // Remove all sign-up fees
         foreach (array('_cart_contents_sign_up_fee_total', '_cart_contents_sign_up_fee_count', '_sign_up_fee_total', '_sign_up_fee_subtotal', '_sign_up_fee_subtotal_ex_tax', '_sign_up_fee_tax_total', '_sign_up_fee_discount_cart', '_sign_up_fee_discount_total') as $meta_key) {
             update_post_meta($renewal_order_id, $meta_key, 0);
         }
         update_post_meta($renewal_order_id, '_sign_up_fee_taxes', array());
     }
     // Keep a record of the original order's ID on the renewal order
     add_post_meta($renewal_order_id, '_original_order', $original_order->id, true);
     // Make sure the original order is cancelled and keep a note of the renewal order
     if (!in_array($original_order->status, array('cancelled', 'expired', 'failed'))) {
         $original_order->cancel_order();
     }
     $original_order->add_order_note(sprintf(__('Order superseded by renewal order %s.', WC_Subscriptions::$text_domain), $renewal_order_data));
     $renewal_order = new WC_Order($renewal_order_id);
     WC_Subscriptions_Manager::process_subscriptions_on_checkout($renewal_order_id);
     do_action('woocommerce_subscriptions_renewal_order_created', $renewal_order, $original_order, $product_id);
 }
 /**
  * Add subscription related order item meta via Ajax when a subscription product is added as an item to an order.
  *
  * This function is hooked to the 'wp_ajax_woocommerce_subscriptions_prefill_order_item_meta' hook which should only fire
  * on WC 1.x (because the admin.js uses a selector which was changed in WC 2.0). For WC 2.0, order item meta is pre-filled
  * via the 'woocommerce_new_order_item' hook in the new @see self::prefill_order_item().
  *
  * @since 1.2.4
  * @return void
  */
 public static function prefill_order_item_meta_old()
 {
     if (function_exists('woocommerce_add_order_item_meta')) {
         // Meta added on the 'woocommerce_new_order_item' hook
         return;
     }
     check_ajax_referer(WC_Subscriptions::$text_domain, 'security');
     $product_id = trim(stripslashes($_POST['item_to_add']));
     $index = trim(stripslashes($_POST['index']));
     $response = array('item_index' => $index, 'html' => '', 'line_totals' => array());
     if (WC_Subscriptions_Product::is_subscription($product_id)) {
         $recurring_amount = WC_Subscriptions_Product::get_price($product_id);
         $item_meta = new WC_Order_Item_Meta();
         // Subscription details so order state persists even when a product is changed
         $item_meta->add('_subscription_period', WC_Subscriptions_Product::get_period($product_id));
         $item_meta->add('_subscription_interval', WC_Subscriptions_Product::get_interval($product_id));
         $item_meta->add('_subscription_length', WC_Subscriptions_Product::get_length($product_id));
         $item_meta->add('_subscription_trial_length', WC_Subscriptions_Product::get_trial_length($product_id));
         $item_meta->add('_subscription_trial_period', WC_Subscriptions_Product::get_trial_period($product_id));
         $item_meta->add('_subscription_recurring_amount', $recurring_amount);
         $item_meta->add('_subscription_sign_up_fee', WC_Subscriptions_Product::get_sign_up_fee($product_id));
         // Recurring totals need to be calcualted
         $item_meta->add('_recurring_line_total', $recurring_amount);
         $item_meta->add('_recurring_line_tax', 0);
         $item_meta->add('_recurring_line_subtotal', $recurring_amount);
         $item_meta->add('_recurring_line_subtotal_tax', 0);
         $item_meta = $item_meta->meta;
         if (isset($item_meta) && is_array($item_meta) && sizeof($item_meta) > 0) {
             foreach ($item_meta as $key => $meta) {
                 // Backwards compatibility
                 if (is_array($meta) && isset($meta['meta_name'])) {
                     $meta_name = $meta['meta_name'];
                     $meta_value = $meta['meta_value'];
                 } else {
                     $meta_name = $key;
                     $meta_value = $meta;
                 }
                 $response['html'] .= '<tr><td><input type="text" name="meta_name[' . $index . '][]" value="' . esc_attr($meta_name) . '" /></td><td><input type="text" name="meta_value[' . $index . '][]" value="' . esc_attr($meta_value) . '" /></td><td width="1%"></td></tr>';
             }
         }
         // Calculate line totals for this item
         if ($sign_up_fee > 0) {
             $line_subtotal = $sign_up_fee;
             $line_total = $sign_up_fee;
             // If there is no free trial, add the recuring amounts
             if ($trial_length == 0) {
                 $line_subtotal += $recurring_amount;
                 $line_total += $recurring_amount;
             }
             $response['line_totals']['line_subtotal'] = esc_attr(number_format((double) $line_subtotal, 2, '.', ''));
             $response['line_totals']['line_total'] = esc_attr(number_format((double) $line_total, 2, '.', ''));
         }
     }
     echo json_encode($response);
     die;
 }