Esempio n. 1
1
function pp_add_order_item_meta($item_id, $cart_item)
{
    global $woocommerce;
    if (!empty($cart_item['_w2p_set_option'])) {
        woocommerce_add_order_item_meta($item_id, '_w2p_set_option', $cart_item['_w2p_set_option']);
    }
}
 /**
  * After ordering, add the data to the order line items.
  *
  * @access public
  * @param mixed $item_id
  * @param mixed $cart_item
  * @return void
  * @since 8.0.0
  */
 public function add_order_item_meta($item_id, $cart_item)
 {
     $length = get_post_meta($cart_item['product_id'], '_length', TRUE);
     $width = get_post_meta($cart_item['product_id'], '_width', TRUE);
     $height = get_post_meta($cart_item['product_id'], '_height', TRUE);
     $is_volumetrik_enabled = get_post_meta($cart_item['product_id'], $this->meta, TRUE);
     if ($is_volumetrik_enabled == 'yes' && !empty($length) && !empty($width) && !empty($height)) {
         woocommerce_add_order_item_meta($item_id, __('Dimension', 'agenwebsite'), sprintf('%u x %u x %u cm', $length, $width, $height));
     }
 }
 /**
  * Save entered credit value by customer in order item meta
  *
  * @param int $item_id
  * @param array $values associative array containing item's details
  */
 public function save_called_credit_details_in_order_item_meta($item_id, $values)
 {
     $coupon_titles = get_post_meta($values['product_id'], '_coupon_title', true);
     if ($this->is_coupon_amount_pick_from_product_price($coupon_titles) && isset($values['data']->price) && $values['data']->price > 0) {
         woocommerce_add_order_item_meta($item_id, 'sc_called_credit', $values['data']->price);
     }
 }
Esempio n. 4
0
/**
 * woocommerce_add_line_tax function.
 *
 * @access public
 * @return void
 */
function woocommerce_add_line_tax()
{
    global $woocommerce, $wpdb;
    check_ajax_referer('calc-totals', 'security');
    $order_id = absint($_POST['order_id']);
    $order = new WC_Order($order_id);
    // Get tax rates
    $rates = $wpdb->get_results("SELECT tax_rate_id, tax_rate_country, tax_rate_state, tax_rate_name, tax_rate_priority FROM {$wpdb->prefix}woocommerce_tax_rates ORDER BY tax_rate_name");
    $tax_codes = array();
    foreach ($rates as $rate) {
        $code = array();
        $code[] = $rate->tax_rate_country;
        $code[] = $rate->tax_rate_state;
        $code[] = $rate->tax_rate_name ? sanitize_title($rate->tax_rate_name) : 'TAX';
        $code[] = absint($rate->tax_rate_priority);
        $tax_codes[$rate->tax_rate_id] = strtoupper(implode('-', array_filter($code)));
    }
    // Add line item
    $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => '', 'order_item_type' => 'tax'));
    // Add line item meta
    if ($item_id) {
        woocommerce_add_order_item_meta($item_id, 'rate_id', '');
        woocommerce_add_order_item_meta($item_id, 'label', '');
        woocommerce_add_order_item_meta($item_id, 'compound', '');
        woocommerce_add_order_item_meta($item_id, 'tax_amount', '');
        woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', '');
    }
    include 'admin/post-types/writepanels/order-tax-html.php';
    // Quit out
    die;
}
Esempio n. 5
0
 /**
  * Save sold by text in database
  *
  * @param item_id, cart_item
  * @return void 
  */
 function order_item_meta_2($item_id, $cart_item)
 {
     global $WCMp;
     if ($WCMp->vendor_caps->vendor_frontend_settings('sold_by_cart_and_checkout')) {
         $general_cap = isset($this->frontend_cap['sold_by_text']) ? $this->frontend_cap['sold_by_text'] : '';
         if (!$general_cap) {
             $general_cap = 'Sold By';
         }
         $vendor = get_wcmp_product_vendors($cart_item['product_id']);
         if ($vendor) {
             woocommerce_add_order_item_meta($item_id, $general_cap, $vendor->user_data->display_name);
             woocommerce_add_order_item_meta($item_id, '_vendor_id', $vendor->id);
         }
     }
 }
 public function save_vendor_settings()
 {
     global $woocommerce;
     $user_id = get_current_user_id();
     if (!empty($_GET['wc_pv_mark_shipped'])) {
         $shop_name = WCV_Vendors::get_vendor_shop_name($user_id);
         $order_id = $_GET['wc_pv_mark_shipped'];
         $shippers = (array) get_post_meta($order_id, 'wc_pv_shipped', true);
         $order = new WC_Order($order_id);
         // If not in the shippers array mark as shipped otherwise do nothing.
         if (!in_array($user_id, $shippers)) {
             $shippers[] = $user_id;
             $mails = $woocommerce->mailer()->get_emails();
             if (!empty($mails)) {
                 $mails['WC_Email_Notify_Shipped']->trigger($order_id, $user_id);
             }
             do_action('wcvendors_vendor_ship', $order_id, $user_id);
             wc_add_notice(__('Order marked shipped.', 'wcvendors'), 'success');
             $order->add_order_note(apply_filters('wcvendors_vendor_shipped_note', __($shop_name . ' has marked as shipped. ', 'wcvendors')), $user_id);
         } elseif (false != ($key = array_search($user_id, $shippers))) {
             unset($shippers[$key]);
             // Remove user from the shippers array
         }
         update_post_meta($order_id, 'wc_pv_shipped', $shippers);
         return;
     }
     if (isset($_POST['update_tracking'])) {
         $order_id = (int) $_POST['order_id'];
         $product_id = (int) $_POST['product_id'];
         $tracking_provider = woocommerce_clean($_POST['tracking_provider']);
         $custom_tracking_provider = woocommerce_clean($_POST['custom_tracking_provider_name']);
         $custom_tracking_link = woocommerce_clean($_POST['custom_tracking_url']);
         $tracking_number = woocommerce_clean($_POST['tracking_number']);
         $date_shipped = woocommerce_clean(strtotime($_POST['date_shipped']));
         $order = new WC_Order($order_id);
         $products = $order->get_items();
         foreach ($products as $key => $value) {
             if ($value['product_id'] == $product_id || $value['variation_id'] == $product_id) {
                 $order_item_id = $key;
                 break;
             }
         }
         if ($order_item_id) {
             woocommerce_delete_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'));
             woocommerce_add_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'), $tracking_number);
             $message = __('Success. Your tracking number has been updated.', 'wcvendors');
             wc_add_notice($message, 'success');
             // Update order data
             update_post_meta($order_id, '_tracking_provider', $tracking_provider);
             update_post_meta($order_id, '_custom_tracking_provider', $custom_tracking_provider);
             update_post_meta($order_id, '_tracking_number', $tracking_number);
             update_post_meta($order_id, '_custom_tracking_link', $custom_tracking_link);
             update_post_meta($order_id, '_date_shipped', $date_shipped);
         }
     }
     if (empty($_POST['vendor_application_submit'])) {
         return false;
     }
     if (isset($_POST['wc-product-vendor-nonce'])) {
         if (!wp_verify_nonce($_POST['wc-product-vendor-nonce'], 'save-shop-settings')) {
             return false;
         }
         if (isset($_POST['pv_paypal'])) {
             if (!is_email($_POST['pv_paypal'])) {
                 wc_add_notice(__('Your PayPal address is not a valid email address.', 'wcvendors'), 'error');
             } else {
                 update_user_meta($user_id, 'pv_paypal', $_POST['pv_paypal']);
             }
         }
         if (!empty($_POST['pv_shop_name'])) {
             $users = get_users(array('meta_key' => 'pv_shop_slug', 'meta_value' => sanitize_title($_POST['pv_shop_name'])));
             if (!empty($users) && $users[0]->ID != $user_id) {
                 wc_add_notice(__('That shop name is already taken. Your shop name must be unique.', 'wcvendors'), 'error');
             } else {
                 update_user_meta($user_id, 'pv_shop_name', $_POST['pv_shop_name']);
                 update_user_meta($user_id, 'pv_shop_slug', sanitize_title($_POST['pv_shop_name']));
             }
         }
         if (isset($_POST['pv_shop_description'])) {
             update_user_meta($user_id, 'pv_shop_description', $_POST['pv_shop_description']);
         }
         if (isset($_POST['pv_seller_info'])) {
             update_user_meta($user_id, 'pv_seller_info', $_POST['pv_seller_info']);
         }
         do_action('wcvendors_shop_settings_saved', $user_id);
         if (!wc_notice_count()) {
             wc_add_notice(__('Settings saved.', 'wcvendors'), 'success');
         }
     }
 }
        function booking_order_box()
        {
            global $woocommerce, $wpdb;
            check_ajax_referer('order-item', 'security');
            $meta_id_next = '';
            $meta_id = '';
            $meta_id = woocommerce_add_order_item_meta(absint($_POST['order_item_id']), __('Name', 'woocommerce'), __('Value', 'woocommerce'));
            //print_r($meta_ids);
            //echo $meta_id; die();
            /*$meta_query = $check_query = "SELECT MAX(meta_id) AS meta_id FROM `".$wpdb->prefix."woocommerce_order_itemmeta`
            				WHERE order_item_id ='".$_POST['order_item_id']."'
            				";
            		$meta_results = $wpdb->get_results($meta_query);
            		$meta_id = $meta_results[0]->meta_id;*/
            $bookings_added = woocommerce_get_order_item_meta($_POST['order_item_id'], get_option("book.date-label"), true);
            if ($bookings_added == '') {
                //print_r("ehre".$bookings_added);die();
                if ($meta_id) {
                    $check_query = "SELECT meta_value AS product_id FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta`\n\t\t\t\t\t\tWHERE meta_key ='_product_id'\n\t\t\t\t\t\tAND order_item_id ='" . $_POST['order_item_id'] . "'\n\t\t\t\t\t\t";
                    $results_check = $wpdb->get_results($check_query);
                    $product_id = $results_check[0]->product_id;
                    //print_r($product_id);
                    $prod_id = get_post_meta($product_id, '_icl_lang_duplicate_of', true);
                    if ($prod_id == '' && $prod_id == null) {
                        //	$duplicate_of = $cart_item['product_id'];
                        $post_time = get_post($product_id);
                        $id_query = "SELECT ID FROM `" . $wpdb->prefix . "posts` WHERE post_date = '" . $post_time->post_date . "' ORDER BY ID LIMIT 1";
                        $results_post_id = $wpdb->get_results($id_query);
                        if (isset($results_post_id)) {
                            $prod_id = $results_post_id[0]->ID;
                        } else {
                            $prod_id = $product_id;
                        }
                    }
                    $cart_item_key = $_POST['order_item_id'];
                    $product_settings = get_post_meta($prod_id, 'woocommerce_booking_settings', true);
                    $i = 0;
                    //echo "PROD<pre>";print_r($product_settings);echo "</pre>";
                    echo '<input type="hidden" id="order_item_ids"  name="order_item_ids" value="' . $_POST['order_item_id'] . '"/>';
                    if (isset($product_settings['booking_enable_multiple_day']) && $product_settings['booking_enable_multiple_day'] == 'on' && (isset($product_settings['booking_fixed_block_enable']) && $product_settings['booking_fixed_block_enable'] == 'yes')) {
                        $results = $this->get_fixed_blocks($prod_id);
                        //print_r($results);die();
                        if (count($results) > 0) {
                            echo '<tr data-meta_id="' . $meta_id . '"><td><input type="text" name="meta_key[' . $meta_id . ']" value="Select Period" /></td><td><select name="meta_value[' . $meta_id . ']" id="admin_block_option_' . $_POST['order_item_id'] . '">';
                            foreach ($results as $key => $value) {
                                echo '<option id = ' . $value->start_day . '&' . $value->number_of_days . '&' . $value->price . ' value="' . $value->block_name . '">' . $value->block_name . '</option>';
                            }
                            echo '</select></td><td width="1%"><button class="remove_order_item_meta button">&times;</button></td></tr>';
                            $meta_id_start = $meta_id + 1;
                            $meta_id_end = $meta_id_start + 1;
                            echo '<input type="hidden" id="meta_id_start"  name="meta_id_start" value="' . $meta_id_start . '"/>';
                            echo '<input type="hidden" id="meta_id_end"  name="meta_id_end" value="' . $meta_id_end . '"/>';
                            ?>
						<script type="text/javascript">	
						var order_item_id = jQuery("#order_item_ids").val();
						jQuery("#admin_block_option_"+order_item_id).change(function()
						{
							//alert();
							if ( jQuery("#admin_block_option_"+order_item_id).val() != "" )
							{
								var passed_id = jQuery(this).children(":selected").attr("id");
								var exploded_id = passed_id.split('&');
								console.log(exploded_id);
								var meta_id_start = jQuery("#meta_id_start").val();
								var meta_id_end = jQuery("#meta_id_end").val();
								jQuery("#admin_block_option_start_day_"+order_item_id).val(exploded_id[0]);
								jQuery("#admin_block_option_number_of_day_"+order_item_id).val(exploded_id[1]);
								jQuery("#admin_block_option_price_"+order_item_id).val(exploded_id[2]);
								jQuery("#wapbk_admin_hidden_date_"+order_item_id).val("");
								jQuery("#wapbk_admin_hidden_date_checkout_"+order_item_id).val("");
								//jQuery("#show_time_slot").html("");
								jQuery("#admin_booking_calender_"+ meta_id_start).datepicker("setDate");
								jQuery("#admin_booking_calender_checkout_" + meta_id_end).datepicker("setDate");
							}
						});
	
	
						</script>
	
						<?php 
                            if (count($results) >= 0) {
                                $sd = $results[0]->start_day;
                                $nd = $results[0]->number_of_days;
                                $pd = $results[0]->price;
                            }
                            echo ' <input type="hidden" id="admin_block_option_enabled_' . $_POST['order_item_id'] . '"  name="admin_block_option_enabled_' . $_POST['order_item_id'] . '" value="on"/> 

						<input type="hidden" id="admin_block_option_start_day_' . $_POST['order_item_id'] . '"  name="admin_block_option_start_day_' . $_POST['order_item_id'] . '" value="' . $sd . '"/> 
						
						<input type="hidden" id="admin_block_option_number_of_day_' . $_POST['order_item_id'] . '"  name="admin_block_option_number_of_day_' . $_POST['order_item_id'] . '" value="' . $nd . '"/>
					
						<input type="hidden" id="admin_block_option_price_' . $_POST['order_item_id'] . '"name="admin_block_option_price_' . $_POST['order_item_id'] . '" value="' . $pd . '"/>';
                        } else {
                            $number_of_fixed_price_blocks = 0;
                            echo ' <input type="hidden" id="admin_block_option_enabled_' . $_POST['order_item_id'] . '"  name="admin_block_option_enabled_' . $_POST['order_item_id'] . '" value="off"/>
						
						<input type="hidden" id="admin_block_option_start_day_' . $_POST['order_item_id'] . '"  name="admin_block_option_start_day_' . $_POST['order_item_id'] . '" value=""/> 
						
						<input type="hidden" id="admin_block_option_number_of_day_' . $_POST['order_item_id'] . '"  name="admin_block_option_number_of_day_' . $_POST['order_item_id'] . '" value=""/>
						
						<input type="hidden" id="admin_block_option_price_' . $_POST['order_item_id'] . '"  name="admin_block_option_price_' . $_POST['order_item_id'] . '" value=""/>';
                        }
                        $meta_ids[$cart_item_key][$i] = $meta_id;
                        $meta_id = $meta_id + 1;
                        $i++;
                    }
                    if (isset($product_settings['booking_enable_date']) && $product_settings['booking_enable_date'] == 'on') {
                        $saved_settings = json_decode(get_option('woocommerce_booking_global_settings'));
                        //echo "<pre>";print_r($saved_settings);echo "</pre>";
                        //woocommerce_add_order_item_meta( $item_number,get_option("book.date-label"),'');
                        //$order = new WC_Order($order_id);
                        //$meta = $order->has_meta($item_number);
                        if ($saved_settings == '') {
                            $saved_settings = new stdClass();
                            $saved_settings->booking_date_format = 'd MM, yy';
                            $saved_settings->booking_time_format = '12';
                            $saved_settings->booking_months = '1';
                        }
                        $meta_ids[$cart_item_key][$i] = $meta_id;
                        $i++;
                        echo '<tr data-meta_id="' . $meta_id . '"><td><input type="text" name="meta_key[' . $meta_id . ']" value="' . get_option("book.item-meta-date") . '" /></td><td><input type="text" name="meta_value[' . $meta_id . ']" value="" /></td><td width="1%"><button class="remove_order_item_meta button">&times;</button></td></tr>';
                        if ($product_settings != '') {
                            // fetch specific booking dates
                            $booking_dates_arr = $product_settings['booking_specific_date'];
                            $booking_dates_str = "";
                            $meta_id_next = 0;
                            //$meta_id_checkout = 0;
                            if ($product_settings['booking_specific_booking'] == "on") {
                                if (!empty($booking_dates_arr)) {
                                    foreach ($booking_dates_arr as $k => $v) {
                                        $booking_dates_str .= '"' . $v . '",';
                                    }
                                }
                                $booking_dates_str = substr($booking_dates_str, 0, strlen($booking_dates_str) - 1);
                            }
                            print '<input type="hidden" name="wapbk_admin_booking_dates_' . $_POST['order_item_id'] . '" id="wapbk_admin_booking_dates_' . $_POST['order_item_id'] . '" value=\'' . $booking_dates_str . '\'>';
                            if (isset($saved_settings->booking_global_holidays)) {
                                $book_global_holidays = $saved_settings->booking_global_holidays;
                                $book_global_holidays = substr($book_global_holidays, 0, strlen($book_global_holidays));
                                $book_global_holidays = '"' . str_replace(',', '","', $book_global_holidays) . '"';
                            } else {
                                $book_global_holidays = '';
                            }
                            //echo "here";die();
                            print '<input type="hidden" name="wapbk_admin_booking_global_holidays_' . $_POST['order_item_id'] . '" id="wapbk_admin_booking_global_holidays_' . $_POST['order_item_id'] . '" value=\'' . $book_global_holidays . '\'>';
                            $booking_holidays_string = '"' . str_replace(',', '","', $product_settings['booking_product_holiday']) . '"';
                            print '<input type="hidden" name="wapbk_admin_booking_holidays_' . $_POST['order_item_id'] . '" id="wapbk_admin_booking_holidays_' . $_POST['order_item_id'] . '" value=\'' . $booking_holidays_string . '\'>';
                            //Default settings
                            $default = "Y";
                            if (isset($product_settings['booking_recurring_booking']) && $product_settings['booking_recurring_booking'] == "on" || isset($product_settings['booking_specific_booking']) && $product_settings['booking_specific_booking'] == "on") {
                                $default = "N";
                            }
                            foreach ($product_settings['booking_recurring'] as $wkey => $wval) {
                                if ($default == "Y") {
                                    print '<input type="hidden" name="wapbk_admin_' . $wkey . '_' . $_POST['order_item_id'] . '" id="wapbk_admin_' . $wkey . '_' . $_POST['order_item_id'] . '" value="on">';
                                } else {
                                    if ($product_settings['booking_recurring_booking'] == "on") {
                                        print '<input type="hidden" name="wapbk_admin_' . $wkey . '_' . $_POST['order_item_id'] . '" id="wapbk_admin_' . $wkey . '_' . $_POST['order_item_id'] . '" value="' . $wval . '">';
                                    } else {
                                        print '<input type="hidden" name="wapbk_admin_' . $wkey . '_' . $_POST['order_item_id'] . '" id="wapbk_admin_' . $wkey . '_' . $_POST['order_item_id'] . '" value="">';
                                    }
                                }
                            }
                            if (isset($product_settings['booking_time_settings'])) {
                                print '<input type="hidden" name="wapbk_admin_booking_times_' . $_POST['order_item_id'] . '" id="wapbk_admin_booking_times_' . $_POST['order_item_id'] . '" value=\'' . $product_settings['booking_time_settings'] . '\'>';
                            } else {
                                print '<input type="hidden" name="wapbk_admin_booking_times_' . $_POST['order_item_id'] . '" id="wapbk_admin_booking_times_' . $_POST['order_item_id'] . '" value="">';
                            }
                            if (isset($product_settings['booking_enable_multiple_day'])) {
                                print '<input type="hidden" id="wapbk_admin_multiple_day_booking_' . $_POST['order_item_id'] . '" name="wapbk_admin_multiple_day_booking_' . $_POST['order_item_id'] . '" value="' . $product_settings['booking_enable_multiple_day'] . '"/>';
                            } else {
                                print '<input type="hidden" id="wapbk_admin_multiple_day_booking_' . $_POST['order_item_id'] . '" name="wapbk_admin_multiple_day_booking_' . $_POST['order_item_id'] . '" value=""/>';
                            }
                            if (isset($product_settings['booking_minimum_number_days'])) {
                                print '<input type="hidden" name="wapbk_admin_minimumOrderDays_' . $_POST['order_item_id'] . '" id="wapbk_admin_minimumOrderDays_' . $_POST['order_item_id'] . '" value="' . $product_settings['booking_minimum_number_days'] . '">';
                            } else {
                                print '<input type="hidden" name="wapbk_admin_minimumOrderDays_' . $_POST['order_item_id'] . '" id="wapbk_admin_minimumOrderDays_' . $_POST['order_item_id'] . '" value="">';
                            }
                            if (isset($product_settings['booking_maximum_number_days'])) {
                                print '<input type="hidden" name="wapbk_admin_number_of_dates_' . $_POST['order_item_id'] . '" id="wapbk_admin_number_of_dates_' . $_POST['order_item_id'] . '" value="' . $product_settings['booking_maximum_number_days'] . '">';
                            } else {
                                print '<input type="hidden" name="wapbk_admin_number_of_dates_' . $_POST['order_item_id'] . '" id="wapbk_admin_number_of_dates_' . $_POST['order_item_id'] . '" value="">';
                            }
                            if (isset($product_settings['booking_enable_time'])) {
                                print '<input type="hidden" name="wapbk_admin_bookingEnableTime_' . $_POST['order_item_id'] . '" id="wapbk_admin_bookingEnableTime_' . $_POST['order_item_id'] . '" value="' . $product_settings['booking_enable_time'] . '">';
                            } else {
                                print '<input type="hidden" name="wapbk_admin_bookingEnableTime_' . $_POST['order_item_id'] . '" id="wapbk_admin_bookingEnableTime_' . $_POST['order_item_id'] . '" value="">';
                            }
                            if (isset($product_settings['booking_recurring_booking'])) {
                                print '<input type="hidden" name="wapbk_admin_recurringDays_' . $_POST['order_item_id'] . '" id="wapbk_admin_recurringDays_' . $_POST['order_item_id'] . '" value="' . $product_settings['booking_recurring_booking'] . '">';
                            } else {
                                print '<input type="hidden" name="wapbk_admin_recurringDays_' . $_POST['order_item_id'] . '" id="wapbk_admin_recurringDays_' . $_POST['order_item_id'] . '" value="">';
                            }
                            if (isset($product_settings['booking_specific_booking'])) {
                                print '<input type="hidden" name="wapbk_admin_specificDates_' . $_POST['order_item_id'] . '" id="wapbk_admin_specificDates_' . $_POST['order_item_id'] . '" value="' . $product_settings['booking_specific_booking'] . '">';
                            } else {
                                print '<input type="hidden" name="wapbk_admin_specificDates_' . $_POST['order_item_id'] . '" id="wapbk_admin_specificDates_' . $_POST['order_item_id'] . '" value="">';
                            }
                            //echo "here";die();
                            global $woocommerce_booking;
                            $lockout_query = "SELECT DISTINCT start_date FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\tWHERE post_id='" . $prod_id . "'\n\t\t\t\t\t\t\t\tAND total_booking > 0\n\t\t\t\t\t\t\t\tAND available_booking = 0";
                            $results_lockout = $wpdb->get_results($lockout_query);
                            //print_r($results_lockout);die();
                            $lockout_query = "SELECT DISTINCT start_date FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\tWHERE post_id='" . $prod_id . "'\n\t\t\t\t\tAND available_booking > 0";
                            //echo $lockout_query;die();
                            $results_lock = $wpdb->get_results($lockout_query);
                            $lockout_date = '';
                            //print_r($results_lock);exit;
                            foreach ($results_lock as $key => $value) {
                                $start_date = $value->start_date;
                                $bookings_done = $this->date_lockout($start_date, $prod_id);
                                if ($bookings_done >= $product_settings['booking_date_lockout']) {
                                    $lockout = explode("-", $start_date);
                                    $lockout_date .= '"' . intval($lockout[2]) . "-" . intval($lockout[1]) . "-" . $lockout[0] . '",';
                                }
                            }
                            //echo $date_lockout;die();
                            $lockout_str = substr($lockout_date, 0, strlen($lockout_date) - 1);
                            foreach ($results_lockout as $k => $v) {
                                foreach ($results_lock as $key => $value) {
                                    if ($v->start_date == $value->start_date) {
                                        $date_lockout = "SELECT COUNT(start_date) FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id='" . $prod_id . "'\n\t\t\t\t\t\t\t\t\t\t\t\tAND start_date='" . $v->start_date . "'\n\t\t\t\t\t\t\t\t\t\t\t\tAND available_booking = 0";
                                        $results_date_lock = $wpdb->get_results($date_lockout);
                                        if ($product_settings['booking_date_lockout'] > $results_date_lock[0]->{'COUNT(start_date)'}) {
                                            unset($results_lockout[$k]);
                                        }
                                    }
                                }
                            }
                            $lockout_dates_str = "";
                            foreach ($results_lockout as $k => $v) {
                                $lockout_temp = $v->start_date;
                                $lockout = explode("-", $lockout_temp);
                                $lockout_dates_str .= '"' . intval($lockout[2]) . "-" . intval($lockout[1]) . "-" . $lockout[0] . '",';
                                $lockout_temp = "";
                            }
                            $lockout_dates_str = substr($lockout_dates_str, 0, strlen($lockout_dates_str) - 1);
                            $lockout_dates = $lockout_dates_str . "," . $lockout_str;
                            print '<input type="hidden" name="wapbk_admin_lockout_days_' . $_POST['order_item_id'] . '" id="wapbk_admin_lockout_days_' . $_POST['order_item_id'] . '" value=\'' . $lockout_dates . '\'>';
                            $todays_date = date('Y-m-d');
                            //print_r($todays_date);die();
                            $query_date = "SELECT DATE_FORMAT(start_date,'%d-%c-%Y') as start_date,DATE_FORMAT(end_date,'%d-%c-%Y') as end_date FROM " . $wpdb->prefix . "booking_history WHERE start_date >='" . $todays_date . "' AND post_id = '" . $prod_id . "'";
                            //echo $query_date;
                            $results_date = $wpdb->get_results($query_date);
                            //print_r($results_date);
                            $dates_new = array();
                            $booked_dates = array();
                            foreach ($results_date as $k => $v) {
                                $start_date = $v->start_date;
                                $end_date = $v->end_date;
                                $dates = $woocommerce_booking->betweendays($start_date, $end_date);
                                //print_r($dates);
                                $dates_new = array_merge($dates, $dates_new);
                            }
                            //	Enable the start date for the booking period for checkout
                            foreach ($results_date as $k => $v) {
                                $start_date = $v->start_date;
                                //echo ($start_date);
                                $end_date = $v->end_date;
                                //echo ($end_date);
                                $new_start = strtotime("+1 day", strtotime($start_date));
                                $new_start = date("d-m-Y", $new_start);
                                //echo $new_start;
                                $dates = $woocommerce_booking->betweendays($new_start, $end_date);
                                $booked_dates = array_merge($dates, $booked_dates);
                            }
                            //print_r($dates);
                            //print_r($booked_dates);
                            $dates_new_arr = array_count_values($dates_new);
                            $booked_dates_arr = array_count_values($booked_dates);
                            //print_r($booking_settings);
                            $lockout = "";
                            if (isset($product_settings['booking_date_lockout'])) {
                                $lockout = $product_settings['booking_date_lockout'];
                            }
                            //echo "ehre".$lockout;
                            $new_arr_str = '';
                            foreach ($dates_new_arr as $k => $v) {
                                if ($v >= $lockout && $lockout != 0) {
                                    //print_r($v);
                                    //print_r($lockout);
                                    $date_temp = $k;
                                    $date = explode("-", $date_temp);
                                    $new_arr_str .= '"' . intval($date[0]) . "-" . intval($date[1]) . "-" . $date[2] . '",';
                                    $date_temp = "";
                                    //$new_arr_str .=  '"'.$k.'",';
                                }
                            }
                            //$new_arr_str = date('d-m-Y',$new_arr_str);
                            $new_arr_str = substr($new_arr_str, 0, strlen($new_arr_str) - 1);
                            //print_r($new_arr_str);
                            print "<input type='hidden' id='wapbk_admin_hidden_booked_dates_" . $_POST['order_item_id'] . "' name='wapbk_admin_hidden_booked_dates_" . $_POST['order_item_id'] . "' value='" . $new_arr_str . "'/>";
                            //checkout calendar booked dates
                            $blocked_dates = array();
                            $booked_dates_str = "";
                            foreach ($booked_dates_arr as $k => $v) {
                                if ($v >= $lockout && $lockout != 0) {
                                    $date_temp = $k;
                                    $date = explode("-", $date_temp);
                                    $date_without_zero_prefixed = intval($date[0]) . "-" . intval($date[1]) . "-" . $date[2];
                                    $booked_dates_str .= '"' . intval($date[0]) . "-" . intval($date[1]) . "-" . $date[2] . '",';
                                    $date_temp = "";
                                    $blocked_dates[] = $date_without_zero_prefixed;
                                    //	$new_arr_str .=  '"'.$k.'",';
                                }
                            }
                            if (isset($booked_dates_str)) {
                                $booked_dates_str = substr($booked_dates_str, 0, strlen($booked_dates_str) - 1);
                            } else {
                                $booked_dates_str = "";
                            }
                            print "<input type='hidden' id='wapbk_admin_hidden_booked_dates_checkout_" . $_POST['order_item_id'] . "' name='wapbk_admin_hidden_booked_dates_checkout_" . $_POST['order_item_id'] . "' value='" . $booked_dates_str . "'/>";
                            print '<input type="hidden" id="wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '" name="wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '" />';
                            print '<input type="hidden" id="wapbk_admin_hidden_date_checkout_' . $_POST['order_item_id'] . '" name="wapbk_admin_hidden_date_checkout_' . $_POST['order_item_id'] . '" />';
                        }
                        $method_to_show = 'check_for_time_slot_admin';
                        $options_checkin = $options_checkout = array();
                        //$options_checkin = $options_checkout = array();
                        $js_code = $blocked_dates_hidden_var = '';
                        $block_dates = array();
                        $block_dates = (array) apply_filters('bkap_block_dates', $prod_id, $blocked_dates);
                        //print_r($block_dates);exit;
                        if (isset($block_dates) && count($block_dates) > 0) {
                            $i = 1;
                            $bvalue = array();
                            $add_day = '';
                            $same_day = '';
                            foreach ($block_dates as $bkey => $bvalue) {
                                if (isset($bvalue['dates']) && count($bvalue['dates']) > 0) {
                                    $blocked_dates_str = '"' . implode('","', $bvalue['dates']) . '"';
                                } else {
                                    $blocked_dates_str = "";
                                }
                                /*	if ( ( isset($bvalue['field_name']) && $bvalue['field_name'] == '' )  || !isset($bvalue['field_name']) )	$bvalue['field_name'] = $i;
                                		 $fld_name = 'woobkap_'.str_replace(' ','_', $bvalue['field_name']);*/
                                $field_name = $i;
                                if (isset($bvalue['field_name']) && $bvalue['field_name'] != '') {
                                    $field_name = $bvalue['field_name'];
                                }
                                $fld_name = 'woobkap_' . str_replace(' ', '_', $field_name);
                                $fld_name_admin = $fld_name . '_' . $_POST['order_item_id'];
                                //echo $fld_name;
                                print "<input type='hidden' id='" . $fld_name_admin . "' name='" . $fld_name_admin . "' value='" . $blocked_dates_str . "'/>";
                                $i++;
                                if (isset($bvalue['add_days_to_charge_booking'])) {
                                    $add_day = $bvalue['add_days_to_charge_booking'];
                                }
                                if ($add_day == '') {
                                    $add_day = 0;
                                }
                                print "<input type='hidden' id='add_days_" . $_POST['order_item_id'] . "' name='add_days_'" . $_POST['order_item_id'] . "' value='" . $blocked_dates_str . "'/>";
                                if (isset($bvalue['same_day_booking'])) {
                                    $same_day = $bvalue['same_day_booking'];
                                }
                                print "<input type='hidden' id='wapbk_admin_same_day_" . $_POST['order_item_id'] . "' name='wapbk_admin_same_day_" . $_POST['order_item_id'] . "' value='" . $same_day . "'/>";
                            }
                            //	if (!isset($bvalue['date_label'])) $bvalue['date_label'] = 'Unavailable for Booking';
                            if (isset($bvalue['date_label']) && $bvalue['date_label'] != '') {
                                $date_label = $bvalue['date_label'];
                            } else {
                                $date_label = 'Unavailable for Booking';
                            }
                            //if (isset($bvalue['add_days_to_charge_booking']) && $bvalue['add_days_to_charge_booking'] == '') $add_day = 0;
                            $js_code = '
						var ' . $fld_name_admin . ' = eval("["+jQuery("#' . $fld_name_admin . '").val()+"]");
						for (i = 0; i < ' . $fld_name_admin . '.length; i++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,' . $fld_name_admin . ') != -1 )
							{
								//alert();
								return [false, "", "' . $date_label . '"];
							}
						}
					';
                            $js_block_date = '
						var ' . $fld_name_admin . ' = eval("["+jQuery("#' . $fld_name_admin . '").val()+"]");
						var date = new_end = new Date(CheckinDate);
						var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
						//alert(count);
						for (var i = 1; i<= count;i++)
						{
						if( jQuery.inArray(d + "-" + (m+1) + "-" + y,' . $fld_name_admin . ') != -1 )
						{
						jQuery("#wapbk_hidden_date_checkout").val("");
						jQuery("#booking_calender_checkout").val("");
						jQuery( ".single_add_to_cart_button" ).hide();
						jQuery( ".quantity" ).hide();
						CalculatePrice = "N";
						alert("Some of the dates in the selected range are on rent. Please try another date range.");
						break;
					}
					new_end = new Date(ad(new_end,1));
					//alert(new_end);
					var m = new_end.getMonth(), d = new_end.getDate(), y = new_end.getFullYear();
					}';
                        }
                        if (isset($product_settings['booking_enable_multiple_day']) && $product_settings['booking_enable_multiple_day'] == 'on') {
                            //woocommerce_add_order_item_meta( $item_number,get_option("checkout.date-label"),'');
                            $meta_id_next = $meta_id + 1;
                            $meta_ids[$cart_item_key][$i] = $meta_id_next;
                            echo '<tr data-meta_id="' . $meta_id_next . '"><td><input type="text" name="meta_key[' . $meta_id_next . ']" value="' . strip_tags(get_option("checkout.item-meta-date")) . '" /></td><td><input type="text" name="meta_value[' . $meta_id_next . ']" value="" /></td><td width="1%"><button class="remove_order_item_meta button">&times;</button></td></tr>';
                            $options_checkout[] = "minDate: 1";
                            $options_checkin[] = 'onClose: function( selectedDate, inst ) {
						
						var monthValue = inst.selectedMonth+1;
						var dayValue = inst.selectedDay;
						var yearValue = inst.selectedYear;
						
						var current_sel_dt = dayValue + "-" + monthValue + "-" + yearValue;
						
						jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val(current_sel_dt);
						jQuery( "tr[data-meta_id=\\"' . $meta_id_next . '\\"]" ).show();
						if(jQuery("#admin_block_option_enabled_' . $_POST['order_item_id'] . '").val() == "on")
						{
							///alert();
							//jQuery("#show_time_slot").show();
							var nod= parseInt(jQuery("#admin_block_option_number_of_day_' . $_POST['order_item_id'] . '").val(),10);										if(jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val() != "")
							{
								var num_of_day= jQuery("#admin_block_option_number_of_day_' . $_POST['order_item_id'] . '").val();
								var split = jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val().split("-");
								split[1] = split[1] - 1;		
								var minDate = new Date(split[2],split[1],split[0]);
									
								minDate.setDate(minDate.getDate() + nod ); 
								//var kc=new Date(Date.parse(selectedDate)); 
								//kc.setDate(kc.getDate() + nod );								
								//var newDate = kc.toDateString(); 
															  
								//newDate = new Date( Date.parse( newDate ) );
			   					console.log(minDate);
														 
			   					jQuery("input[name=\\"meta_value[' . $meta_id_next . ']\\"]").datepicker("setDate",minDate);

 			   												
								//var objDate= jQuery( "#admin_booking_calender_checkout").datepicker("getDate");
								//var strDate = objDate.getDate() + "-" + (objDate.getMonth() + 1) + "-" + objDate.getFullYear();
															
								//jQuery("#wapbk_hidden_date_checkout").val(strDate);
															
								// calculate_price();
															 
								// disabled calendar	
								 //jQuery( "#booking_calender_checkout" ).prop("disabled", true);
								 //jQuery("#show_time_slot").hide();
								//jQuery(".amount").hide();
							}
						}
						else
						{
							if (jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val() != "")
							{
								if(jQuery("#wapbk_admin_same_day_' . $_POST['order_item_id'] . '").val() == "on")
								{
									if (jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val() != "")
									{
										var split = jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val().split("-");
										split[1] = split[1] - 1;
										var minDate = new Date(split[2],split[1],split[0]);
							
										minDate.setDate(minDate.getDate());
										//alert(minDate);
										jQuery( "input[name=\\"meta_value[' . $meta_id_next . ']\\"]" ).datepicker( "option", "minDate", minDate);
									}
								}
								else
								{
									var split = jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val().split("-");
									split[1] = split[1] - 1;
									var minDate = new Date(split[2],split[1],split[0]);
							
									minDate.setDate(minDate.getDate() + 1);
										//alert(minDate);
									jQuery( "input[name=\\"meta_value[' . $meta_id_next . ']\\"]" ).datepicker( "option", "minDate", minDate);
								}
							}
						}
						
						}';
                            $options_checkout[] = "onSelect: get_per_night_price";
                            $options_checkin[] = "onSelect: set_checkin_date";
                            $options_checkout[] = "beforeShowDay: check_booked_dates";
                            $options_checkin[] = "beforeShowDay: check_booked_dates";
                        } else {
                            if (isset($product_settings['booking_enable_time']) && $product_settings['booking_enable_time'] == 'on') {
                                $meta_id_next = $meta_id + 1;
                                $meta_ids[$cart_item_key][$i] = $meta_id_next;
                                //woocommerce_add_order_item_meta( $item_number,get_option('book.time-label'),'');
                                echo '<tr data-meta_id="' . $meta_id_next . '"><td><input type="text" name="meta_key[' . $meta_id_next . ']" value="' . get_option('book.time-label') . '" /></td><td><input type="text" name="meta_value[' . $meta_id_next . ']" value="" /></td><td width="1%"><button class="remove_order_item_meta button">&times;</button></td></tr>';
                                //$meta = $order->has_meta($item_number);
                                $options_checkin[] = "beforeShowDay: show_book";
                                $options_checkin[] = "onSelect: show_times";
                                $options_checkin[] = 'onClose: function( selectedDate, inst ) {
						
						var monthValue = inst.selectedMonth+1;
						var dayValue = inst.selectedDay;
						var yearValue = inst.selectedYear;
						
						var current_sel_dt = dayValue + "-" + monthValue + "-" + yearValue;
						
						jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val(current_sel_dt);
						jQuery( "tr[data-meta_id=\\"' . $meta_id_next . '\\"]" ).show();
						}';
                            } else {
                                $options_checkin[] = 'onClose: function( selectedDate, inst ) {
						
						var monthValue = inst.selectedMonth+1;
						var dayValue = inst.selectedDay;
						var yearValue = inst.selectedYear;
						
						var current_sel_dt = dayValue + "-" + monthValue + "-" + yearValue;
						
						jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val(current_sel_dt);
						}';
                                $options_checkin[] = "beforeShowDay: show_book";
                                $options_checkin[] = "onSelect: show_times";
                            }
                        }
                        $options_checkin_str = '';
                        if (count($options_checkin) > 0) {
                            $options_checkin_str = implode(',', $options_checkin);
                        }
                        $options_checkout_str = '';
                        if (count($options_checkout) > 0) {
                            $options_checkout_str = implode(',', $options_checkout);
                        }
                        $meta_ids_str = '';
                        if (count($meta_ids) > 0) {
                            $meta_ids_str = implode(',', $meta_ids[$cart_item_key]);
                        }
                        echo '<input type="hidden" name="meta_ids' . $cart_item_key . '" id="meta_ids' . $cart_item_key . '" value="' . $meta_ids_str . '" />';
                        print '
					<script type="text/javascript">
					jQuery(document).ready(function()
						{	
							jQuery.extend(jQuery.datepicker, { afterShow: function(event)
							{
								jQuery.datepicker._getInst(event.target).dpDiv.css("z-index", 9999);
							}});
						
						var today = new Date();
						jQuery(function() {
						jQuery( "tr[data-meta_id=\\"' . $meta_id_next . '\\"]" ).hide();
					    jQuery( "input[name=\\"meta_value[' . $meta_id . ']\\"]" ).datepicker({
							beforeShow: avd,
							minDate:today,
							dateFormat: "' . $saved_settings->booking_date_format . '",						
							numberOfMonths: parseInt(' . $saved_settings->booking_months . '),
							' . $options_checkin_str . ' ,
					}).focus(function (event)
					{
						jQuery.datepicker.afterShow(event);
					});
					});
					jQuery( "input[name=\\"meta_value[' . $meta_id . ']\\"]" ).wrap("<div class=\\"hasDatepicker\\"></div>");
					jQuery( "input[name=\\"meta_value[' . $meta_id . ']\\"]" ).attr("id","admin_booking_calender_' . $meta_id . '");
					jQuery( "input[name=\\"meta_value[' . $meta_id_next . ']\\"]" ).attr("id","admin_booking_calender_checkout_' . $meta_id_next . '");
					});
				
					';
                        //if (isset($product_settings['booking_enable_timeslot']) == 'on')
                        if (isset($product_settings['booking_enable_multiple_day']) && $product_settings['booking_enable_multiple_day'] == 'on') {
                            print 'jQuery("input[name=\\"meta_value[' . $meta_id_next . ']\\"]").datepicker({
									dateFormat: "' . $saved_settings->booking_date_format . '",
									numberOfMonths: parseInt(' . $saved_settings->booking_months . '),
									' . $options_checkout_str . ' ,
									onClose: function( selectedDate ) {
									jQuery( "input[name=\\"meta_value[' . $meta_id . ']\\"]" ).datepicker( "option", "maxDate", selectedDate );
						},
						}).focus(function (event)
						{
									jQuery.datepicker.afterShow(event);
						});
						jQuery( "input[name=\\"meta_value[' . $meta_id_next . ']\\"]" ).wrap("<div class=\\"hasDatepicker\\"></div>");
						';
                        }
                        print '
					function check_booked_dates(date)
					{
						var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
						var holidayDates = eval("["+jQuery("#wapbk_admin_booking_holidays_' . $_POST['order_item_id'] . '").val()+"]");
						var globalHolidays = eval("["+jQuery("#wapbk_admin_booking_global_holidays_' . $_POST['order_item_id'] . '").val()+"]");
						//alert(jQuery("#wapbk_admin_hidden_booked_dates_' . $_POST['order_item_id'] . '").val());
						var bookedDates=eval("[" + jQuery("#wapbk_admin_hidden_booked_dates_' . $_POST['order_item_id'] . '").val() + "]");
						var bookedDatesCheckout = eval("["+jQuery("#wapbk_admin_hidden_booked_dates_checkout_' . $_POST['order_item_id'] . '").val()+"]");

						var block_option_start_day= jQuery("#admin_block_option_start_day_' . $_POST['order_item_id'] . '").val();
					 	var block_option_price= jQuery("#admin_block_option_price_' . $_POST['order_item_id'] . '").val();
						//alert(block_option_start_day);
						for (iii = 0; iii < globalHolidays.length; iii++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,globalHolidays) != -1 )
							{
								return [false, "", "Holiday"];
							}
						}
						for (ii = 0; ii < holidayDates.length; ii++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,holidayDates) != -1 )
							{
								return [false, "", "Holiday"];
							}
						}
						var id_booking = jQuery(this).attr("id");
						//alert(id_booking);
						if (id_booking == "admin_booking_calender_' . $meta_id . '" || id_booking == "inline_calendar")
						{
							for (iii = 0; iii < bookedDates.length; iii++)
							{
								//alert(bookedDates);
								if( jQuery.inArray(d + "-" + (m+1) + "-" + y,bookedDates) != -1 )
								{
									return [false, "", "Unavailable for Booking"];
								}
							}
						}	
						if (id_booking == "admin_booking_calender_checkout_' . $meta_id_next . '" || id_booking == "inline_calendar_checkout") 
						{
							//alert();
							for (iii = 0; iii < bookedDatesCheckout.length; iii++)
							{
								//alert(bookedDates);
								if( jQuery.inArray(d + "-" + (m+1) + "-" + y,bookedDatesCheckout) != -1 )
								{
									return [false, "", "Unavailable for Booking"];
								}
							}
						}
						var block_option_enabled= jQuery("#admin_block_option_enabled_' . $_POST['order_item_id'] . '").val();
	
						if (block_option_enabled =="on")
						{
							if ( id_booking == "admin_booking_calender_' . $meta_id . '" || id_booking == "inline_calendar" )
							{
								//alert(date.getDay());
								if (block_option_start_day == date.getDay())
					            {
					              return [true];
					            }
					            else
					            {
									return [false];
					            }
				       		}
				       		var bcc_date=jQuery( "input[name=\\"meta_value[' . $meta_id_next . ']\\"]").datepicker("getDate");
							//alert(bcc_date);
							if(bcc_date != null)
							{
								var dd = bcc_date.getDate();
								var mm = bcc_date.getMonth()+1; //January is 0!
								var yyyy = bcc_date.getFullYear();
								var checkout = dd + "-" + mm + "-"+ yyyy;
								jQuery("#wapbk_admin_hidden_date_checkout_' . $_POST['order_item_id'] . '").val(checkout);

						   		if (id_booking == "admin_booking_calender_checkout_' . $meta_id_next . '" || id_booking == "inline_calendar_checkout"){

 
				       			if (Date.parse(bcc_date) === Date.parse(date)){
				       					return [true];
				       			}else{
				       					return [false];
				       			}
							}
				       		}
				       	}
						' . $js_code . '
						return [true];
					}
					function show_book(date)
					{
						//var date = new Date();
						var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
						// .html() is used when we have zip code groups enabled
						var deliveryDates = eval("["+jQuery("#wapbk_admin_booking_dates_' . $_POST['order_item_id'] . '").val()+"]");
						
						var holidayDates = eval("["+jQuery("#wapbk_admin_booking_holidays_' . $_POST['order_item_id'] . '").val()+"]");
							
						var globalHolidays = eval("["+jQuery("#wapbk_admin_booking_global_holidays_' . $_POST['order_item_id'] . '").val()+"]");
						
						//Lockout Dates
						var lockoutdates = eval("["+jQuery("#wapbk_admin_lockout_days_' . $_POST['order_item_id'] . '").val()+"]");
						
						var bookedDates = eval("["+jQuery("#wapbk_admin_hidden_booked_dates_' . $_POST['order_item_id'] . '").val()+"]");
						var dt = new Date();
						var today = dt.getMonth() + "-" + dt.getDate() + "-" + dt.getFullYear();
						for (iii = 0; iii < lockoutdates.length; iii++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,lockoutdates) != -1 )
							{
								return [false, "", "Booked"];
	
							}
						}	
						
						for (iii = 0; iii < globalHolidays.length; iii++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,globalHolidays) != -1 )
							{
								return [false, "", "Holiday"];
							}
						}
						
						for (ii = 0; ii < holidayDates.length; ii++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,holidayDates) != -1 )
							{
								return [false, "", "Holiday"];
							}
						}
					
						for (i = 0; i < bookedDates.length; i++)
						{
							//alert(bookedDates);
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,bookedDates) != -1 )
							{
								return [false, "", "Unavailable for Booking"];
							}
						}
						 	
						for (i = 0; i < deliveryDates.length; i++)
						{
							if( jQuery.inArray(d + "-" + (m+1) + "-" + y,deliveryDates) != -1 )
							{
								return [true];
							}
						}

						var day = "booking_weekday_" + date.getDay();
						var name = day+"_"+' . $_POST['order_item_id'] . ';
						if (jQuery("#wapbk_admin_"+name).val() == "on")
						{
							return [true];
						}
						return [false];
					}
							
					function show_times(date,inst)
					{
						var monthValue = inst.selectedMonth+1;
						var dayValue = inst.selectedDay;
						var yearValue = inst.selectedYear;

						var current_dt = dayValue + "-" + monthValue + "-" + yearValue;
						var sold_individually = jQuery("#wapbk_sold_individually_' . $_POST['order_item_id'] . '").val();
						jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val(current_dt);
						if (jQuery("#wapbk_admin_bookingEnableTime_' . $_POST['order_item_id'] . '").val() == "on" && jQuery("#wapbk_admin_booking_times_' . $_POST['order_item_id'] . '").val() != "")
						{
							//jQuery.datepicker.formatDate("d-m-yy", new Date(yearValue, dayValue, monthValue) );
							var time_slots_arr = jQuery("#wapbk_admin_booking_times_' . $_POST['order_item_id'] . '").val();
							var data = {
								current_date: current_dt,
								post_id: "' . $prod_id . '",
								action: "' . $method_to_show . '"
								
								};
										
								jQuery.post("' . get_admin_url() . '/admin-ajax.php", data, function(response)
								{
								jQuery( "tr[data-meta_id=\\"' . $meta_id_next . '\\"]" ).show();
							
								var select = jQuery("<select style=\\"width:100%;\\">");
								select.append(jQuery("<option>").val("Choose a Time").html("Choose an option"));
								//alert(response);
								var time_slots = response.split("|");
								for (var i = 0; i <= time_slots.length; ++i) 
								{
									if(time_slots[i] != "" && time_slots[i] != null)
										select.append(jQuery("<option>").val(time_slots[i]).html(time_slots[i]));
								}
								//response;
								//alert(' . $meta_id_next . ');
								select.val(1).attr({name: "meta_value[' . $meta_id_next . ']"}).change(function(){
								    
								});
								jQuery("input[name=\\"meta_value[' . $meta_id_next . ']\\"]").replaceWith(select);
								//alert("Got this from the server: " + response);
								jQuery( "#ajax_img" ).hide();
								jQuery("#show_time_slot").html(response);
								jQuery("#time_slot").change(function()
								{
									if ( jQuery("#time_slot").val() != "" )
									{
										jQuery( ".single_add_to_cart_button" ).show();
										if(sold_individually == "yes")
										{
											jQuery( ".quantity" ).hide();
										}
										else
										{
											jQuery( ".quantity" ).show();
										}
							
									}
									else if ( jQuery("#time_slot").val() == "" )
									{
										jQuery( ".single_add_to_cart_button" ).hide();
										jQuery( ".quantity" ).hide();
									}
								})
								
							});
						}
						else
						{
							if ( jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val() != "" )
							{
								var data = {
								current_date: current_dt,
								post_id: "' . $prod_id . '", 
								action: "insert_admin_date"
								};
								jQuery.post("' . get_admin_url() . '/admin-ajax.php", data, function(response)
								{
									jQuery( ".single_add_to_cart_button" ).show();
									if(sold_individually == "yes")
										{
											jQuery( ".quantity" ).hide();
										}
										else
										{
											jQuery( ".quantity" ).show();
										}
							
								});
							}
							else if ( jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val() == "" )
							{
								jQuery( ".single_add_to_cart_button" ).hide();
								jQuery( ".quantity" ).hide();
							}
						}
					}
							
					function set_checkin_date(date,inst)
					{
						var monthValue = inst.selectedMonth+1;
						var dayValue = inst.selectedDay;
						var yearValue = inst.selectedYear;

						var current_dt = dayValue + "-" + monthValue + "-" + yearValue;
						jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val(current_dt);
						// Check if any date in the selected date range is unavailable
						if (jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val() != "" )
						{
							var CalculatePrice = "Y";
							var split = jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val().split("-");
							split[1] = split[1] - 1;		
							var CheckinDate = new Date(split[2],split[1],split[0]);
								
							var split = jQuery("#wapbk_admin_hidden_date_checkout_' . $_POST['order_item_id'] . '").val().split("-");
							split[1] = split[1] - 1;
							var CheckoutDate = new Date(split[2],split[1],split[0]);
								
							var date = new_end = new Date(CheckinDate);
							var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
								
							var bookedDates = eval("["+jQuery("#wapbk_admin_hidden_booked_dates_' . $_POST['order_item_id'] . '").val()+"]");
							var holidayDates = eval("["+jQuery("#wapbk_admin_booking_holidays_' . $_POST['order_item_id'] . '").val()+"]");
							var globalHolidays = eval("["+jQuery("#wapbk_admin_booking_global_holidays_' . $_POST['order_item_id'] . '").val()+"]");
						
							var count = gd(CheckinDate, CheckoutDate, "days");
							//Locked Dates
							for (var i = 1; i<= count;i++)
								{
									if( jQuery.inArray(d + "-" + (m+1) + "-" + y,bookedDates) != -1 )
									{
										jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val("");
										jQuery("input[name=\\"meta_value[' . $meta_id . ']\\"]").val("");
										jQuery( ".single_add_to_cart_button" ).hide();
										jQuery( ".quantity" ).hide();
										CalculatePrice = "N";
										alert("Some of the dates in the selected range are unavailable. Please try another date range.");
										break;
									}
								new_end = new Date(ad(new_end,1));
								var m = new_end.getMonth(), d = new_end.getDate(), y = new_end.getFullYear();													
								}
							//Global Holidays
							var date = new_end = new Date(CheckinDate);
							var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
						
							for (var i = 1; i<= count;i++)
								{
									if( jQuery.inArray(d + "-" + (m+1) + "-" + y,globalHolidays) != -1 )
									{
										jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val("");
										jQuery("input[name=\\"meta_value[' . $meta_id . ']\\"]").val("");
										CalculatePrice = "N";
										alert("Some of the dates in the selected range are unavailable. Please try another date range.");
										break;
									}
								new_end = new Date(ad(new_end,1));
								var m = new_end.getMonth(), d = new_end.getDate(), y = new_end.getFullYear();													
								}
							//Product Holidays
							var date = new_end = new Date(CheckinDate);
							var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
						
							for (var i = 1; i<= count;i++)
								{
									if( jQuery.inArray(d + "-" + (m+1) + "-" + y,holidayDates) != -1 )
									{
										jQuery("#wapbk_admin_hidden_date_' . $_POST['order_item_id'] . '").val("");
										jQuery("input[name=\\"meta_value[' . $meta_id . ']\\"]").val("");
										CalculatePrice = "N";
										alert("Some of the dates in the selected range are unavailable. Please try another date range.");
										break;
									}
								new_end = new Date(ad(new_end,1));
								var m = new_end.getMonth(), d = new_end.getDate(), y = new_end.getFullYear();													
								}
							' . $js_block_date . '
							//if (CalculatePrice == "Y") calculate_price();
						}
					}
							
					function get_per_night_price(date,inst)
					{
						var monthValue = inst.selectedMonth+1;
						var dayValue = inst.selectedDay;
						var yearValue = inst.selectedYear;

						var current_dt = dayValue + "-" + monthValue + "-" + yearValue;
						jQuery("#wapbk_admin_hidden_date_checkout_' . $_POST['order_item_id'] . '").val(current_dt);
						
					}
					
					</script>
					';
                        //echo "CHECK<pre>";print_r($a);echo "</pre>";
                        //return $a;*/
                    }
                    //print_r($meta_ids);
                }
            } else {
                echo '<tr data-meta_id="' . $meta_id . '"><td><input type="text" name="meta_key[' . $meta_id . ']" value="" /><textarea name="meta_key[' . $meta_id . ']" value="" /></td><td width="1%"><button class="remove_order_item_meta button">&times;</button></td></tr>';
            }
            die;
        }
    function woocommerce_etsyi_submenu_page_callback()
    {
        global $wpdb, $oscdb, $import_cat_counter, $import_prod_counter;
        if (!empty($_POST)) {
            $oscdb = new wpdb(trim($_POST['store_user']), trim($_POST['store_pass']), trim($_POST['store_dbname']), trim($_POST['store_host']));
            if ($oscdb->ready) {
                echo '<p>Starting...<em>(If the page stops loading or shows a timeout error, then just refresh the page and the importer will continue where it left off.  If you are using a shared server and are importing a lot of products you may need to refresh several times)</p>';
                // Do customer import
                if ($_POST['dtype']['customers'] == 1) {
                    $country_data = $oscdb->get_results("SELECT * FROM countries", ARRAY_A);
                    $countries_id = array();
                    foreach ($country_data as $cdata) {
                        $countries_id[$cdata['countries_id']] = $cdata;
                    }
                    $zones = array();
                    $zone_data = $oscdb->get_results("SELECT zone_id, zone_code FROM zones", ARRAY_A);
                    foreach ($zone_data as $z) {
                        $zones[$z['zone_id']] = $z['zone_code'];
                    }
                    if ($customers = $oscdb->get_results("SELECT c.customers_id, c.customers_firstname, c.customers_lastname, c.customers_telephone, c.customers_email_address, ab.entry_country_id, ab.entry_lastname, ab.entry_firstname, ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_state, ab.entry_zone_id FROM customers c, address_book ab WHERE c.customers_id=ab.customers_id AND c.customers_default_address_id=ab.address_book_id", ARRAY_A)) {
                        foreach ($customers as $customer) {
                            if (!email_exists($customer['customers_email_address'])) {
                                $original = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $customer['customers_firstname'] . $customer['customers_lastname']));
                                $user_name = $original;
                                $i = 1;
                                while ($user_id = username_exists($user_name)) {
                                    $user_name = $original . $i;
                                    $i++;
                                }
                                $random_password = wp_generate_password();
                                $user_id = wp_create_user($user_name, $random_password, $customer['customers_email_address']);
                                $data = array('first_name' => $customer['customers_firstname'], 'last_name' => $customer['customers_lastname'], 'billing_country' => $countries_id[$customer['entry_country_id']]['countries_iso_code_2'], 'billing_first_name' => $customer['entry_firstname'], 'billing_last_name' => $customer['entry_lastname'], 'billing_address_1' => $customer['entry_street_address'], 'billing_address_2' => $customer['entry_suburb'], 'billing_city' => $customer['entry_city'], 'billing_state' => $customer['entry_state'] != '' ? $customer['entry_state'] : $zones[$customer['entry_zone_id']], 'billing_postcode' => $customer['entry_postcode'], 'billing_email' => $customer['customers_email_address'], 'billing_phone' => $customer['customers_telephone'], 'shipping_country' => $countries_id[$customer['entry_country_id']]['countries_iso_code_2'], 'shipping_first_name' => $customer['entry_firstname'], 'shipping_last_name' => $customer['entry_lastname'], 'shipping_address_1' => $customer['entry_street_address'], 'shipping_address_2' => $customer['entry_suburb'], 'shipping_city' => $customer['entry_city'], 'shipping_state' => $customer['entry_state'] != '' ? $customer['entry_state'] : $zones[$customer['entry_zone_id']], 'shipping_postcode' => $customer['entry_postcode'], 'osc_id' => $customer['customers_id']);
                                foreach ($data as $k => $v) {
                                    update_user_meta($user_id, $k, $v);
                                }
                                if ($user_id > 1) {
                                    wp_update_user(array('ID' => $user_id, 'role' => 'customer'));
                                }
                                $import_customer_counter++;
                            }
                        }
                    }
                }
                if ($_POST['dtype']['products'] == 1) {
                    woocommerce_osc_run_cats();
                    // Get all categories by OSC cat ID
                    $categories = array();
                    $terms = get_terms('product_cat', array('hide_empty' => 0));
                    foreach ($terms as $term) {
                        $o = get_woocommerce_term_meta($term->term_id, 'osc_id', true);
                        $categories[$o] = (int) $term->term_id;
                    }
                    // Import the products
                    if ($products = $oscdb->get_results("SELECT p.*, pd.*, p2c.categories_id FROM products p, products_description pd, products_to_categories p2c WHERE p.products_id=pd.products_id AND pd.language_id=1 AND p.products_id=p2c.products_id GROUP BY p.products_id", ARRAY_A)) {
                        foreach ($products as $product) {
                            $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any', 'meta_query' => array(array('key' => 'osc_id', 'value' => $product['products_id']))));
                            if (empty($existing_product)) {
                                $product_id = wp_insert_post(array('post_title' => $product['products_name'], 'post_content' => $product['products_description'], 'post_status' => 'publish', 'post_type' => 'product', 'post_author' => 1));
                                update_post_meta($product_id, 'osc_id', $product['products_id']);
                                wp_set_object_terms($product_id, 'simple', 'product_type');
                                wp_set_object_terms($product_id, (int) $categories[$product['categories_id']], 'product_cat');
                                update_post_meta($product_id, '_sku', $product['products_model']);
                                update_post_meta($product_id, '_regular_price', $product['products_price']);
                                update_post_meta($product_id, '_price', $product['products_price']);
                                update_post_meta($product_id, '_visibility', 'visible');
                                update_post_meta($product_id, '_stock_status', $product['products_status'] ? 'instock' : 'outofstock');
                                update_post_meta($product_id, '_manage_stock', '1');
                                update_post_meta($product_id, '_stock', $product['products_quantity']);
                                $import_prod_counter++;
                                if ($special = $oscdb->get_row("SELECT specials_new_products_price, expires_date FROM specials WHERE status=1 AND products_id='" . $product_id . "' LIMIT 1", ARRAY_A)) {
                                    update_post_meta($product_id, '_sale_price', $special['specials_new_products_price']);
                                    $special['expires_date'] = strtotime($special['expires_date']);
                                    if ($special['expires_date'] > time()) {
                                        update_post_meta($product_id, '_sale_price_dates_to', date("Y-m-d", $special['expires_date']));
                                        update_post_meta($product_id, '_sale_price_dates_from', date("Y-m-d"));
                                    }
                                }
                                $attach_id = 0;
                                if ($product['products_image'] != '') {
                                    $url = rtrim($_POST['store_url'], '/') . '/images/' . urlencode($product['products_image']);
                                    $attach_id = woocommerce_osc_import_image($url);
                                }
                                if ($attach_id > 0) {
                                    set_post_thumbnail($product_id, $attach_id);
                                }
                                // Handle attributes
                                if ($attributes = $oscdb->get_results("SELECT po.products_options_name, pov.products_options_values_name FROM products_attributes pa, products_options po, products_options_values pov WHERE pa.products_id='" . $product['products_id'] . "' AND  pov.products_options_values_id = pa.options_values_id AND pov.language_id=po.language_id AND po.language_id=1 AND pa.options_id=products_options_id", ARRAY_A)) {
                                    wp_set_object_terms($product_id, 'variable', 'product_type');
                                    $attrib_array = array();
                                    $attrib_combo = array();
                                    $max_price = $product['products_price'];
                                    $min_price = $product['products_price'];
                                    foreach ($attributes as $attribute) {
                                        $slug = sanitize_title($attribute['products_options_name']);
                                        $attrib_array[$slug] = array('name' => $attribute['products_options_name'], 'value' => ltrim($attrib_array[$slug]['value'] . ' | ' . $attribute['products_options_values_name'], ' | '), 'position' => 0, 'is_visible' => 1, 'is_variation' => 1, 'is_taxonomy' => 0);
                                        $attrib_combo[$slug][] = array($attribute['products_options_values_name'], ($attribute['price_prefix'] == '-' ? '-' : '') . $attribute['options_values_price']);
                                    }
                                    // Now it gets tricky...
                                    $combos = woocommerce_osc_cartesian_product($attrib_combo);
                                    foreach ($combos as $combo) {
                                        $variation_id = wp_insert_post(array('post_title' => 'Product ' . $product_id . ' Variation', 'post_content' => '', 'post_status' => 'publish', 'post_type' => 'product_variation', 'post_author' => 1, 'post_parent' => $product_id));
                                        $opt_price = $product['products_price'];
                                        $special_price = $special['specials_new_products_price'];
                                        foreach ($combo as $k => $v) {
                                            update_post_meta($variation_id, 'attribute_' . $k, $v[0]);
                                            $opt_price += $v[1];
                                            $special_price += $v[1];
                                        }
                                        update_post_meta($variation_id, '_sku', $product['products_model']);
                                        update_post_meta($variation_id, '_regular_price', $opt_price);
                                        update_post_meta($variation_id, '_price', $opt_price);
                                        update_post_meta($variation_id, '_thumbnail_id', 0);
                                        update_post_meta($variation_id, '_stock', $product['products_quantity']);
                                        if ($special) {
                                            update_post_meta($variation_id, '_sale_price', $special_price);
                                            if ($special['expires_date'] > time()) {
                                                update_post_meta($variation_id, '_sale_price_dates_to', date("Y-m-d", $special['expires_date']));
                                                update_post_meta($variation_id, '_sale_price_dates_from', date("Y-m-d"));
                                            }
                                        }
                                        if ($opt_price > $max_price) {
                                            $max_price = $opt_price;
                                        }
                                        if ($opt_price < $min_price) {
                                            $min_price = $opt_price;
                                        }
                                    }
                                    update_post_meta($product_id, '_product_attributes', $attrib_array);
                                    update_post_meta($product_id, '_max_variation_regular_price', $max_price);
                                    update_post_meta($product_id, '_min_variation_regular_price', $min_price);
                                    update_post_meta($product_id, '_max_variation_price', $max_price);
                                    update_post_meta($product_id, '_min_variation_price', $min_price);
                                }
                            }
                        }
                    }
                }
                if ($_POST['dtype']['orders'] == 1) {
                    $customers = $wpdb->get_results("SELECT ID FROM {$wpdb->users}", ARRAY_A);
                    $customer_id = array();
                    foreach ($customers as $c) {
                        $osc_id = get_user_meta($c['ID'], 'osc_id', true);
                        $customer_id[$osc_id] = $c['ID'];
                    }
                    $product_id = array();
                    $products_query = $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE post_type='product'", ARRAY_A);
                    foreach ($products_query as $p) {
                        $osc_id = get_post_meta($p['ID'], 'osc_id', true);
                        $product_id[$osc_id] = $p['ID'];
                    }
                    $country_data = $oscdb->get_results("SELECT * FROM countries", ARRAY_A);
                    $countries_name = array();
                    foreach ($country_data as $cdata) {
                        $countries_name[$cdata['countries_name']] = $cdata;
                    }
                    if ($orders = $oscdb->get_results("SELECT * FROM orders ORDER BY orders_id", ARRAY_A)) {
                        foreach ($orders as $order) {
                            $existing_order = get_posts(array('post_type' => 'shop_order', 'posts_per_page' => 1, 'post_status' => 'any', 'meta_query' => array(array('key' => 'osc_id', 'value' => $order['orders_id']))));
                            if (empty($existing_order)) {
                                $totals = array();
                                if ($total_query = $oscdb->get_results("SELECT * FROM orders_total WHERE orders_id='" . $order['orders_id'] . "'", ARRAY_A)) {
                                    foreach ($total_query as $t) {
                                        $totals[$t['class']] = $t;
                                    }
                                }
                                $order_key = 'order_' . wp_generate_password(13);
                                $data = array('post_type' => 'shop_order', 'post_date' => $order['date_purchased'], 'post_author' => $customer_id[$order['customers_id']], 'post_password' => $order_key, 'post_title' => 'Order &ndash; ' . date("M d, Y @ h:i A", strtotime($order['date_purchased'])), 'post_status' => 'publish');
                                $order_id = wp_insert_post($data);
                                $billing_namebits = explode(' ', $order['billing_name']);
                                $billing_firstname = $billing_namebits[0];
                                $billing_lastname = trim(str_replace($billing_namebits[0], '', $order['billing_name']));
                                $shipping_namebits = explode(' ', $order['delivery_name']);
                                $shipping_firstname = $shipping_namebits[0];
                                $shipping_lastname = trim(str_replace($shipping_namebits[0], '', $order['delivery_name']));
                                $meta_data = array('_billing_address_1' => $order['billing_street_address'], '_billing_address_2' => $order['billing_suburb'], '_wpas_done_all' => 1, '_billing_country' => $countries_name[$order['billing_country']]['countries_iso_code_2'], '_billing_first_name' => $billing_firstname, '_billing_last_name' => $billing_lastname, '_billing_company' => $order['billing_company'], '_billing_city' => $order['billing_city'], '_billing_state' => $order['billing_state'], '_billing_postcode' => $order['billing_postcode'], '_billing_phone' => $order['customers_telephone'], '_billing_email' => $order['customers_email_address'], '_shipping_country' => $countries_name[$order['delivery_country']]['countries_iso_code_2'], '_shipping_first_name' => $shipping_firstname, '_shipping_last_name' => $shipping_lastname, '_shipping_company' => $order['delivery_company'], '_shipping_address_1' => $order['delivery_street_address'], '_shipping_address_2' => $order['delivery_suburb'], '_shipping_city' => $order['delivery_city'], '_shipping_state' => $order['delivery_state'], '_shipping_postcode' => $order['delivery_postcode'], '_shipping_method_title' => $totals['ot_shipping']['title'], '_payment_method_title' => $order['payment_method'], '_order_shipping' => $totals['ot_shipping']['value'], '_order_discount' => $totals['ot_coupon']['value'] + $totals['ot_discount']['value'], '_order_tax' => $totals['ot_tax']['value'], '_order_shipping_tax' => 0, '_order_total' => $totals['ot_total']['value'], '_order_key' => $order_key, '_customer_user' => $customer_id[$order['customers_id']], '_order_currency' => $order['currency'], '_prices_include_tax' => 'no', 'osc_id' => $order['orders_id']);
                                foreach ($meta_data as $k => $v) {
                                    update_post_meta($order_id, $k, $v);
                                }
                                $order_import_counter++;
                                if ($order_products = $oscdb->get_results("SELECT * FROM orders_products WHERE orders_id='" . $order['orders_id'] . "'", ARRAY_A)) {
                                    foreach ($order_products as $product) {
                                        $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $product['products_name'], 'order_item_type' => 'line_item'));
                                        if ($item_id) {
                                            $item_meta = array('_qty' => $product['products_quantity'], '_product_id' => $product_id[$product['products_id']], '_line_subtotal' => $product['final_price'] * $product['products_quantity'], '_line_total' => $product['final_price'] * $product['products_quantity']);
                                            foreach ($item_meta as $k => $v) {
                                                woocommerce_add_order_item_meta($item_id, $k, $v);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if ($_POST['dtype']['pages'] == 1) {
                    $page_import_counter = 0;
                    if ($information_table = $oscdb->get_results("SHOW TABLES LIKE 'information'", ARRAY_A)) {
                        if ($information_pages = $oscdb->get_results("SELECT * FROM information WHERE language_id=1", ARRAY_A)) {
                            foreach ($information_pages as $information) {
                                $existing_page = $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE post_type='page' AND LOWER(post_title)='" . strtolower(esc_sql($information['information_title'])) . "'", ARRAY_A);
                                if (!$existing_page) {
                                    $existing_page = get_posts(array('post_type' => 'page', 'posts_per_page' => 1, 'post_status' => 'any', 'meta_query' => array(array('key' => 'osc_id', 'value' => $information['information_id']))));
                                    if (!$existing_page) {
                                        $data = array('post_type' => 'page', 'post_title' => $information['information_title'], 'post_content' => $information['information_description'], 'post_status' => 'publish');
                                        $page_id = wp_insert_post($data);
                                        update_post_meta($page_id, 'osc_id', $information['information_id']);
                                        $page_import_counter++;
                                    }
                                }
                            }
                        }
                    } else {
                        echo '<p class="notice">The information (pages) table does not exist in this osCommerce installation.</p>';
                    }
                }
                $success = true;
            } else {
                echo '<p class="notice">Could not connect to the osCommerce database</p>';
            }
        }
        if ($success) {
            echo '<h3>The oscommerce data was successfully imported</h3>';
            if ($_POST['dtype']['customers'] == 1) {
                echo '<p><strong>Customers Imported: ' . $import_customer_counter . '</p>';
            }
            if ($_POST['dtype']['orders'] == 1) {
                echo '<p><strong>Orders Imported: ' . $order_import_counter . '</p>';
            }
            if ($_POST['dtype']['products'] == 1) {
                echo '<p><strong>Categories Imported: ' . $import_cat_counter . '</p>';
                echo '<p><strong>Products Imported: ' . $import_prod_counter . '</p>';
            }
            if ($_POST['dtype']['pages'] == 1) {
                echo '<p><strong>Pages Imported: ' . $page_import_counter . '</p>';
            }
        } else {
            ?>
            <form action="<?php 
            echo $_SERVER['REQUEST_URI'];
            ?>
" method="post">
                <h3>Import data from osCommerce</h3>

                <p>
                    Enter your oscommerce database information (you will need remote access to your oscommerce database)
                </p>

                <p>
                    <label>osCommerce store URL: <input type="text" name="store_url"
                                                        value="<?php 
            echo $_POST['store_url'];
            ?>
"></label>
                </p>

                <p>
                    <label>osCommerce Database Host: <input type="text" name="store_host" value="localhost"></label></p>

                <p>
                    <label>osCommerce Database User: <input type="text" name="store_user"
                                                            value="<?php 
            echo $_POST['store_user'];
            ?>
"></label>
                </p>

                <p>
                    <label>osCommerce Database Password: <input type="text" name="store_pass"
                                                                value="<?php 
            echo $_POST['store_pass'];
            ?>
"></label>
                </p>

                <p>
                    <label>osCommerce Database Name: <input type="text" name="store_dbname"
                                                            value="<?php 
            echo $_POST['store_dbname'];
            ?>
"></label>
                </p>

                <p>
                    Data to Import:<br>
                    <label><input type="checkbox" name="dtype[customers]" value="1"> Customers (passwords will not be
                        transferred)</label>
                    <br>
                    <label><input type="checkbox" name="dtype[orders]" value="1"> Orders</label>
                    <br>
                    <label><input type="checkbox" name="dtype[products]" value="1"> Categories/Products</label>
                    <br>
                    <label><input type="checkbox" name="dtype[pages]" value="1"> Information Pages</label>
                </p>

                <p>
                    <input type="submit" value="Import Data" class="button button-primary button-large">
                </p>
            </form>
            <?php 
        }
    }
 /**
  * Output the form
  */
 public function output()
 {
     global $woocommerce;
     $this->errors = array();
     $step = 1;
     try {
         if (!empty($_POST) && !check_admin_referer('create_booking_notification')) {
             throw new Exception(__('Error - please try again', 'woocommerce-bookings'));
         }
         if (!empty($_POST['create_booking'])) {
             $customer_id = absint($_POST['customer_id']);
             $bookable_product_id = absint($_POST['bookable_product_id']);
             $create_order = isset($_POST['create_order']) ? 1 : 0;
             if (!$bookable_product_id) {
                 throw new Exception(__('Please choose a bookable product', 'woocommerce-bookings'));
             }
             $step++;
             $product = get_product($bookable_product_id);
             $booking_form = new WC_Booking_Form($product);
         } elseif (!empty($_POST['create_booking_2'])) {
             $customer_id = absint($_POST['customer_id']);
             $bookable_product_id = absint($_POST['bookable_product_id']);
             $create_order = absint($_POST['create_order']);
             $product = get_product($bookable_product_id);
             $booking_form = new WC_Booking_Form($product);
             $booking_data = $booking_form->get_posted_data($_POST);
             $booking_cost = number_format($booking_form->calculate_booking_cost($_POST), 2, '.', '');
             // Data to go into the booking
             $new_booking_data = array('product_id' => $product->id, 'resource_id' => isset($booking_data['_resource_id']) ? $booking_data['_resource_id'] : '', 'persons' => $booking_data['_persons'], 'cost' => $booking_cost, 'start_date' => $booking_data['_start_date'], 'end_date' => $booking_data['_end_date'], 'all_day' => $booking_data['_all_day'] ? 1 : 0);
             // Create order
             if ($create_order) {
                 $order_id = $this->create_order($booking_cost, $customer_id);
                 if (!$order_id) {
                     throw new Exception(__('Error: Could not create order', 'woocommerce-bookings'));
                 }
                 $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $product->get_title(), 'order_item_type' => 'line_item'));
                 if (!$item_id) {
                     throw new Exception(__('Error: Could not create item', 'woocommerce-bookings'));
                 }
                 // Add line item meta
                 woocommerce_add_order_item_meta($item_id, '_qty', 1);
                 woocommerce_add_order_item_meta($item_id, '_tax_class', $product->get_tax_class());
                 woocommerce_add_order_item_meta($item_id, '_product_id', $product->id);
                 woocommerce_add_order_item_meta($item_id, '_variation_id', '');
                 woocommerce_add_order_item_meta($item_id, '_line_subtotal', $booking_cost);
                 woocommerce_add_order_item_meta($item_id, '_line_total', $booking_cost);
                 woocommerce_add_order_item_meta($item_id, '_line_tax', 0);
                 woocommerce_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
                 // We have an item id
                 $new_booking_data['order_item_id'] = $item_id;
                 // Add line item data
                 foreach ($booking_data as $key => $value) {
                     if (strpos($key, '_') !== 0) {
                         woocommerce_add_order_item_meta($item_id, get_wc_booking_data_label($key, $product), $value);
                     }
                 }
             }
             // Create the booking itself
             $new_booking = get_wc_booking($new_booking_data);
             $new_booking->create($create_order ? 'unpaid' : 'pending');
             wp_safe_redirect(admin_url('post.php?post=' . ($create_order ? $order_id : $new_booking->id) . '&action=edit'));
             exit;
         }
     } catch (Exception $e) {
         $this->errors[] = $e->getMessage();
     }
     switch ($step) {
         case 1:
             include 'views/html-create-booking-page.php';
             break;
         case 2:
             include 'views/html-create-booking-page-2.php';
             break;
     }
 }
function tshirt_designer_add_order_item_meta($item_id, $cart_item)
{
    //order completed page. & admin
    if (!empty($cart_item['tshirt_designer_front_img']) || !empty($cart_item['tshirt_designer_back_img'])) {
        woocommerce_add_order_item_meta($item_id, 'tshirt_designer_front_img', $cart_item['tshirt_designer_front_img']);
        woocommerce_add_order_item_meta($item_id, 'tshirt_designer_back_img', $cart_item['tshirt_designer_back_img']);
    }
}
 function add_order_item_meta($item_id, $values)
 {
     if ($values['sample']) {
         woocommerce_add_order_item_meta($item_id, 'product type', 'sample');
     }
 }
 /**
  * Update recurring line taxes via AJAX
  * @see WC_Subscriptions_Order::calculate_recurring_line_taxes()
  * 
  * @since 4.4
  * @return JSON object with updated tax data
  */
 public static function ajax_update_recurring_tax()
 {
     global $wpdb;
     $woo_22_plus = version_compare(WOOCOMMERCE_VERSION, '2.2', '>=');
     check_ajax_referer('woocommerce-subscriptions', 'security');
     $order_id = absint($_POST['order_id']);
     $country = strtoupper(esc_attr($_POST['country']));
     // Step out of the way if the customer is not located in the US
     if ($country != 'US') {
         return;
     }
     $shipping = $_POST['shipping'];
     $line_subtotal = isset($_POST['line_subtotal']) ? esc_attr($_POST['line_subtotal']) : 0;
     $line_total = isset($_POST['line_total']) ? esc_attr($_POST['line_total']) : 0;
     // Set up WC_WooTax_Order object
     $order = self::get_order($order_id);
     // We only need to instantiate a WC_Tax object if we are using WooCommerce < 2.3
     if (!$woo_22_plus) {
         $tax = new WC_Tax();
     }
     $taxes = $shipping_taxes = array();
     $return = array();
     $item_data = array();
     $type_array = array();
     $product_id = '';
     if (isset($_POST['order_item_id'])) {
         $product_id = woocommerce_get_order_item_meta($_POST['order_item_id'], '_product_id');
     } elseif (isset($_POST['product_id'])) {
         $product_id = esc_attr($_POST['product_id']);
     }
     if (!empty($product_id) && WC_Subscriptions_Product::is_subscription($product_id)) {
         // Get product details
         $product = WC_Subscriptions::get_product($product_id);
         // Add product to items array
         $tic = get_post_meta($product->id, 'wootax_tic', true);
         $item_info = array('Index' => '', 'ItemID' => isset($_POST['order_item_id']) ? $_POST['order_item_id'] : $product_id, 'Qty' => 1, 'Price' => $line_subtotal > 0 ? $line_subtotal : $product->get_price(), 'Type' => 'cart');
         if (!empty($tic) && $tic) {
             $item_info['TIC'] = $tic;
         }
         $item_data[] = $item_info;
         $type_array[$_POST['order_item_id']] = 'cart';
         // Add shipping to items array
         if ($shipping > 0) {
             $item_data[] = array('Index' => '', 'ItemID' => WT_SHIPPING_ITEM, 'TIC' => WT_SHIPPING_TIC, 'Qty' => 1, 'Price' => $shipping, 'Type' => 'shipping');
             $type_array[WT_SHIPPING_ITEM] = 'shipping';
         }
         // Issue Lookup request
         $res = $order->do_lookup($item_data, $type_array, true);
         if (is_array($res)) {
             $return['recurring_shipping_tax'] = 0;
             $return['recurring_line_subtotal_tax'] = 0;
             $return['recurring_line_tax'] = 0;
             foreach ($res as $item) {
                 $item_id = $item->ItemID;
                 $item_tax = $item->TaxAmount;
                 if ($item_id == WT_SHIPPING_ITEM) {
                     $return['recurring_shipping_tax'] += $item_tax;
                 } else {
                     $return['recurring_line_subtotal_tax'] += $item_tax;
                     $return['recurring_line_tax'] += $item_tax;
                 }
             }
             $taxes[WT_RATE_ID] = $return['recurring_line_tax'];
             $shipping_taxes[WT_RATE_ID] = $return['recurring_shipping_tax'];
             // Get tax rates
             $tax_codes = array(WT_RATE_ID => apply_filters('wootax_rate_code', 'WOOTAX-RATE-DO-NOT-REMOVE'));
             // Remove old tax rows
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'recurring_tax' )", $order_id));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'recurring_tax'", $order_id));
             // Now merge to keep tax rows
             ob_start();
             foreach (array_keys($taxes + $shipping_taxes) as $key) {
                 $item = array();
                 $item['rate_id'] = $key;
                 $item['name'] = $tax_codes[$key];
                 $item['label'] = $woo_22_plus ? WC_Tax::get_rate_label($key) : $tax->get_rate_label($key);
                 $item['compound'] = $woo_22_plus ? WC_Tax::is_compound($key) : $tax->is_compound($key) ? 1 : 0;
                 $item['tax_amount'] = wc_round_tax_total(isset($taxes[$key]) ? $taxes[$key] : 0);
                 $item['shipping_tax_amount'] = wc_round_tax_total(isset($shipping_taxes[$key]) ? $shipping_taxes[$key] : 0);
                 if (!$item['label']) {
                     $item['label'] = WC()->countries->tax_or_vat();
                 }
                 // Add line item
                 $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'recurring_tax'));
                 // Add line item meta
                 if ($item_id) {
                     woocommerce_add_order_item_meta($item_id, 'rate_id', $item['rate_id']);
                     woocommerce_add_order_item_meta($item_id, 'label', $item['label']);
                     woocommerce_add_order_item_meta($item_id, 'compound', $item['compound']);
                     woocommerce_add_order_item_meta($item_id, 'tax_amount', $item['tax_amount']);
                     woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', $item['shipping_tax_amount']);
                 }
                 include plugin_dir_path(WC_Subscriptions::$plugin_file) . 'templates/admin/post-types/writepanels/order-tax-html.php';
             }
             $return['tax_row_html'] = ob_get_clean();
             echo json_encode($return);
         }
     }
     die;
 }
 /**
  * order_item_meta function.
  *
  * @param mixed $item_id
  * @param mixed $values
  */
 public function order_item_meta($item_id, $values)
 {
     if (!empty($values['food'])) {
         $product = $values['data'];
         // Add summary of details to line item
         foreach ($values['food'] as $key => $value) {
             if (strpos($key, '_') !== 0) {
                 if (is_array($value)) {
                     foreach ($value as $data) {
                         woocommerce_add_order_item_meta($item_id, get_takeaway_food_data_label($key, $product), $data);
                     }
                 } else {
                     woocommerce_add_order_item_meta($item_id, get_takeaway_food_data_label($key, $product), $value);
                 }
             }
         }
     }
 }
Esempio n. 14
0
 function wdm_add_values_to_order_item_meta($item_id, $values)
 {
     global $woocommerce, $wpdb;
     $user_custom_values = $values['wdm_user_custom_data_value'];
     $pdf_processing_status = 0;
     $pdf_processing_description = 'Waiting for execution of cron-job';
     if (!empty($user_custom_values)) {
         woocommerce_add_order_item_meta($item_id, 'wdm_user_custom_data', $user_custom_values);
         woocommerce_add_order_item_meta($item_id, 'pdf_processing_status', $pdf_processing_status);
         woocommerce_add_order_item_meta($item_id, 'pdf_processing_description', $pdf_processing_description);
     }
 }
 /**
  * Version 1.2 introduced a massive change to the order meta data schema. This function goes
  * through and upgrades the existing data on all orders to the new schema.
  *
  * The upgrade process is timeout safe as it keeps a record of the orders upgraded and only
  * deletes this record once all orders have been upgraded successfully. If operating on a huge
  * number of orders and the upgrade process times out, only the orders not already upgraded
  * will be upgraded in future requests that trigger this function.
  *
  * @since 1.2
  */
 private static function upgrade_database_to_1_2()
 {
     global $wpdb;
     set_transient('wc_subscriptions_is_upgrading', 'true', 60 * 2);
     // Get IDs only and use a direct DB query for efficiency
     $orders_to_upgrade = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'shop_order' AND post_parent = 0");
     $upgraded_orders = get_option('wcs_1_2_upgraded_order_ids', array());
     // Transition deprecated subscription status if we aren't in the middle of updating orders
     if (empty($upgraded_orders)) {
         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->usermeta} SET meta_value = replace( meta_value, 's:9:\"suspended\"', 's:7:\"on-hold\"' ) WHERE meta_key LIKE %s", '%_' . WC_Subscriptions_Manager::$users_meta_key));
         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->usermeta} SET meta_value = replace( meta_value, 's:6:\"failed\"', 's:9:\"cancelled\"' ) WHERE meta_key LIKE %s", '%_' . WC_Subscriptions_Manager::$users_meta_key));
     }
     $orders_to_upgrade = array_diff($orders_to_upgrade, $upgraded_orders);
     // Upgrade all _sign_up_{field} order meta to new order data format
     foreach ($orders_to_upgrade as $order_id) {
         $order = new WC_Order($order_id);
         // Manually check if a product in an order is a subscription, we can't use WC_Subscriptions_Order::order_contains_subscription( $order ) because it relies on the new data structure
         $contains_subscription = false;
         foreach ($order->get_items() as $order_item) {
             if (WC_Subscriptions_Product::is_subscription(WC_Subscriptions_Order::get_items_product_id($order_item))) {
                 $contains_subscription = true;
                 break;
             }
         }
         if (!$contains_subscription) {
             continue;
         }
         $trial_lengths = WC_Subscriptions_Order::get_meta($order, '_order_subscription_trial_lengths', array());
         $trial_length = array_pop($trial_lengths);
         $has_trial = !empty($trial_length) && $trial_length > 0 ? true : false;
         $sign_up_fee_total = WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_total', 0);
         // Create recurring_* meta data from existing cart totals
         $cart_discount = $order->get_cart_discount();
         update_post_meta($order_id, '_order_recurring_discount_cart', $cart_discount);
         $order_discount = $order->get_order_discount();
         update_post_meta($order_id, '_order_recurring_discount_total', $order_discount);
         $order_shipping_tax = get_post_meta($order_id, '_order_shipping_tax', true);
         update_post_meta($order_id, '_order_recurring_shipping_tax_total', $order_shipping_tax);
         $order_tax = get_post_meta($order_id, '_order_tax', true);
         // $order->get_total_tax() includes shipping tax
         update_post_meta($order_id, '_order_recurring_tax_total', $order_tax);
         $order_total = $order->get_total();
         update_post_meta($order_id, '_order_recurring_total', $order_total);
         // Set order totals to include sign up fee fields, if there was a sign up fee on the order and a trial period (other wise, the recurring totals are correct)
         if ($sign_up_fee_total > 0) {
             // Order totals need to be changed to be equal to sign up fee totals
             if ($has_trial) {
                 $cart_discount = WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_discount_cart', 0);
                 $order_discount = WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_discount_total', 0);
                 $order_tax = WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_tax_total', 0);
                 $order_total = $sign_up_fee_total;
             } else {
                 // No trial, sign up fees need to be added to order totals
                 $cart_discount += WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_discount_cart', 0);
                 $order_discount += WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_discount_total', 0);
                 $order_tax += WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_tax_total', 0);
                 $order_total += $sign_up_fee_total;
             }
             update_post_meta($order_id, '_order_total', $order_total);
             update_post_meta($order_id, '_cart_discount', $cart_discount);
             update_post_meta($order_id, '_order_discount', $order_discount);
             update_post_meta($order_id, '_order_tax', $order_tax);
         }
         // Make sure we get order taxes in WC 1.x format
         if (false == self::$is_wc_version_2) {
             $order_taxes = $order->get_taxes();
         } else {
             $order_tax_row = $wpdb->get_row($wpdb->prepare("\n\t\t\t\t\tSELECT * FROM {$wpdb->postmeta}\n\t\t\t\t\tWHERE meta_key = '_order_taxes_old'\n\t\t\t\t\tAND post_id = %s\n\t\t\t\t\t", $order_id));
             $order_taxes = (array) maybe_unserialize($order_tax_row->meta_value);
         }
         // Set recurring taxes to order taxes, if using WC 2.0, this will be migrated to the new format in @see self::upgrade_to_latest_wc()
         update_post_meta($order_id, '_order_recurring_taxes', $order_taxes);
         $sign_up_fee_taxes = WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_taxes', array());
         // Update order taxes to include sign up fee taxes
         foreach ($sign_up_fee_taxes as $index => $sign_up_tax) {
             if ($has_trial && $sign_up_fee_total > 0) {
                 // Order taxes need to be set to the same as the sign up fee taxes
                 if (isset($sign_up_tax['cart_tax']) && $sign_up_tax['cart_tax'] > 0) {
                     $order_taxes[$index]['cart_tax'] = $sign_up_tax['cart_tax'];
                 }
             } elseif (!$has_trial && $sign_up_fee_total > 0) {
                 // Sign up fee taxes need to be added to order taxes
                 if (isset($sign_up_tax['cart_tax']) && $sign_up_tax['cart_tax'] > 0) {
                     $order_taxes[$index]['cart_tax'] += $sign_up_tax['cart_tax'];
                 }
             }
         }
         if (false == self::$is_wc_version_2) {
             // Doing it right: updated Subs *before* updating WooCommerce, the WooCommerce updater will take care of data migration
             update_post_meta($order_id, '_order_taxes', $order_taxes);
         } else {
             // Doing it wrong: updated Subs *after* updating WooCommerce, need to store in WC2.0 tax structure
             $index = 0;
             $new_order_taxes = $order->get_taxes();
             foreach ($new_order_taxes as $item_id => $order_tax) {
                 $index = $index + 1;
                 if (!isset($order_taxes[$index]['label']) || !isset($order_taxes[$index]['cart_tax']) || !isset($order_taxes[$index]['shipping_tax'])) {
                     continue;
                 }
                 // Add line item meta
                 if ($item_id) {
                     woocommerce_update_order_item_meta($item_id, 'compound', absint(isset($order_taxes[$index]['compound']) ? $order_taxes[$index]['compound'] : 0));
                     woocommerce_update_order_item_meta($item_id, 'tax_amount', woocommerce_clean($order_taxes[$index]['cart_tax']));
                     woocommerce_update_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($order_taxes[$index]['shipping_tax']));
                 }
             }
         }
         /* Upgrade each order item to use new Item Meta schema */
         $order_subscription_periods = WC_Subscriptions_Order::get_meta($order_id, '_order_subscription_periods', array());
         $order_subscription_intervals = WC_Subscriptions_Order::get_meta($order_id, '_order_subscription_intervals', array());
         $order_subscription_lengths = WC_Subscriptions_Order::get_meta($order_id, '_order_subscription_lengths', array());
         $order_subscription_trial_lengths = WC_Subscriptions_Order::get_meta($order_id, '_order_subscription_trial_lengths', array());
         $order_items = $order->get_items();
         foreach ($order_items as $index => $order_item) {
             $product_id = WC_Subscriptions_Order::get_items_product_id($order_item);
             $item_meta = new WC_Order_Item_Meta($order_item['item_meta']);
             $subscription_interval = isset($order_subscription_intervals[$product_id]) ? $order_subscription_intervals[$product_id] : 1;
             $subscription_length = isset($order_subscription_lengths[$product_id]) ? $order_subscription_lengths[$product_id] : 0;
             $subscription_trial_length = isset($order_subscription_trial_lengths[$product_id]) ? $order_subscription_trial_lengths[$product_id] : 0;
             $subscription_sign_up_fee = WC_Subscriptions_Order::get_meta($order, '_cart_contents_sign_up_fee_total', 0);
             if ($sign_up_fee_total > 0) {
                 // Discounted price * Quantity
                 $sign_up_fee_line_total = WC_Subscriptions_Order::get_meta($order, '_cart_contents_sign_up_fee_total', 0);
                 $sign_up_fee_line_tax = WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_tax_total', 0);
                 // Base price * Quantity
                 $sign_up_fee_line_subtotal = WC_Subscriptions_Order::get_meta($order, '_cart_contents_sign_up_fee_total', 0) + WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_discount_cart', 0);
                 $sign_up_fee_propotion = $sign_up_fee_line_total > 0 ? $sign_up_fee_line_subtotal / $sign_up_fee_line_total : 0;
                 $sign_up_fee_line_subtotal_tax = WC_Subscriptions_Manager::get_amount_from_proportion(WC_Subscriptions_Order::get_meta($order, '_sign_up_fee_tax_total', 0), $sign_up_fee_propotion);
                 if ($has_trial) {
                     // Set line item totals equal to sign up fee totals
                     $order_item['line_subtotal'] = $sign_up_fee_line_subtotal;
                     $order_item['line_subtotal_tax'] = $sign_up_fee_line_subtotal_tax;
                     $order_item['line_total'] = $sign_up_fee_line_total;
                     $order_item['line_tax'] = $sign_up_fee_line_tax;
                 } else {
                     // No trial period, sign up fees need to be added to order totals
                     $order_item['line_subtotal'] += $sign_up_fee_line_subtotal;
                     $order_item['line_subtotal_tax'] += $sign_up_fee_line_subtotal_tax;
                     $order_item['line_total'] += $sign_up_fee_line_total;
                     $order_item['line_tax'] += $sign_up_fee_line_tax;
                 }
             }
             // Upgrading with WC 1.x
             if (method_exists($item_meta, 'add')) {
                 $item_meta->add('_subscription_period', $order_subscription_periods[$product_id]);
                 $item_meta->add('_subscription_interval', $subscription_interval);
                 $item_meta->add('_subscription_length', $subscription_length);
                 $item_meta->add('_subscription_trial_length', $subscription_trial_length);
                 $item_meta->add('_subscription_recurring_amount', $order_item['line_subtotal']);
                 // WC_Subscriptions_Product::get_price() would return a price without filters applied
                 $item_meta->add('_subscription_sign_up_fee', $subscription_sign_up_fee);
                 // Set recurring amounts for the item
                 $item_meta->add('_recurring_line_total', $order_item['line_total']);
                 $item_meta->add('_recurring_line_tax', $order_item['line_tax']);
                 $item_meta->add('_recurring_line_subtotal', $order_item['line_subtotal']);
                 $item_meta->add('_recurring_line_subtotal_tax', $order_item['line_subtotal_tax']);
                 $order_item['item_meta'] = $item_meta->meta;
                 $order_items[$index] = $order_item;
             } else {
                 // Ignoring all advice, upgrading 4 months after version 1.2 was released, and doing it with WC 2.0 installed
                 woocommerce_add_order_item_meta($index, '_subscription_period', $order_subscription_periods[$product_id]);
                 woocommerce_add_order_item_meta($index, '_subscription_interval', $subscription_interval);
                 woocommerce_add_order_item_meta($index, '_subscription_length', $subscription_length);
                 woocommerce_add_order_item_meta($index, '_subscription_trial_length', $subscription_trial_length);
                 woocommerce_add_order_item_meta($index, '_subscription_trial_period', $order_subscription_periods[$product_id]);
                 woocommerce_add_order_item_meta($index, '_subscription_recurring_amount', $order_item['line_subtotal']);
                 woocommerce_add_order_item_meta($index, '_subscription_sign_up_fee', $subscription_sign_up_fee);
                 // Calculated recurring amounts for the item
                 woocommerce_add_order_item_meta($index, '_recurring_line_total', $order_item['line_total']);
                 woocommerce_add_order_item_meta($index, '_recurring_line_tax', $order_item['line_tax']);
                 woocommerce_add_order_item_meta($index, '_recurring_line_subtotal', $order_item['line_subtotal']);
                 woocommerce_add_order_item_meta($index, '_recurring_line_subtotal_tax', $order_item['line_subtotal_tax']);
                 if ($sign_up_fee_total > 0) {
                     // Order totals have changed
                     woocommerce_update_order_item_meta($index, '_line_subtotal', woocommerce_format_decimal($order_item['line_subtotal']));
                     woocommerce_update_order_item_meta($index, '_line_subtotal_tax', woocommerce_format_decimal($order_item['line_subtotal_tax']));
                     woocommerce_update_order_item_meta($index, '_line_total', woocommerce_format_decimal($order_item['line_total']));
                     woocommerce_update_order_item_meta($index, '_line_tax', woocommerce_format_decimal($order_item['line_tax']));
                 }
             }
         }
         // Save the new meta on the order items for WC 1.x (the API functions already saved the data for WC2.x)
         if (false == self::$is_wc_version_2) {
             update_post_meta($order_id, '_order_items', $order_items);
         }
         $upgraded_orders[] = $order_id;
         update_option('wcs_1_2_upgraded_order_ids', $upgraded_orders);
     }
     // Remove the lock on upgrading
     delete_transient('wc_subscriptions_is_upgrading');
 }
 /**
  * Creates a new order for renewing a subscription product based on the details of a previous order.
  *
  * No trial periods or sign up fees are applied to the renewal order. However, if the order has failed
  * payments and the store manager has set failed payments to be added to renewal orders, then the
  * orders totals will be set to include the outstanding balance.
  *
  * If the $args['new_order_role'] flag is set to 'parent', then the renewal order will supersede the existing 
  * order. The existing order and subscription associated with it will be cancelled. A new order and
  * subscription will be created. 
  *
  * If the $args['new_order_role'] flag is 'child', the $original_order will remain the master order for the
  * subscription and the new order is just for accepting a recurring payment on the subscription.
  *
  * Renewal orders have the same meta data as the original order. If the renewal order is set to be a 'child'
  * then any subscription related meta data will not be stored on the new order. This is to keep subscription
  * meta data associated only with the one master order for the subscription.
  *
  * @param WC_Order|int $order The WC_Order object or ID of the order for which the a new order should be created.
  * @param string $product_id The ID of the subscription product in the order which needs to be added to the new order.
  * @param array $args (optional) An array of name => value flags:
  *         'new_order_role' string A flag to indicate whether the new order should become the master order for the subscription. Accepts either 'parent' or 'child'. Defaults to 'parent' - replace the existing order.
  *         'checkout_renewal' bool Indicates if invoked from an interactive cart/checkout session. Default false.
  *         'failed_order_id' int For checkout_renewal true, indicates order id being replaced
  * @since 1.2
  */
 public static function generate_renewal_order($original_order, $product_id, $args = array())
 {
     global $wpdb, $woocommerce;
     if (!is_object($original_order)) {
         $original_order = new WC_Order($original_order);
     }
     if (!WC_Subscriptions_Order::order_contains_subscription($original_order) || !WC_Subscriptions_Order::is_item_subscription($original_order, $product_id)) {
         return false;
     }
     if (self::is_renewal($original_order, array('order_role' => 'child'))) {
         $original_order = self::get_parent_order($original_order);
     }
     if (!is_array($args)) {
         _deprecated_argument(__CLASS__ . '::' . __FUNCTION__, '1.3', __('Third parameter is now an array of name => value pairs. Use array( "new_order_role" => "parent" ) instead.', WC_Subscriptions::$text_domain));
         $args = array('new_order_role' => $args);
     }
     $args = wp_parse_args($args, array('new_order_role' => 'parent', 'checkout_renewal' => false));
     $renewal_order_key = uniqid('order_');
     // Create the new order
     $renewal_order_data = array('post_type' => 'shop_order', 'post_title' => sprintf(__('Subscription Renewal Order &ndash; %s', WC_Subscriptions::$text_domain), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', WC_Subscriptions::$text_domain))), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => $original_order->customer_note, 'post_author' => 1, 'post_password' => $renewal_order_key);
     $create_new_order = true;
     if ('child' == $args['new_order_role']) {
         $renewal_order_data['post_parent'] = $original_order->id;
     }
     if (true === $args['checkout_renewal']) {
         $renewal_order_id = null;
         if ($woocommerce->session->order_awaiting_payment > 0) {
             $renewal_order_id = absint($woocommerce->session->order_awaiting_payment);
         } elseif (isset($args['failed_order_id'])) {
             $failed_order_id = $args['failed_order_id'];
             /* Check order is unpaid by getting its status */
             $terms = wp_get_object_terms($failed_order_id, 'shop_order_status', array('fields' => 'slugs'));
             $order_status = isset($terms[0]) ? $terms[0] : 'pending';
             /* If paying on a pending order, we are resuming */
             if ($order_status == 'pending') {
                 $renewal_order_id = $failed_order_id;
             }
         }
         if ($renewal_order_id) {
             /* Check order is unpaid by getting its status */
             $terms = wp_get_object_terms($renewal_order_id, 'shop_order_status', array('fields' => 'slugs'));
             $order_status = isset($terms[0]) ? $terms[0] : 'pending';
             // Resume the unpaid order if its pending
             if ($order_status == 'pending' || $order_status == 'failed') {
                 // Update the existing order as we are resuming it
                 $create_new_order = false;
                 $renewal_order_data['ID'] = $renewal_order_id;
                 wp_update_post($renewal_order_data);
                 // Clear the old line items - we'll add these again in case they changed
                 $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d )", $renewal_order_id));
                 $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d", $renewal_order_id));
             }
         }
     }
     if ($create_new_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');
     // Set a unique key for this order
     update_post_meta($renewal_order_id, '_order_key', $renewal_order_key);
     if (true === $args['checkout_renewal']) {
         $checkout_object = $woocommerce->checkout;
         $customer_id = $original_order->customer_user;
         // Save posted billing fields to both renewal and original order
         if ($checkout_object->checkout_fields['billing']) {
             foreach ($checkout_object->checkout_fields['billing'] as $key => $field) {
                 update_post_meta($renewal_order_id, '_' . $key, $checkout_object->posted[$key]);
                 update_post_meta($original_order->id, '_' . $key, $checkout_object->posted[$key]);
                 // User
                 if ($customer_id && !empty($checkout_object->posted[$key])) {
                     update_user_meta($customer_id, $key, $checkout_object->posted[$key]);
                     // Special fields
                     switch ($key) {
                         case "billing_email":
                             if (!email_exists($checkout_object->posted[$key])) {
                                 wp_update_user(array('ID' => $customer_id, 'user_email' => $checkout_object->posted[$key]));
                             }
                             break;
                         case "billing_first_name":
                             wp_update_user(array('ID' => $customer_id, 'first_name' => $checkout_object->posted[$key]));
                             break;
                         case "billing_last_name":
                             wp_update_user(array('ID' => $customer_id, 'last_name' => $checkout_object->posted[$key]));
                             break;
                     }
                 }
             }
         }
         // Save posted shipping fields to both renewal and original order
         if ($checkout_object->checkout_fields['shipping'] && ($woocommerce->cart->needs_shipping() || get_option('woocommerce_require_shipping_address') == 'yes')) {
             foreach ($checkout_object->checkout_fields['shipping'] as $key => $field) {
                 $postvalue = false;
                 if ($checkout_object->posted['shiptobilling']) {
                     if (isset($checkout_object->posted[str_replace('shipping_', 'billing_', $key)])) {
                         $postvalue = $checkout_object->posted[str_replace('shipping_', 'billing_', $key)];
                         update_post_meta($renewal_order_id, '_' . $key, $postvalue);
                         update_post_meta($original_order->id, '_' . $key, $postvalue);
                     }
                 } else {
                     $postvalue = $checkout_object->posted[$key];
                     update_post_meta($renewal_order_id, '_' . $key, $postvalue);
                     update_post_meta($original_order->id, '_' . $key, $postvalue);
                 }
                 // User
                 if ($postvalue && $customer_id) {
                     update_user_meta($customer_id, $key, $postvalue);
                 }
             }
         }
     }
     $order_meta_query = "SELECT `meta_key`, `meta_value`\n\t\t\t\t\t\t\t FROM {$wpdb->postmeta}\n\t\t\t\t\t\t\t WHERE `post_id` = {$original_order->id}\n\t\t\t\t\t\t\t AND `meta_key` NOT IN ('_paid_date', '_completed_date', '_order_key', '_edit_lock', '_original_order')";
     // Superseding existing order so don't carry over payment details
     if ('parent' == $args['new_order_role'] || true === $args['checkout_renewal']) {
         $order_meta_query .= " AND `meta_key` NOT IN ('_payment_method', '_payment_method_title', '_recurring_payment_method', '_recurring_payment_method_title', '_shipping_method', '_shipping_method_title', '_recurring_shipping_method', '_recurring_shipping_method_title')";
     } else {
         $order_meta_query .= " AND `meta_key` NOT LIKE '_order_recurring_%' AND `meta_key` NOT IN ('_payment_method', '_payment_method_title', '_recurring_payment_method', '_recurring_payment_method_title', '_shipping_method', '_shipping_method_title', '_recurring_shipping_method', '_recurring_shipping_method_title')";
     }
     // Allow extensions to add/remove order meta
     $order_meta_query = apply_filters('woocommerce_subscriptions_renewal_order_meta_query', $order_meta_query, $original_order->id, $renewal_order_id, $args['new_order_role']);
     // Carry all the required meta from the old order over to the new order
     $order_meta = $wpdb->get_results($order_meta_query, 'ARRAY_A');
     $order_meta = apply_filters('woocommerce_subscriptions_renewal_order_meta', $order_meta, $original_order->id, $renewal_order_id, $args['new_order_role']);
     foreach ($order_meta as $meta_item) {
         add_post_meta($renewal_order_id, $meta_item['meta_key'], maybe_unserialize($meta_item['meta_value']), true);
     }
     $outstanding_balance = WC_Subscriptions_Order::get_outstanding_balance($original_order, $product_id);
     if (true === $args['checkout_renewal']) {
         $failed_payment_multiplier = 1;
         update_post_meta($renewal_order_id, '_order_shipping', woocommerce_format_total($woocommerce->cart->shipping_total));
         update_post_meta($renewal_order_id, '_order_discount', woocommerce_format_total($woocommerce->cart->get_order_discount_total()));
         update_post_meta($renewal_order_id, '_cart_discount', woocommerce_format_total($woocommerce->cart->get_cart_discount_total()));
         update_post_meta($renewal_order_id, '_order_tax', woocommerce_format_total($woocommerce->cart->tax_total));
         update_post_meta($renewal_order_id, '_order_shipping_tax', woocommerce_format_total($woocommerce->cart->shipping_tax_total));
         update_post_meta($renewal_order_id, '_order_total', woocommerce_format_total($woocommerce->cart->total));
         update_post_meta($renewal_order_id, '_checkout_renewal', 'yes');
     } else {
         // If there are outstanding payment amounts, add them to the order, otherwise set the order details to the values of the recurring totals
         if ($outstanding_balance > 0 && 'yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_add_outstanding_balance', 'no')) {
             $failed_payment_multiplier = WC_Subscriptions_Order::get_failed_payment_count($original_order, $product_id);
         } else {
             $failed_payment_multiplier = 1;
         }
         // Set order totals based on recurring totals from the original order
         $cart_discount = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_discount_cart', true);
         $order_discount = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_discount_total', true);
         $order_shipping_tax = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_shipping_tax_total', true);
         $order_shipping = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_shipping_total', true);
         $order_tax = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_tax_total', true);
         $order_total = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_total', true);
         update_post_meta($renewal_order_id, '_cart_discount', $cart_discount);
         update_post_meta($renewal_order_id, '_order_discount', $order_discount);
         update_post_meta($renewal_order_id, '_order_shipping_tax', $order_shipping_tax);
         update_post_meta($renewal_order_id, '_order_shipping', $order_shipping);
         update_post_meta($renewal_order_id, '_order_tax', $order_tax);
         update_post_meta($renewal_order_id, '_order_total', $order_total);
         update_post_meta($renewal_order_id, '_shipping_method', $original_order->recurring_shipping_method);
         update_post_meta($renewal_order_id, '_shipping_method_title', $original_order->recurring_shipping_method_title);
         // Apply the recurring shipping & payment methods to child renewal orders
         if ('child' == $args['new_order_role']) {
             update_post_meta($renewal_order_id, '_payment_method', $original_order->recurring_payment_method);
             update_post_meta($renewal_order_id, '_payment_method_title', $original_order->recurring_payment_method_title);
         }
     }
     // Set order taxes based on recurring taxes from the original order
     $recurring_order_taxes = WC_Subscriptions_Order::get_recurring_taxes($original_order);
     foreach ($recurring_order_taxes as $index => $recurring_order_tax) {
         if (function_exists('woocommerce_update_order_item_meta')) {
             // WC 2.0+
             $item_ids = array();
             $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_order_tax['name'], 'order_item_type' => 'tax'));
             // Also set recurring taxes on parent renewal orders
             if ('parent' == $args['new_order_role']) {
                 $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_order_tax['name'], 'order_item_type' => 'recurring_tax'));
             }
             // Add line item meta
             foreach ($item_ids as $item_id) {
                 woocommerce_add_order_item_meta($item_id, 'compound', absint(isset($recurring_order_tax['compound']) ? $recurring_order_tax['compound'] : 0));
                 woocommerce_add_order_item_meta($item_id, 'tax_amount', woocommerce_clean($failed_payment_multiplier * $recurring_order_tax['tax_amount']));
                 woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($failed_payment_multiplier * $recurring_order_tax['shipping_tax_amount']));
                 if (isset($recurring_order_tax['rate_id'])) {
                     woocommerce_add_order_item_meta($item_id, 'rate_id', $recurring_order_tax['rate_id']);
                 }
                 if (isset($recurring_order_tax['label'])) {
                     woocommerce_add_order_item_meta($item_id, 'label', $recurring_order_tax['label']);
                 }
             }
         } else {
             // WC 1.x
             if (isset($recurring_order_tax['cart_tax']) && $recurring_order_tax['cart_tax'] > 0) {
                 $recurring_order_taxes[$index]['cart_tax'] = $failed_payment_multiplier * $recurring_order_tax['cart_tax'];
             } else {
                 $recurring_order_taxes[$index]['cart_tax'] = 0;
             }
             if (isset($recurring_order_tax['shipping_tax']) && $recurring_order_tax['shipping_tax'] > 0) {
                 $recurring_order_taxes[$index]['shipping_tax'] = $failed_payment_multiplier * $recurring_order_tax['shipping_tax'];
             } else {
                 $recurring_order_taxes[$index]['shipping_tax'] = 0;
             }
             // Inefficient but keeps WC 1.x code grouped together
             update_post_meta($renewal_order_id, '_order_taxes', $recurring_order_taxes);
         }
     }
     // Set line totals to be recurring line totals and remove the subscription/recurring related item meta from each order item
     $order_items = WC_Subscriptions_Order::get_recurring_items($original_order);
     // Allow extensions to add/remove items or item meta
     $order_items = apply_filters('woocommerce_subscriptions_renewal_order_items', $order_items, $original_order->id, $renewal_order_id, $product_id, $args['new_order_role']);
     foreach ($order_items as $item_index => $order_item) {
         $item_meta = new WC_Order_Item_Meta($order_item['item_meta']);
         // WC 2.0+ order item structure - as of WC 2.0 item_meta is stored as $key => meta pairs, not 'meta_name'/'meta_value'
         if (function_exists('woocommerce_add_order_item_meta')) {
             if ('child' == $args['new_order_role']) {
                 $renewal_order_item_name = sprintf(__('Renewal of "%s" purchased in Order %s', WC_Subscriptions::$text_domain), $order_item['name'], $original_order->get_order_number());
             } else {
                 $renewal_order_item_name = $order_item['name'];
             }
             // Create order line item on the renewal order
             $recurring_item_id = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $renewal_order_item_name, 'order_item_type' => 'line_item'));
             // Remove recurring line items and set item totals based on recurring line totals
             foreach ($item_meta->meta as $meta_key => $meta) {
                 // $meta is an array, so the item needs to be extracted from $meta[0] (just like order meta on a WC Order)
                 $meta_value = $meta[0];
                 // Map line item totals based on recurring line totals
                 switch ($meta_key) {
                     case '_recurring_line_total':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_total');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_total', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     case '_recurring_line_tax':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_tax');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_tax', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     case '_recurring_line_subtotal':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_subtotal');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_subtotal', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     case '_recurring_line_subtotal_tax':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_subtotal_tax');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_subtotal_tax', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     default:
                         break;
                 }
                 // Copy over line item meta data, with some parent/child role based exceptions for recurring amounts
                 $copy_to_renewal_item = true;
                 switch ($meta_key) {
                     case '_recurring_line_total':
                     case '_recurring_line_tax':
                     case '_recurring_line_subtotal':
                     case '_recurring_line_subtotal_tax':
                     case '_subscription_recurring_amount':
                     case '_subscription_sign_up_fee':
                     case '_subscription_period':
                     case '_subscription_interval':
                     case '_subscription_length':
                     case '_subscription_trial_period':
                     case '_subscription_end_date':
                     case '_subscription_expiry_date':
                     case '_subscription_start_date':
                     case '_subscription_status':
                     case '_subscription_completed_payments':
                         if ('child' == $args['new_order_role']) {
                             $copy_to_renewal_item = false;
                         }
                         break;
                     case '_subscription_trial_length':
                         // We never want to duplicate free trials on renewal orders
                         $copy_to_renewal_item = false;
                         break;
                     case '_subscription_suspension_count':
                         // We want to reset some values for the new order
                     // We want to reset some values for the new order
                     case '_subscription_trial_expiry_date':
                     case '_subscription_failed_payments':
                         $copy_to_renewal_item = false;
                         $meta_value = 0;
                         break;
                     default:
                         break;
                 }
                 // Copy existing item over to new recurring order item
                 if ($copy_to_renewal_item) {
                     woocommerce_add_order_item_meta($recurring_item_id, $meta_key, $meta_value);
                 }
             }
         } else {
             // WC 1.x order item structure
             foreach ($item_meta->meta as $meta_index => $meta_item) {
                 switch ($meta_item['meta_name']) {
                     case '_recurring_line_total':
                         $order_items[$item_index]['line_total'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_tax':
                         $order_items[$item_index]['line_tax'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_subtotal':
                         $order_items[$item_index]['line_subtotal'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_subtotal_tax':
                         $order_items[$item_index]['line_subtotal_tax'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_total':
                     case '_recurring_line_tax':
                     case '_recurring_line_subtotal':
                     case '_recurring_line_subtotal_tax':
                     case '_recurring_line_subtotal_tax':
                     case '_subscription_recurring_amount':
                     case '_subscription_sign_up_fee':
                     case '_subscription_period':
                     case '_subscription_interval':
                     case '_subscription_length':
                     case '_subscription_trial_length':
                     case '_subscription_trial_period':
                         if ('child' == $args['new_order_role']) {
                             unset($item_meta->meta[$meta_index]);
                         }
                         break;
                     case '_subscription_trial_length':
                         // We never want to duplicate free trials on renewal orders
                         if ('child' == $args['new_order_role']) {
                             unset($item_meta->meta[$meta_index]);
                         } else {
                             $item_meta->meta[$meta_index] = 0;
                         }
                         break;
                 }
                 if ('child' == $args['new_order_role']) {
                     $order_items[$item_index]['name'] = sprintf(__('Renewal of "%s" purchased in Order %s', WC_Subscriptions::$text_domain), $order_item['name'], $original_order->get_order_number());
                 }
                 $order_items[$item_index]['item_meta'] = $item_meta->meta;
             }
             // Save the item meta on the new order
             update_post_meta($renewal_order_id, '_order_items', $order_items);
         }
     }
     // Keep a record of the original order's ID on the renewal order
     update_post_meta($renewal_order_id, '_original_order', $original_order->id, true);
     $renewal_order = new WC_Order($renewal_order_id);
     if ('parent' == $args['new_order_role']) {
         WC_Subscriptions_Manager::process_subscriptions_on_checkout($renewal_order_id);
         $original_order->add_order_note(sprintf(__('Order superseded by Renewal Order %s.', WC_Subscriptions::$text_domain), $renewal_order->get_order_number()));
     }
     do_action('woocommerce_subscriptions_renewal_order_created', $renewal_order, $original_order, $product_id, $args['new_order_role']);
     return apply_filters('woocommerce_subscriptions_renewal_order_id', $renewal_order_id, $original_order, $product_id, $args['new_order_role']);
 }
 /**
  * Output the form
  */
 public function output()
 {
     $this->errors = array();
     $step = 1;
     try {
         if (!empty($_POST) && !check_admin_referer('create_booking_notification')) {
             throw new Exception(__('Error - please try again', 'woocommerce-bookings'));
         }
         if (!empty($_POST['create_booking'])) {
             $customer_id = absint($_POST['customer_id']);
             $bookable_product_id = absint($_POST['bookable_product_id']);
             $booking_order = wc_clean($_POST['booking_order']);
             if (!$bookable_product_id) {
                 throw new Exception(__('Please choose a bookable product', 'woocommerce-bookings'));
             }
             if ($booking_order === 'existing') {
                 $order_id = absint($_POST['booking_order_id']);
                 $booking_order = $order_id;
                 if (!$booking_order || get_post_type($booking_order) !== 'shop_order') {
                     throw new Exception(__('Invalid order ID provided', 'woocommerce-bookings'));
                 }
             }
             $step++;
             $product = get_product($bookable_product_id);
             $booking_form = new WC_Booking_Form($product);
         } elseif (!empty($_POST['create_booking_2'])) {
             $customer_id = absint($_POST['customer_id']);
             $bookable_product_id = absint($_POST['bookable_product_id']);
             $booking_order = wc_clean($_POST['booking_order']);
             $product = get_product($bookable_product_id);
             $booking_form = new WC_Booking_Form($product);
             $booking_data = $booking_form->get_posted_data($_POST);
             $booking_cost = ($cost = $booking_form->calculate_booking_cost($_POST)) && !is_wp_error($cost) ? number_format($cost, 2, '.', '') : 0;
             $create_order = false;
             if ('yes' === get_option('woocommerce_prices_include_tax')) {
                 if (version_compare(WOOCOMMERCE_VERSION, '2.3', '<')) {
                     $base_tax_rates = WC_Tax::get_shop_base_rate($product->tax_class);
                 } else {
                     $base_tax_rates = WC_Tax::get_base_tax_rates($product->tax_class);
                 }
                 $base_taxes = WC_Tax::calc_tax($booking_cost, $base_tax_rates, true);
                 $booking_cost = round($booking_cost - array_sum($base_taxes), absint(get_option('woocommerce_price_num_decimals')));
             }
             // Data to go into the booking
             $new_booking_data = array('user_id' => $customer_id, 'product_id' => $product->id, 'resource_id' => isset($booking_data['_resource_id']) ? $booking_data['_resource_id'] : '', 'persons' => $booking_data['_persons'], 'cost' => $booking_cost, 'start_date' => $booking_data['_start_date'], 'end_date' => $booking_data['_end_date'], 'all_day' => $booking_data['_all_day'] ? 1 : 0);
             // Create order
             if ($booking_order === 'new') {
                 $create_order = true;
                 $order_id = $this->create_order($booking_cost, $customer_id);
                 if (!$order_id) {
                     throw new Exception(__('Error: Could not create order', 'woocommerce-bookings'));
                 }
             } elseif ($booking_order > 0) {
                 $order_id = absint($booking_order);
                 if (!$order_id || get_post_type($order_id) !== 'shop_order') {
                     throw new Exception(__('Invalid order ID provided', 'woocommerce-bookings'));
                 }
                 $order = new WC_Order($order_id);
                 update_post_meta($order_id, '_order_total', $order->get_total() + $booking_cost);
                 update_post_meta($order_id, '_booking_order', '1');
             } else {
                 $order_id = 0;
             }
             if ($order_id) {
                 $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $product->get_title(), 'order_item_type' => 'line_item'));
                 if (!$item_id) {
                     throw new Exception(__('Error: Could not create item', 'woocommerce-bookings'));
                 }
                 // Add line item meta
                 woocommerce_add_order_item_meta($item_id, '_qty', 1);
                 woocommerce_add_order_item_meta($item_id, '_tax_class', $product->get_tax_class());
                 woocommerce_add_order_item_meta($item_id, '_product_id', $product->id);
                 woocommerce_add_order_item_meta($item_id, '_variation_id', '');
                 woocommerce_add_order_item_meta($item_id, '_line_subtotal', $booking_cost);
                 woocommerce_add_order_item_meta($item_id, '_line_total', $booking_cost);
                 woocommerce_add_order_item_meta($item_id, '_line_tax', 0);
                 woocommerce_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
                 // We have an item id
                 $new_booking_data['order_item_id'] = $item_id;
                 // Add line item data
                 foreach ($booking_data as $key => $value) {
                     if (strpos($key, '_') !== 0) {
                         woocommerce_add_order_item_meta($item_id, get_wc_booking_data_label($key, $product), $value);
                     }
                 }
             }
             // Create the booking itself
             $new_booking = get_wc_booking($new_booking_data);
             $new_booking->create($create_order ? 'unpaid' : 'pending-confirmation');
             wp_safe_redirect(admin_url('post.php?post=' . ($create_order ? $order_id : $new_booking->id) . '&action=edit'));
             exit;
         }
     } catch (Exception $e) {
         $this->errors[] = $e->getMessage();
     }
     switch ($step) {
         case 1:
             include 'views/html-create-booking-page.php';
             break;
         case 2:
             include 'views/html-create-booking-page-2.php';
             break;
     }
 }
 /**
  * order_item_meta function.
  *
  * @param mixed $item_id
  * @param mixed $values
  */
 public function order_item_meta($item_id, $values)
 {
     if (!empty($values['booking'])) {
         $product = $values['data'];
         // Create the new booking
         $new_booking_data = array('order_item_id' => $item_id, 'product_id' => $values['product_id'], 'cost' => $values['booking']['_cost'], 'start_date' => $values['booking']['_start_date'], 'end_date' => $values['booking']['_end_date'], 'all_day' => $values['booking']['_all_day']);
         // Check if the booking has resources
         if (isset($values['booking']['_resource_id'])) {
             $new_booking_data['resource_id'] = $values['booking']['_resource_id'];
             // ID of the resource
         }
         // Checks if the booking allows persons
         if (isset($values['booking']['_persons'])) {
             $new_booking_data['persons'] = $values['booking']['_persons'];
             // Count of persons making booking
         }
         $booking_status = 'unpaid';
         // Set as pending when the booking requires confirmation
         if (wc_booking_requires_confirmation($values['product_id'])) {
             $booking_status = 'pending';
         }
         $new_booking = get_wc_booking($new_booking_data);
         $new_booking->create($booking_status);
         // Add summary of details to line item
         foreach ($values['booking'] as $key => $value) {
             if (strpos($key, '_') !== 0) {
                 woocommerce_add_order_item_meta($item_id, get_wc_booking_data_label($key, $product), $value);
             }
         }
     }
 }
 /**
  * Uses the details of an order to create a pending subscription on the customers account
  * for a subscription product, as specified with $product_id.
  *
  * @param int|WC_Order $order The order ID or WC_Order object to create the subscription from.
  * @param int $product_id The ID of the subscription product on the order.
  * @param array $args An array of name => value pairs to customise the details of the subscription, including:
  * 			'start_date' A MySQL formatted date/time string on which the subscription should start, in UTC timezone
  * 			'expiry_date' A MySQL formatted date/time string on which the subscription should expire, in UTC timezone
  * @since 1.1
  */
 public static function create_pending_subscription_for_order($order, $product_id, $args = array())
 {
     if (!is_object($order)) {
         $order = new WC_Order($order);
     }
     if (!WC_Subscriptions_Product::is_subscription($product_id)) {
         return;
     }
     $args = wp_parse_args($args, array('start_date' => '', 'expiry_date' => ''));
     $subscription_key = self::get_subscription_key($order->id, $product_id);
     // In case the subscription exists already
     $subscription = self::get_subscription($subscription_key);
     if (!empty($subscription['variation_id'])) {
         $product_id = $subscription['variation_id'];
     } elseif (!empty($subscription['product_id'])) {
         $product_id = $subscription['product_id'];
     }
     // Adding a new subscription so set the start date/time to now
     if (!empty($args['start_date'])) {
         if (is_numeric($args['start_date'])) {
             $args['start_date'] = date('Y-m-d H:i:s', $args['start_date']);
         }
         $start_date = $args['start_date'];
     } else {
         $start_date = !empty($subscription['start_date']) ? $subscription['start_date'] : gmdate('Y-m-d H:i:s');
     }
     // Adding a new subscription so set the expiry date/time from the order date
     if (!empty($args['expiry_date'])) {
         if (is_numeric($args['expiry_date'])) {
             $args['expiry_date'] = date('Y-m-d H:i:s', $args['expiry_date']);
         }
         $expiration = $args['expiry_date'];
     } else {
         $expiration = !empty($subscription['expiry_date']) ? $subscription['expiry_date'] : WC_Subscriptions_Product::get_expiration_date($product_id, $start_date);
     }
     // Adding a new subscription so set the expiry date/time from the order date
     $trial_expiration = !empty($subscription['trial_expiry_date']) ? $subscription['trial_expiry_date'] : WC_Subscriptions_Product::get_trial_expiration_date($product_id, $start_date);
     $failed_payments = !empty($subscription['failed_payments']) ? $subscription['failed_payments'] : 0;
     $completed_payments = !empty($subscription['completed_payments']) ? $subscription['completed_payments'] : array();
     $order_item_id = WC_Subscriptions_Order::get_item_id_by_subscription_key($subscription_key);
     // Store the subscription details in item meta
     woocommerce_add_order_item_meta($order_item_id, '_subscription_start_date', $start_date, true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_expiry_date', $expiration, true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_trial_expiry_date', $trial_expiration, true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_failed_payments', $failed_payments, true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_completed_payments', $completed_payments, true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_status', 'pending', true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_end_date', 0, true);
     woocommerce_add_order_item_meta($order_item_id, '_subscription_suspension_count', 0, true);
     $product = WC_Subscriptions::get_product($product_id);
     // Set subscription status to active and log activation
     $order->add_order_note(sprintf(__('Pending subscription created for "%s".', 'woocommerce-subscriptions'), $product->get_title()));
     do_action('pending_subscription_created_for_order', $order, $product_id);
 }
Esempio n. 20
0
 /**
  * Unassign vendor from a product
  */
 function unassign_vendor()
 {
     global $WCMp;
     $product_id = $_POST['product_id'];
     $vendor = get_wcmp_product_vendors($product_id);
     $admin_id = get_current_user_id();
     $_product = get_product($product_id);
     $orders = array();
     if ($_product->is_type('variable')) {
         $get_children = $_product->get_children();
         if (!empty($get_children)) {
             foreach ($get_children as $child) {
                 $orders = array_merge($orders, $vendor->get_vendor_orders_by_product($vendor->term_id, $child));
             }
             $orders = array_unique($orders);
         }
     } else {
         $orders = array_unique($vendor->get_vendor_orders_by_product($vendor->term_id, $product_id));
     }
     foreach ($orders as $order_id) {
         $order = new WC_Order($order_id);
         $items = $order->get_items('line_item');
         foreach ($items as $item_id => $item) {
             woocommerce_add_order_item_meta($item_id, '_vendor_id', $vendor->id);
         }
     }
     wp_delete_object_term_relationships($product_id, 'dc_vendor_shop');
     wp_delete_object_term_relationships($product_id, 'product_shipping_class');
     wp_update_post(array('ID' => $product_id, 'post_author' => $admin_id));
     delete_post_meta($product_id, '_commission_per_product');
     delete_post_meta($product_id, '_commission_percentage_per_product');
     delete_post_meta($product_id, '_commission_fixed_with_percentage_qty');
     delete_post_meta($product_id, '_commission_fixed_with_percentage');
     $product_obj = wc_get_product($product_id);
     if ($product_obj->is_type('variable')) {
         $child_ids = $product_obj->get_children();
         if (isset($child_ids) && !empty($child_ids)) {
             foreach ($child_ids as $child_id) {
                 delete_post_meta($child_id, '_commission_fixed_with_percentage');
                 delete_post_meta($child_id, '_product_vendors_commission_percentage');
                 delete_post_meta($child_id, '_product_vendors_commission_fixed_per_trans');
                 delete_post_meta($child_id, '_product_vendors_commission_fixed_per_qty');
             }
         }
     }
     die;
 }
 /**
  * Add meta to orders
  *
  * @access public
  * @param mixed $item_id
  * @param mixed $values
  * @return void
  */
 public function order_item_meta($item_id, $values)
 {
     if (!empty($values['addons'])) {
         foreach ($values['addons'] as $addon) {
             $name = $addon['name'];
             if ($addon['price'] > 0 && apply_filters('woocommerce_addons_add_price_to_name', true)) {
                 $name .= ' (' . strip_tags(wc_price(get_frame_price_for_display($addon['price'], $values['data'], true))) . ')';
             }
             woocommerce_add_order_item_meta($item_id, $name, $addon['value']);
         }
     }
 }
 public function order_item_meta_2($item_id, $cart_item)
 {
     if (function_exists('woocommerce_add_order_item_meta')) {
         if (isset($cart_item['_gravity_form_lead']) && isset($cart_item['_gravity_form_data'])) {
             woocommerce_add_order_item_meta($item_id, '_gravity_forms_history', array('_gravity_form_lead' => $cart_item['_gravity_form_lead'], '_gravity_form_data' => $cart_item['_gravity_form_data']));
             //Gravity forms generates errors and warnings.  To prevent these from conflicting with other things, we are going to disable warnings and errors.
             $err_level = error_reporting();
             error_reporting(0);
             $gravity_form_data = $cart_item['_gravity_form_data'];
             $form_meta = RGFormsModel::get_form_meta($gravity_form_data['id']);
             if (!empty($form_meta)) {
                 $lead = $cart_item['_gravity_form_lead'];
                 $lead['id'] = uniqid() . time() . rand();
                 $products = $this->get_product_fields($form_meta, $lead);
                 $valid_products = array();
                 foreach ($products['products'] as $id => $product) {
                     if (!isset($product['quantity'])) {
                     } elseif ($product['quantity']) {
                         $valid_products[] = $id;
                     }
                 }
                 foreach ($form_meta['fields'] as $field) {
                     if (isset($field['inputType']) && $field['inputType'] == 'hiddenproduct' || isset($field['displayOnly']) && $field['displayOnly']) {
                         continue;
                     }
                     if ($field['type'] == 'product') {
                         if (!in_array($field['id'], $valid_products)) {
                             continue;
                         }
                     }
                     $value = RGFormsModel::get_lead_field_value($lead, $field);
                     $arr_var = is_array($value) ? implode('', $value) : '-';
                     if (!empty($value) && !empty($arr_var)) {
                         try {
                             if ($field['type'] == 'fileupload' && isset($lead[$field['id']])) {
                                 $display_value = $lead[$field['id']];
                             } else {
                                 $display_value = GFCommon::get_lead_field_display($field, $value, isset($lead["currency"]) ? $lead["currency"] : false, apply_filters('woocommerce_gforms_use_label_as_value', true, $value, $field, $lead, $form_meta));
                                 $price_adjustement = false;
                                 $display_value = apply_filters("gform_entry_field_value", $display_value, $field, $lead, $form_meta);
                             }
                             $display_title = GFCommon::get_label($field);
                             $display_title = apply_filters("woocommerce_gforms_order_meta_title", $display_title, $field, $lead, $form_meta, $item_id, $cart_item);
                             $display_value = apply_filters("woocommerce_gforms_order_meta_value", $display_value, $field, $lead, $form_meta, $item_id, $cart_item);
                             if (apply_filters('woocommerce_gforms_strip_meta_html', true, $display_value, $field, $lead, $form_meta, $item_id, $cart_item)) {
                                 if (strstr($display_value, '<li>')) {
                                     $display_value = str_replace('<li>', '', $display_value);
                                     $display_value = explode('</li>', $display_value);
                                     $display_value = trim(strip_tags(implode(', ', $display_value)));
                                     $display_value = trim($display_value, ',');
                                 }
                                 $display_value = strip_tags(wp_kses($display_value, ''));
                             }
                             $display_text = GFCommon::get_lead_field_display($field, $value, isset($lead["currency"]) ? $lead["currency"] : false, false);
                             $display_value = apply_filters("woocommerce_gforms_field_display_text", $display_value, $display_text, $field, $lead, $form_meta);
                             $hidden = $field['type'] == 'hidden';
                             $prefix = $hidden ? '_' : '';
                             woocommerce_add_order_item_meta($item_id, $prefix . $display_title, $display_value);
                         } catch (Exception $e) {
                         }
                     }
                 }
             }
             error_reporting($err_level);
         }
     }
 }
Esempio n. 23
0
 /**
  * Use views to display the Orders page
  *
  * @return html
  */
 public function display_product_orders()
 {
     if (!WCV_Vendors::is_vendor(get_current_user_id())) {
         ob_start();
         wc_get_template('denied.php', array(), 'wc-vendors/dashboard/', wcv_plugin_dir . 'templates/dashboard/');
         return ob_get_clean();
     }
     if (empty($_GET['orders_for_product'])) {
         return __('You haven\'t selected a product\'s orders to view! Please go back to the Vendor Dashboard and click Show Orders on the product you\'d like to view.', 'wcvendors');
     }
     if (!$this->orders) {
         return __('No orders.', 'wcvendors');
     }
     if (!empty($_POST['submit_comment'])) {
         require_once wcv_plugin_dir . 'classes/front/orders/class-submit-comment.php';
         WCV_Submit_Comment::new_comment($this->orders);
     }
     if (isset($_POST['mark_shipped'])) {
         $order_id = (int) $_POST['order_id'];
         $product_id = (int) $_POST['product_id'];
         exit;
     }
     if (isset($_POST['update_tracking'])) {
         $order_id = (int) $_POST['order_id'];
         $product_id = (int) $_POST['product_id'];
         $tracking_provider = woocommerce_clean($_POST['tracking_provider']);
         $custom_tracking_provider = woocommerce_clean($_POST['custom_tracking_provider']);
         $custom_tracking_link = woocommerce_clean($_POST['custom_tracking_link']);
         $tracking_number = woocommerce_clean($_POST['tracking_number']);
         $date_shipped = woocommerce_clean(strtotime($_POST['date_shipped']));
         $order = new WC_Order($order_id);
         $products = $order->get_items();
         foreach ($products as $key => $value) {
             if ($value['product_id'] == $product_id || $value['variation_id'] == $product_id) {
                 $order_item_id = $key;
                 break;
             }
         }
         if ($order_item_id) {
             woocommerce_delete_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'));
             woocommerce_add_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'), $tracking_number);
             $message = __('Success. Your tracking number has been updated.', 'wcvendors');
             wc_add_notice($message, 'success');
             // Update order data
             update_post_meta($order_id, '_tracking_provider', $tracking_provider);
             update_post_meta($order_id, '_custom_tracking_provider', $custom_tracking_provider);
             update_post_meta($order_id, '_tracking_number', $tracking_number);
             update_post_meta($order_id, '_custom_tracking_link', $custom_tracking_link);
             update_post_meta($order_id, '_date_shipped', $date_shipped);
         }
     }
     $headers = WCV_Orders::get_headers();
     $all = WCV_Orders::format_order_details($this->orders, $this->product_id);
     wp_enqueue_style('pv_frontend_style', wcv_assets_url . 'css/wcv-frontend.css');
     wp_enqueue_script('pv_frontend_script', wcv_assets_url . 'js/front-orders.js');
     // WC Shipment Tracking Providers
     global $WC_Shipment_Tracking;
     $providers = !empty($WC_Shipment_Tracking->providers) ? $WC_Shipment_Tracking->providers : false;
     $provider_array = array();
     if ($providers) {
         foreach ($providers as $providerss) {
             foreach ($providerss as $provider => $format) {
                 $provider_array[sanitize_title($provider)] = urlencode($format);
             }
         }
     }
     // End
     ob_start();
     // Show the Export CSV button
     if ($this->can_export_csv) {
         wc_get_template('csv-export.php', array(), 'wc-vendors/orders/', wcv_plugin_dir . 'templates/orders/');
     }
     wc_get_template('orders.php', array('headers' => $headers, 'body' => $all['body'], 'items' => $all['items'], 'product_id' => $all['product_id'], 'providers' => $providers, 'provider_array' => $provider_array), 'wc-vendors/orders/', wcv_plugin_dir . 'templates/orders/');
     return ob_get_clean();
 }
function uni_cpo_add_order_item_meta($item_id, $values, $cart_item_key)
{
    $sEnableCalcFrontend = $values['_uni_cpo_calc_option'];
    if (isset($sEnableCalcFrontend)) {
        if (isset($values['_uni_cpo_data'])) {
            $sProductId = $values['product_id'];
            $aCustomOptions = uni_cpo_get_product_attributes($sProductId);
            if ($aCustomOptions) {
                foreach ($aCustomOptions as $aOption) {
                    if (empty($aOption['is_visible']) || $aOption['is_taxonomy'] && !taxonomy_exists($aOption['name'])) {
                        continue;
                    }
                    switch ($aOption['cpo_type']) {
                        case 'input':
                            if ($aOption['value']) {
                                foreach ($aOption['value'] as $sValue) {
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    if (!empty($values['_uni_cpo_data']['uni_cpo_' . $sValue])) {
                                        woocommerce_add_order_item_meta($item_id, $oTerm->name, $values['_uni_cpo_data']['uni_cpo_' . $sValue]);
                                    }
                                }
                            }
                            break;
                        case 'input_number':
                            if ($aOption['value']) {
                                foreach ($aOption['value'] as $sValue) {
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    woocommerce_add_order_item_meta($item_id, $oTerm->name, $values['_uni_cpo_data']['uni_cpo_' . $sValue]);
                                }
                            }
                            break;
                        case 'select':
                            $sParentTermSlug = $aOption['name'];
                            $sFieldValue = $values['_uni_cpo_data']['uni_cpo_' . $sParentTermSlug];
                            $oTerm = get_term_by('slug', $sFieldValue, $sParentTermSlug);
                            if ($sFieldValue) {
                                woocommerce_add_order_item_meta($item_id, wc_attribute_label($aOption['name']), $oTerm->name);
                            }
                            break;
                        case 'radio':
                            $sParentTermSlug = $aOption['name'];
                            $sFieldValue = $values['_uni_cpo_data']['uni_cpo_' . $sParentTermSlug];
                            $oTerm = get_term_by('slug', $sFieldValue, $sParentTermSlug);
                            if ($sFieldValue) {
                                woocommerce_add_order_item_meta($item_id, wc_attribute_label($aOption['name']), $oTerm->name);
                            }
                            break;
                        case 'checkbox':
                            if ($aOption['value']) {
                                foreach ($aOption['value'] as $sValue) {
                                    $sFieldValue = $values['_uni_cpo_data']['uni_cpo_' . $sValue];
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    if ($sFieldValue) {
                                        woocommerce_add_order_item_meta($item_id, $oTerm->name, __('Checked', 'uni-cpo'));
                                    }
                                }
                            }
                            break;
                        case 'checkbox_multiple':
                            if (isset($values['_uni_cpo_data']['uni_cpo_' . $aOption['name']]) && !empty($values['_uni_cpo_data']['uni_cpo_' . $aOption['name']])) {
                                $aCheckboxedTermsName = array();
                                foreach ($values['_uni_cpo_data']['uni_cpo_' . $aOption['name']] as $sValue) {
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    $aCheckboxedTermsName[] = $oTerm->name;
                                }
                                if (isset($aCheckboxedTermsName) && !empty($aCheckboxedTermsName)) {
                                    $sCheckboxedTermsName = implode(', ', $aCheckboxedTermsName);
                                    woocommerce_add_order_item_meta($item_id, wc_attribute_label($aOption['name']), $sCheckboxedTermsName);
                                }
                            }
                            break;
                        case 'color':
                            $sParentTermSlug = $aOption['name'];
                            $sFieldValue = $values['_uni_cpo_data']['uni_cpo_' . $sParentTermSlug];
                            if ($sFieldValue) {
                                foreach ($aOption['value'] as $sValue) {
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data');
                                    if ($aTermData['attr_color_code'] == $sFieldValue) {
                                        woocommerce_add_order_item_meta($item_id, wc_attribute_label($aOption['name']), $oTerm->name);
                                    }
                                }
                            }
                            break;
                        case 'color_ext':
                            $sParentTermSlug = $aOption['name'];
                            $sFieldValue = $values['_uni_cpo_data']['uni_cpo_' . $sParentTermSlug];
                            if ($sFieldValue) {
                                foreach ($aOption['value'] as $sValue) {
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data');
                                    woocommerce_add_order_item_meta($item_id, wc_attribute_label($aOption['name']), $sFieldValue);
                                }
                            }
                            break;
                        case 'textarea':
                            if ($aOption['value']) {
                                foreach ($aOption['value'] as $sValue) {
                                    $oTerm = get_term_by('slug', $sValue, $aOption['name']);
                                    woocommerce_add_order_item_meta($item_id, $oTerm->name, $values['_uni_cpo_data']['uni_cpo_' . $sValue]);
                                }
                            }
                            break;
                    }
                }
            }
        }
    }
}
 /**
  * Triggered when adding an item in the backend.
  *
  * If deposits are forced, set all meta data.
  */
 public function ajax_add_order_item_meta($item_id, $item)
 {
     if (WC_Deposits_Product_Manager::deposits_forced($item['product_id'])) {
         $product = wc_get_product(absint($item['variation_id'] ? $item['variation_id'] : $item['product_id']));
         woocommerce_add_order_item_meta($item_id, '_is_deposit', 'yes');
         woocommerce_add_order_item_meta($item_id, '_deposit_full_amount', $item['line_total']);
         woocommerce_add_order_item_meta($item_id, '_deposit_full_amount_ex_tax', $item['line_total']);
         if ('plan' === WC_Deposits_Product_Manager::get_deposit_type($item['product_id'])) {
             $plan_id = current(WC_Deposits_Plans_Manager::get_plan_ids_for_product($item['product_id']));
             woocommerce_add_order_item_meta($item_id, '_payment_plan', $plan_id);
         } else {
             $plan_id = 0;
         }
         // Change line item costs
         $deposit_amount = WC_Deposits_Product_Manager::get_deposit_amount($product, $plan_id, 'order', $item['line_total']);
         wc_update_order_item_meta($item_id, '_line_total', $deposit_amount);
         wc_update_order_item_meta($item_id, '_line_subtotal', $deposit_amount);
     }
 }
 /**
  * Create new orders based on the parsed data
  */
 private function process_orders()
 {
     global $wpdb;
     $this->imported = $this->merged = 0;
     // peforming a dry run?
     $dry_run = isset($_POST['dry_run']) && $_POST['dry_run'] ? true : false;
     $this->log->add('---');
     $this->log->add(__('Processing orders.', WC_Customer_CSV_Import_Suite::TEXT_DOMAIN));
     foreach ($this->posts as $post) {
         // orders with custom order order numbers can be checked for existance, otherwise there's not much we can do
         if (!empty($post['order_number_formatted']) && isset($this->processed_posts[$post['order_number_formatted']])) {
             $this->skipped++;
             $this->log->add(sprintf(__('> Order %s already processed. Skipping.', WC_Customer_CSV_Import_Suite::TEXT_DOMAIN), $post['order_number_formatted']), true);
             continue;
         }
         // see class-wc-checkout.php for reference
         $order_data = array('post_date' => date('Y-m-d H:i:s', $post['date']), 'post_type' => 'shop_order', 'post_title' => 'Order &ndash; ' . date('F j, Y @ h:i A', $post['date']), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => $post['order_comments'], 'post_author' => 1, 'post_password' => uniqid('order_'));
         if (!$dry_run) {
             // track whether download permissions need to be granted
             $add_download_permissions = false;
             $order_id = wp_insert_post($order_data);
             if (is_wp_error($order_id)) {
                 $this->errored++;
                 $this->log->add(sprintf(__('> Error inserting %s: %s', WC_Customer_CSV_Import_Suite::TEXT_DOMAIN), $post['order_number_formatted'], $order_id->get_error_message()), true);
             }
             // empty update to bump up the post_modified date to today's date (otherwise it would match the post_date, which isn't quite right)
             wp_update_post(array('ID' => $order_id));
             // set order status
             wp_set_object_terms($order_id, $post['status'], 'shop_order_status');
             // handle special meta fields
             update_post_meta($order_id, '_order_key', apply_filters('woocommerce_generate_order_key', uniqid('order_')));
             update_post_meta($order_id, '_order_currency', get_woocommerce_currency());
             // TODO: fine to use store default?
             if (!SV_WC_Plugin_Compatibility::is_wc_version_gte_2_1()) {
                 update_post_meta($order_id, '_order_taxes', array());
                 // pre-2.1
             }
             update_post_meta($order_id, '_prices_include_tax', get_option('woocommerce_prices_include_tax'));
             // add order postmeta
             foreach ($post['postmeta'] as $meta) {
                 $meta_processed = false;
                 // we don't set the "download permissions granted" meta, we call the woocommerce function to take care of this for us
                 if (('Download Permissions Granted' == $meta['key'] || '_download_permissions_granted' == $meta['key']) && $meta['value']) {
                     $add_download_permissions = true;
                     $meta_processed = true;
                 }
                 if (!$meta_processed) {
                     update_post_meta($order_id, $meta['key'], $meta['value']);
                 }
                 // set the paying customer flag on the user meta if applicable
                 if ('_customer_user' == $meta['key'] && $meta['value'] && in_array($post['status'], array('processing', 'completed', 'refunded'))) {
                     update_user_meta($meta['value'], "paying_customer", 1);
                 }
             }
             // handle order items
             $order_items = array();
             $order_item_meta = null;
             foreach ($post['order_items'] as $item) {
                 $product = null;
                 $variation_item_meta = array();
                 // if there's a product_id then we've already determined during parsing that this product exists
                 if ($item['product_id']) {
                     $product = get_product($item['product_id']);
                     // handle variations
                     if (($product->is_type('variable') || $product->is_type('variation') || $product->is_type('subscription_variation')) && method_exists($product, 'get_variation_id')) {
                         foreach ($product->get_variation_attributes() as $key => $value) {
                             $variation_item_meta[] = array('meta_name' => esc_attr(substr($key, 10)), 'meta_value' => $value);
                             // remove the leading 'attribute_' from the name to get 'pa_color' for instance
                         }
                     }
                 }
                 // order item
                 $order_items[] = array('order_item_name' => $product ? $product->get_title() : __('Unknown Product', WC_Customer_CSV_Import_Suite::TEXT_DOMAIN), 'order_item_type' => 'line_item');
                 // standard order item meta
                 $_order_item_meta = array('_qty' => (int) $item['qty'], '_tax_class' => '', '_product_id' => $item['product_id'], '_variation_id' => $product && method_exists($product, 'get_variation_id') ? $product->get_variation_id() : 0, '_line_subtotal' => number_format((double) $item['total'], 2, '.', ''), '_line_subtotal_tax' => 0, '_line_total' => number_format((double) $item['total'], 2, '.', ''), '_line_tax' => 0);
                 // add any product variation meta
                 foreach ($variation_item_meta as $meta) {
                     $_order_item_meta[$meta['meta_name']] = $meta['meta_value'];
                 }
                 // include any arbitrary order item meta
                 $_order_item_meta = array_merge($_order_item_meta, $item['meta']);
                 $order_item_meta[] = $_order_item_meta;
             }
             foreach ($order_items as $key => $order_item) {
                 $order_item_id = woocommerce_add_order_item($order_id, $order_item);
                 if ($order_item_id) {
                     foreach ($order_item_meta[$key] as $meta_key => $meta_value) {
                         if (strpos($meta_value, ':{i')) {
                             $meta_value = unserialize(stripslashes($meta_value));
                             //'a:1:{i:0;s:19:"2014-05-01 08:00:00";}';
                         }
                         woocommerce_add_order_item_meta($order_item_id, $meta_key, $meta_value);
                     }
                 }
             }
             // create the shipping order items (WC 2.1+)
             foreach ($post['order_shipping'] as $order_shipping) {
                 $shipping_order_item = array('order_item_name' => $order_shipping['title'], 'order_item_type' => 'shipping');
                 $shipping_order_item_id = woocommerce_add_order_item($order_id, $shipping_order_item);
                 if ($shipping_order_item_id) {
                     woocommerce_add_order_item_meta($shipping_order_item_id, 'method_id', $order_shipping['method_id']);
                     woocommerce_add_order_item_meta($shipping_order_item_id, 'cost', $order_shipping['cost']);
                 }
             }
             // create the tax order items (WC 2.1+)
             foreach ($post['tax_items'] as $tax_item) {
                 $tax_order_item = array('order_item_name' => $tax_item['title'], 'order_item_type' => 'tax');
                 $tax_order_item_id = woocommerce_add_order_item($order_id, $tax_order_item);
                 if ($tax_order_item_id) {
                     woocommerce_add_order_item_meta($tax_order_item_id, 'rate_id', $tax_item['rate_id']);
                     woocommerce_add_order_item_meta($tax_order_item_id, 'label', $tax_item['label']);
                     woocommerce_add_order_item_meta($tax_order_item_id, 'compound', $tax_item['compound']);
                     woocommerce_add_order_item_meta($tax_order_item_id, 'tax_amount', $tax_item['tax_amount']);
                     woocommerce_add_order_item_meta($tax_order_item_id, 'shipping_tax_amount', $tax_item['shipping_tax_amount']);
                 }
             }
             // Grant downloadalbe product permissions
             if ($add_download_permissions) {
                 woocommerce_downloadable_product_permissions($order_id);
             }
             // add order notes
             $order = new WC_Order($order_id);
             foreach ($post['notes'] as $order_note) {
                 $order->add_order_note($order_note);
             }
             // record the product sales
             $order->record_product_sales();
         }
         // ! dry run
         // was an original order number provided?
         if (!empty($post['order_number_formatted'])) {
             if (!$dry_run) {
                 // do our best to provide some custom order number functionality while also allowing 3rd party plugins to provide their own custom order number facilities
                 do_action('woocommerce_set_order_number', $order, $post['order_number'], $post['order_number_formatted']);
                 $order->add_order_note(sprintf(__("Original order #%s", WC_Customer_CSV_Import_Suite::TEXT_DOMAIN), $post['order_number_formatted']));
                 // get the order so we can display the correct order number
                 $order = new WC_Order($order_id);
             }
             $this->processed_posts[$post['order_number_formatted']] = $post['order_number_formatted'];
         }
         $this->imported++;
         $this->log->add(sprintf(__('> Finished importing order %s', WC_Customer_CSV_Import_Suite::TEXT_DOMAIN), $dry_run ? "" : $order->get_order_number()));
     }
     $this->log->add(__('Finished processing orders.', WC_Customer_CSV_Import_Suite::TEXT_DOMAIN));
     unset($this->posts);
 }
 /**
  * create_order function.
  *
  * @access public
  * @return void
  */
 public function create_order()
 {
     global $woocommerce, $wpdb;
     // Give plugins the opportunity to create an order themselves
     $order_id = apply_filters('woocommerce_create_order', null, $this);
     if (is_numeric($order_id)) {
         return $order_id;
     }
     // Create Order (send cart variable so we can record items and reduce inventory). Only create if this is a new order, not if the payment was rejected.
     $order_data = apply_filters('woocommerce_new_order_data', array('post_type' => 'shop_order', 'post_title' => sprintf(__('Order &ndash; %s', 'woocommerce'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'woocommerce'))), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '', 'post_author' => 1, 'post_password' => uniqid('order_')));
     // Insert or update the post data
     $create_new_order = true;
     if ($woocommerce->session->order_awaiting_payment > 0) {
         $order_id = absint($woocommerce->session->order_awaiting_payment);
         /* Check order is unpaid by getting its status */
         $terms = wp_get_object_terms($order_id, 'shop_order_status', array('fields' => 'slugs'));
         $order_status = isset($terms[0]) ? $terms[0] : 'pending';
         // Resume the unpaid order if its pending
         if ($order_status == 'pending' || $order_status == 'failed') {
             // Update the existing order as we are resuming it
             $create_new_order = false;
             $order_data['ID'] = $order_id;
             wp_update_post($order_data);
             // Clear the old line items - we'll add these again in case they changed
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d )", $order_id));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d", $order_id));
             // Trigger an action for the resumed order
             do_action('woocommerce_resume_order', $order_id);
         }
     }
     if ($create_new_order) {
         $order_id = wp_insert_post($order_data);
         if (is_wp_error($order_id)) {
             throw new MyException('Error: Unable to create order. Please try again.');
         } else {
             do_action('woocommerce_new_order', $order_id);
         }
     }
     // Store user data
     if ($this->checkout_fields['billing']) {
         foreach ($this->checkout_fields['billing'] as $key => $field) {
             update_post_meta($order_id, '_' . $key, $this->posted[$key]);
             // User
             if ($this->customer_id && !empty($this->posted[$key])) {
                 update_user_meta($this->customer_id, $key, $this->posted[$key]);
                 // Special fields
                 switch ($key) {
                     case "billing_email":
                         if (!email_exists($this->posted[$key])) {
                             wp_update_user(array('ID' => $this->customer_id, 'user_email' => $this->posted[$key]));
                         }
                         break;
                     case "billing_first_name":
                         wp_update_user(array('ID' => $this->customer_id, 'first_name' => $this->posted[$key]));
                         break;
                     case "billing_last_name":
                         wp_update_user(array('ID' => $this->customer_id, 'last_name' => $this->posted[$key]));
                         break;
                 }
             }
         }
     }
     if ($this->checkout_fields['shipping'] && ($woocommerce->cart->needs_shipping() || get_option('woocommerce_require_shipping_address') == 'yes')) {
         foreach ($this->checkout_fields['shipping'] as $key => $field) {
             $postvalue = false;
             if ($this->posted['shiptobilling']) {
                 if (isset($this->posted[str_replace('shipping_', 'billing_', $key)])) {
                     $postvalue = $this->posted[str_replace('shipping_', 'billing_', $key)];
                     update_post_meta($order_id, '_' . $key, $postvalue);
                 }
             } else {
                 $postvalue = $this->posted[$key];
                 update_post_meta($order_id, '_' . $key, $postvalue);
             }
             // User
             if ($postvalue && $this->customer_id) {
                 update_user_meta($this->customer_id, $key, $postvalue);
             }
         }
     }
     // Save any other user meta
     if ($this->customer_id) {
         do_action('woocommerce_checkout_update_user_meta', $this->customer_id, $this->posted);
     }
     // Store the line items to the new/resumed order
     foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
         $_product = $values['data'];
         // Add line item
         $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $_product->get_title(), 'order_item_type' => 'line_item'));
         // Add line item meta
         if ($item_id) {
             woocommerce_add_order_item_meta($item_id, '_qty', apply_filters('woocommerce_stock_amount', $values['quantity']));
             woocommerce_add_order_item_meta($item_id, '_tax_class', $_product->get_tax_class());
             woocommerce_add_order_item_meta($item_id, '_product_id', $values['product_id']);
             woocommerce_add_order_item_meta($item_id, '_variation_id', $values['variation_id']);
             woocommerce_add_order_item_meta($item_id, '_line_subtotal', woocommerce_format_decimal($values['line_subtotal'], 4));
             woocommerce_add_order_item_meta($item_id, '_line_total', woocommerce_format_decimal($values['line_total'], 4));
             woocommerce_add_order_item_meta($item_id, '_line_tax', woocommerce_format_decimal($values['line_tax'], 4));
             woocommerce_add_order_item_meta($item_id, '_line_subtotal_tax', woocommerce_format_decimal($values['line_subtotal_tax'], 4));
             // Store variation data in meta so admin can view it
             if ($values['variation'] && is_array($values['variation'])) {
                 foreach ($values['variation'] as $key => $value) {
                     woocommerce_add_order_item_meta($item_id, esc_attr(str_replace('attribute_', '', $key)), $value);
                 }
             }
             // Add line item meta for backorder status
             if ($_product->backorders_require_notification() && $_product->is_on_backorder($values['quantity'])) {
                 woocommerce_add_order_item_meta($item_id, apply_filters('woocommerce_backordered_item_meta_name', __('Backordered', 'woocommerce'), $cart_item_key, $order_id), $values['quantity'] - max(0, $_product->get_total_stock()));
             }
             // Allow plugins to add order item meta
             do_action('woocommerce_add_order_item_meta', $item_id, $values);
         }
     }
     // Store fees
     foreach ($woocommerce->cart->get_fees() as $fee) {
         $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $fee->name, 'order_item_type' => 'fee'));
         if ($fee->taxable) {
             woocommerce_add_order_item_meta($item_id, '_tax_class', $fee->tax_class);
         } else {
             woocommerce_add_order_item_meta($item_id, '_tax_class', '0');
         }
         woocommerce_add_order_item_meta($item_id, '_line_total', woocommerce_format_decimal($fee->amount));
         woocommerce_add_order_item_meta($item_id, '_line_tax', woocommerce_format_decimal($fee->tax));
     }
     // Store tax rows
     foreach (array_keys($woocommerce->cart->taxes + $woocommerce->cart->shipping_taxes) as $key) {
         $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $woocommerce->cart->tax->get_rate_code($key), 'order_item_type' => 'tax'));
         // Add line item meta
         if ($item_id) {
             woocommerce_add_order_item_meta($item_id, 'rate_id', $key);
             woocommerce_add_order_item_meta($item_id, 'label', $woocommerce->cart->tax->get_rate_label($key));
             woocommerce_add_order_item_meta($item_id, 'compound', absint($woocommerce->cart->tax->is_compound($key) ? 1 : 0));
             woocommerce_add_order_item_meta($item_id, 'tax_amount', woocommerce_clean(isset($woocommerce->cart->taxes[$key]) ? $woocommerce->cart->taxes[$key] : 0));
             woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean(isset($woocommerce->cart->shipping_taxes[$key]) ? $woocommerce->cart->shipping_taxes[$key] : 0));
         }
     }
     // Store coupons
     if ($applied_coupons = $woocommerce->cart->get_applied_coupons()) {
         foreach ($applied_coupons as $code) {
             $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $code, 'order_item_type' => 'coupon'));
             // Add line item meta
             if ($item_id) {
                 woocommerce_add_order_item_meta($item_id, 'discount_amount', isset($woocommerce->cart->coupon_discount_amounts[$code]) ? $woocommerce->cart->coupon_discount_amounts[$code] : 0);
             }
         }
     }
     // Store meta
     if ($this->shipping_method) {
         update_post_meta($order_id, '_shipping_method', $this->shipping_method->id);
         update_post_meta($order_id, '_shipping_method_title', $this->shipping_method->label);
     }
     if ($this->payment_method) {
         update_post_meta($order_id, '_payment_method', $this->payment_method->id);
         update_post_meta($order_id, '_payment_method_title', $this->payment_method->get_title());
     }
     update_post_meta($order_id, '_order_shipping', woocommerce_format_total($woocommerce->cart->shipping_total));
     update_post_meta($order_id, '_order_discount', woocommerce_format_total($woocommerce->cart->get_order_discount_total()));
     update_post_meta($order_id, '_cart_discount', woocommerce_format_total($woocommerce->cart->get_cart_discount_total()));
     update_post_meta($order_id, '_order_tax', woocommerce_clean($woocommerce->cart->tax_total));
     update_post_meta($order_id, '_order_shipping_tax', woocommerce_clean($woocommerce->cart->shipping_tax_total));
     update_post_meta($order_id, '_order_total', woocommerce_format_total($woocommerce->cart->total));
     update_post_meta($order_id, '_order_key', apply_filters('woocommerce_generate_order_key', uniqid('order_')));
     update_post_meta($order_id, '_customer_user', absint($this->customer_id));
     update_post_meta($order_id, '_order_currency', get_woocommerce_currency());
     update_post_meta($order_id, '_prices_include_tax', get_option('woocommerce_prices_include_tax'));
     update_post_meta($order_id, '_customer_ip_address', isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
     update_post_meta($order_id, '_customer_user_agent', isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
     // Let plugins add meta
     do_action('woocommerce_checkout_update_order_meta', $order_id, $this->posted);
     // Order status
     wp_set_object_terms($order_id, 'pending', 'shop_order_status');
     return $order_id;
 }
 function order_item_meta($values, $order)
 {
     global $wpdb;
     $currency_symbol = get_woocommerce_currency_symbol();
     $product_id = $values['product_id'];
     $quantity = $values['quantity'];
     $booking = $values['booking'];
     $order_item_id = $order->order_item_id;
     $order_id = $order->order_id;
     $global_settings = json_decode(get_option('woocommerce_booking_global_settings'));
     $booking_settings = get_post_meta($product_id, 'woocommerce_booking_settings', true);
     if (isset($booking_settings['booking_fixed_block_enable']) && isset($booking_settings['booking_partial_payment_radio']) && is_plugin_active("bkap-deposits/deposits.php")) {
         if (isset($global_settings->enable_rounding) && $global_settings->enable_rounding == "on") {
             woocommerce_add_order_item_meta($order_item_id, book_t('book.item-partial-total'), $currency_symbol . round($values['booking'][0]['Total'] * $values['quantity']), true);
             woocommerce_add_order_item_meta($order_item_id, book_t('book.item-partial-deposit'), $currency_symbol . round($values['booking'][0]['Deposit'] * $values['quantity']), true);
             woocommerce_add_order_item_meta($order_item_id, book_t('book.item-partial-remaining'), $currency_symbol . round($values['booking'][0]['Remaining'] * $values['quantity']), true);
         } else {
             woocommerce_add_order_item_meta($order_item_id, book_t('book.item-partial-total'), $currency_symbol . $values['booking'][0]['Total'] * $values['quantity'], true);
             woocommerce_add_order_item_meta($order_item_id, book_t('book.item-partial-deposit'), $currency_symbol . $values['booking'][0]['Deposit'] * $values['quantity'], true);
             woocommerce_add_order_item_meta($order_item_id, book_t('book.item-partial-remaining'), $currency_symbol . $values['booking'][0]['Remaining'] * $values['quantity'], true);
         }
     }
 }
// Do the same kind of update for order_taxes - move to lines
// Reverse with UPDATE `wpwc_postmeta` SET meta_key = '_order_taxes' WHERE meta_key = '_order_taxes_old'
$order_tax_rows = $wpdb->get_results("\r\n\tSELECT * FROM {$wpdb->postmeta}\r\n\tWHERE meta_key = '_order_taxes'\r\n");
foreach ($order_tax_rows as $order_tax_row) {
    $order_taxes = (array) maybe_unserialize($order_tax_row->meta_value);
    if ($order_taxes) {
        foreach ($order_taxes as $order_tax) {
            if (!isset($order_tax['label']) || !isset($order_tax['cart_tax']) || !isset($order_tax['shipping_tax'])) {
                continue;
            }
            $item_id = woocommerce_add_order_item($order_tax_row->post_id, array('order_item_name' => $order_tax['label'], 'order_item_type' => 'tax'));
            // Add line item meta
            if ($item_id) {
                woocommerce_add_order_item_meta($item_id, 'compound', absint(isset($order_tax['compound']) ? $order_tax['compound'] : 0));
                woocommerce_add_order_item_meta($item_id, 'tax_amount', woocommerce_clean($order_tax['cart_tax']));
                woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($order_tax['shipping_tax']));
            }
            // Delete from DB (rename)
            $wpdb->query($wpdb->prepare("\r\n\t\t\t\tUPDATE {$wpdb->postmeta}\r\n\t\t\t\tSET meta_key = '_order_taxes_old'\r\n\t\t\t\tWHERE meta_key = '_order_taxes'\r\n\t\t\t\tAND post_id = %d\r\n\t\t\t", $order_tax_row->post_id));
            unset($tax_amount);
        }
    }
}
// Grab the pre 2.0 Image options and use to populate the new image options settings,
// cleaning up afterwards like nice people do
foreach (array('catalog', 'single', 'thumbnail') as $value) {
    $old_settings = array_filter(array('width' => get_option('woocommerce_' . $value . '_image_width'), 'height' => get_option('woocommerce_' . $value . '_image_height'), 'crop' => get_option('woocommerce_' . $value . '_image_crop')));
    if (!empty($old_settings) && update_option('shop_' . $value . '_image_size', $old_settings)) {
        delete_option('woocommerce_' . $value . '_image_width');
        delete_option('woocommerce_' . $value . '_image_height');
        delete_option('woocommerce_' . $value . '_image_crop');
 /**
  * Add each subscription product's details to an order so that the state of the subscription persists even when a product is changed
  *
  * @since 1.2.5
  */
 public static function add_order_item_meta($item_id, $values)
 {
     global $woocommerce;
     if (!WC_Subscriptions_Cart::cart_contains_subscription_renewal('child') && WC_Subscriptions_Product::is_subscription($values['product_id'])) {
         $cart_item = $values['data'];
         $product_id = empty($values['variation_id']) ? $values['product_id'] : $values['variation_id'];
         // Add subscription details so order state persists even when a product is changed
         $period = isset($cart_item->subscription_period) ? $cart_item->subscription_period : WC_Subscriptions_Product::get_period($product_id);
         $interval = isset($cart_item->subscription_period_interval) ? $cart_item->subscription_period_interval : WC_Subscriptions_Product::get_interval($product_id);
         $length = isset($cart_item->subscription_length) ? $cart_item->subscription_length : WC_Subscriptions_Product::get_length($product_id);
         $trial_length = isset($cart_item->subscription_trial_length) ? $cart_item->subscription_trial_length : WC_Subscriptions_Product::get_trial_length($product_id);
         $trial_period = isset($cart_item->subscription_trial_period) ? $cart_item->subscription_trial_period : WC_Subscriptions_Product::get_trial_period($product_id);
         $sign_up_fee = isset($cart_item->subscription_sign_up_fee) ? $cart_item->subscription_sign_up_fee : WC_Subscriptions_Product::get_sign_up_fee($product_id);
         woocommerce_add_order_item_meta($item_id, '_subscription_period', $period);
         woocommerce_add_order_item_meta($item_id, '_subscription_interval', $interval);
         woocommerce_add_order_item_meta($item_id, '_subscription_length', $length);
         woocommerce_add_order_item_meta($item_id, '_subscription_trial_length', $trial_length);
         woocommerce_add_order_item_meta($item_id, '_subscription_trial_period', $trial_period);
         woocommerce_add_order_item_meta($item_id, '_subscription_recurring_amount', $woocommerce->cart->base_recurring_prices[$product_id]);
         // WC_Subscriptions_Product::get_price() would return a price without filters applied
         woocommerce_add_order_item_meta($item_id, '_subscription_sign_up_fee', $sign_up_fee);
         // Calculated recurring amounts for the item
         woocommerce_add_order_item_meta($item_id, '_recurring_line_total', $woocommerce->cart->recurring_cart_contents[$values['product_id']]['recurring_line_total']);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_tax', $woocommerce->cart->recurring_cart_contents[$values['product_id']]['recurring_line_tax']);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_subtotal', $woocommerce->cart->recurring_cart_contents[$values['product_id']]['recurring_line_subtotal']);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_subtotal_tax', $woocommerce->cart->recurring_cart_contents[$values['product_id']]['recurring_line_subtotal_tax']);
         // Add recurring line tax data (for WC 2.2+)
         $raw_tax_data = $woocommerce->cart->recurring_cart_contents[$values['product_id']]['recurring_line_tax_data'];
         $recurring_tax_data = array();
         $recurring_tax_data['total'] = array_map('wc_format_decimal', $raw_tax_data['total']);
         $recurring_tax_data['subtotal'] = array_map('wc_format_decimal', $raw_tax_data['subtotal']);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_tax_data', $recurring_tax_data);
     }
 }