/**
     * Create renewal order
     * Based on the WooCommerce procedure found in class-wc-checkout.php
     * 
     * @access public
     * @param object $subscription
     * @return int
     */
    public static function create_renewal_order($subscription)
    {
        // Get instance of main plugin class to access settings
        $subscriptio = Subscriptio::get_instance();

        // Since WooCommerce 2.2 order statuses are stored as post statuses
        $post_status = Subscriptio::wc_version_gte('2.2') ? 'wc-pending' : 'publish';

        // Prepare post properties
        $order_data = array(
            'post_type' 	=> 'shop_order',
            'post_title' 	=> sprintf(__('Order – %s', 'subscriptio'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'subscriptio'))),
            'post_status' 	=> $post_status,
            'ping_status'	=> 'closed',
            'post_excerpt' 	=> $subscription->renewal_customer_note,
            'post_author' 	=> 1,
            'post_password'	=> uniqid('order_'),
        );

        // Insert post into database
        $order_id = wp_insert_post($order_data, true);

        // Successfully inserted order post?
        if (is_wp_error($order_id)) {
            throw new Exception(__('Unable to create renewal order - failed inserting post.', 'subscriptio'));
        }

        // Load user meta
        $user_meta = Subscriptio::unwrap_post_meta(get_user_meta($subscription->user_id));

        // Insert billing and shipping details
        $billing_shipping_fields = array(
            'billing'  => array(
                '_first_name',
                '_last_name',
                '_company',
                '_address_1',
                '_address_2',
                '_city',
                '_state',
                '_postcode',
                '_country',
                '_email',
                '_phone',
            ),
        );

        // Check if subscription needs shipping
        if ($subscription->needs_shipping()) {
            $billing_shipping_fields['shipping'] = array(
                '_first_name',
                '_last_name',
                '_company',
                '_address_1',
                '_address_2',
                '_city',
                '_state',
                '_postcode',
                '_country',
            );
        }

        // Iterate over billing/shipping fields and save them
        foreach ($billing_shipping_fields as $type => $fields) {
            foreach ($fields as $field) {

                // Billing fields
                if ($type == 'billing' && isset($user_meta[$type . $field])) {
                    $field_value = $user_meta[$type . $field];
                }

                // Shipping fields
                else if ($type == 'shipping' && isset($subscription->shipping_address['_' . $type . $field])) {
                    $field_value = $subscription->shipping_address['_' . $type . $field];
                }

                // In case some field does not exist
                else {
                    $field_value = '';
                }

                // Save field to post meta
                update_post_meta($order_id, '_' . $type . $field, $field_value);
            }
        }

        // Add other meta fields
        $other_meta_fields = array(
            '_order_shipping'       => $subscription->renewal_order_shipping,
            '_order_shipping_tax'   => $subscription->renewal_order_shipping_tax,
            '_cart_discount'        => $subscription->renewal_cart_discount,
            '_order_discount'       => $subscription->renewal_order_discount,
            '_order_tax'            => $subscription->renewal_order_tax,
            '_order_total'          => $subscription->renewal_order_total,
            '_customer_user'        => $subscription->user_id,
            '_order_currency'       => $subscription->renewal_order_currency,
            '_order_key'            => 'wc_' . apply_filters('woocommerce_generate_order_key', uniqid('order_')),
            '_prices_include_tax'   => $subscription->renewal_prices_include_tax,
            '_customer_ip_address'  => $subscription->renewal_customer_ip_address,
            '_customer_user_agent'  => $subscription->renewal_customer_user_agent,
            '_payment_method'       => '',  // Not yet paid
            '_payment_method_title' => '',  // Not yet paid
            '_subscriptio_renewal'  => 'yes',
        );

        foreach ($other_meta_fields as $field_key => $field_value) {
            update_post_meta($order_id, $field_key, $field_value);
        }

        // Check if subscription product is variable
        $product_id_to_use = !empty($subscription->variation_id) ? $subscription->variation_id : $subscription->product_id;

        // Check if product still exists
        if (Subscriptio::product_is_active($product_id_to_use)) {

            // Load product object
            $product = new WC_Product($product_id_to_use);

            // Get product name
            $product_title = $product->get_title();

            // Update product name on subscription if it was changed
            if ($product_title != $subscription->product_name) {
                $subscription->update_subscription_details(array(
                    'product_name'  => $product_title,
                ));
            }
        }

        // If not - use saved product "snapshot" from previous order
        else {
            $product_title = $subscription->product_name;
        }

        // Add line item (product) to order
        $item_id = wc_add_order_item($order_id, array(
            'order_item_name'   => $product_title,
            'order_item_type'   => 'line_item',
        ));

        if (!$item_id) {
            throw new Exception(__('Unable to add product to renewal order.', 'subscriptio'));
        }

        // Add line item meta
        $item_meta = array(
            '_qty'                  => !empty($subscription->quantity) ? $subscription->quantity : 1,
            '_tax_class'            => $subscription->renewal_tax_class,
            '_product_id'           => $subscription->product_id,
            '_variation_id'         => !empty($subscription->variation_id) ? $subscription->variation_id : '',
            '_line_subtotal'        => wc_format_decimal($subscription->renewal_line_subtotal),
            '_line_subtotal_tax'    => wc_format_decimal($subscription->renewal_line_subtotal_tax),
            '_line_total'           => wc_format_decimal($subscription->renewal_line_total),
            '_line_tax'             => wc_format_decimal($subscription->renewal_line_tax),
        );

        foreach ($item_meta as $item_meta_key => $item_meta_value) {
            wc_add_order_item_meta($item_id, $item_meta_key, $item_meta_value);
        }

        // Save shipping info (if any)
        if (!empty($subscription->shipping)) {
            $shipping_item_id = wc_add_order_item($order_id, array(
                'order_item_name'   => $subscription->shipping['name'],
                'order_item_type'   => 'shipping',
            ));

            wc_add_order_item_meta($shipping_item_id, 'method_id', $subscription->shipping['method_id']);
            wc_add_order_item_meta($shipping_item_id, 'cost', wc_format_decimal($subscription->shipping['cost']));
        }

        // Save taxes (if any)
        foreach ($subscription->taxes as $tax) {
            $tax_item_id = wc_add_order_item($order_id, array(
                'order_item_name'   => $tax['name'],
                'order_item_type'   => 'tax',
            ));

            wc_add_order_item_meta($tax_item_id, 'rate_id', $tax['rate_id']);
            wc_add_order_item_meta($tax_item_id, 'label', $tax['label']);
            wc_add_order_item_meta($tax_item_id, 'compound', $tax['compound']);
            wc_add_order_item_meta($tax_item_id, 'tax_amount', wc_format_decimal($tax['tax_amount'], 4));
            wc_add_order_item_meta($tax_item_id, 'shipping_tax_amount', wc_format_decimal($tax['shipping_tax_amount'], 4));
        }

        // Schedule payment due reminders
        if ($payment_due_timestamp = wp_next_scheduled('subscriptio_scheduled_payment', $subscription->id)) {
            foreach ($subscription->get_reminders('pre_payment_due', $payment_due_timestamp) as $timestamp) {
                Subscriptio_Scheduler::schedule_reminder($subscription->id, $timestamp);
            }
        }

        // Update appropriate subscription fields with new order id
        $subscription->update_subscription_details(array(
            'last_order_id' => $order_id,
            'all_order_ids' => $order_id,
        ));

        // Create a new order object
        $order = new WC_Order($order_id);

        // Set status to pending (pre- WooCommerce 2.2)
        if (!Subscriptio::wc_version_gte('2.2')) {
            $order->update_status('pending');
        }

        // Send New Order email
        Subscriptio_Mailer::send('new_order', $order);

        return $order_id;
    }
    /**
     * Get subscription items
     * 
     * @access public
     * @return array
     */
    public function get_items()
    {
        $items = array();

        // Currently we can only have one product per subscription (and most probably it will stay this way)
        if (!empty($this->product_id)) {

            $item = array(
                'product_id'    => $this->product_id,
                'quantity'      => $this->quantity,
                'total'         => $this->renewal_line_total,
                'tax'           => $this->renewal_line_tax,
                'deleted'       => false,
            );

            // Is this a variable product?
            $item['name'] = !empty($this->variation_id) ? sprintf(__('Variation #%1$s of', 'subscriptio'), $this->variation_id) . ' ' : '';

            // Get quantity
            $quantity = !empty($this->quantity) ? $this->quantity : 1;

            // Is this product still active?
            if (Subscriptio::product_is_active($this->product_id)) {

                // Get current product name
                $item['name'] .= get_the_title($this->product_id);

                // Is variation still active?
                if ($this->variation_id && !Subscriptio::product_is_active($this->variation_id)) {
                    $item['name'] .= ' (' . __('variation deleted', 'subscriptio') . ')';
                }
            }
            else {
                $item['name'] .= $this->product_name;
                $item['name'] .= ' (' . __('deleted', 'subscriptio') . ')' . ($quantity > 1 ? ' x ' . $quantity : '');
                $item['deleted'] = true;
            }

            $items[] = $item;
        }

        return $items;
    }