/**
  * We use a trial period to make sure totals are calculated correctly (i.e. order total does not include any recurring amounts)
  * but we don't want switched subscriptions to actually have a trial period, so reset the value on the order after checkout.
  *
  * @since 1.4
  */
 public static function fix_order_item_meta($item_id, $values)
 {
     if (false !== self::cart_contains_subscription_switch()) {
         woocommerce_update_order_item_meta($item_id, '_subscription_trial_length', 0);
         woocommerce_update_order_item_meta($item_id, '_subscription_trial_expiry_date', 0);
     }
 }
        function update_order_details($order_id, $post)
        {
            global $wpdb, $woocommerce;
            $order_query = "SELECT * FROM `" . $wpdb->prefix . "booking_order_history`\n\t\t\t\tWHERE order_id = '" . $order_id . "' ";
            $existing_order_result = $wpdb->get_results($order_query);
            $new_order = false;
            $edit_order = true;
            if (count($existing_order_result) == 0) {
                $new_order = true;
                $edit_order = false;
            }
            if (isset($_POST['save']) && $_POST['save']) {
                $order = new WC_Order($order_id);
                $items = $order->get_items();
                //print_r($_POST);exit;
                foreach ($items as $cart_item_key => $values) {
                    //echo "here";
                    $order_item_id = array();
                    if (isset($_POST['order_item_id'])) {
                        $order_item_id = $_POST['order_item_id'];
                    }
                    //print_r($order_item_id);
                    foreach ($order_item_id as $oid_key => $oid_value) {
                        if ($cart_item_key == $oid_value) {
                            $meta = $order->has_meta($cart_item_key);
                            $existing_quantity = woocommerce_get_order_item_meta($cart_item_key, '_qty', true);
                            $order_item_qty = $_POST['order_item_qty'];
                            //print_r($order_item_qty);
                            $quantity = $order_item_qty[$oid_value];
                            $post_id = get_post_meta($values['product_id'], '_icl_lang_duplicate_of', true);
                            if ($post_id == '' && $post_id == null) {
                                $post_time = get_post($values['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 ($results_post_id) {
                                    $post_id = $results_post_id[0]->ID;
                                } else {
                                    $post_id = $values['product_id'];
                                }
                            }
                            if (isset($_POST['meta_key'])) {
                                $meta_keys = $_POST['meta_key'];
                            } else {
                                $meta_keys = array();
                            }
                            if (isset($_POST['meta_value'])) {
                                $meta_values = $_POST['meta_value'];
                            } else {
                                $meta_values = array();
                            }
                            $item_key = $_POST['order_item_id'];
                            $line_subtotal = $_POST['line_subtotal'];
                            //print_r($line_subtotal);
                            $booking = array();
                            $variation_id = $values['variation_id'];
                            $order_key_exists = '';
                            //echo $oid_value;
                            if (isset($_POST['meta_ids' . $cart_item_key])) {
                                $meta_ids = explode(",", $_POST['meta_ids' . $cart_item_key]);
                            } else {
                                $id_query = "SELECT meta_id FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` WHERE order_item_id = '" . $cart_item_key . "'";
                                $results = $wpdb->get_results($id_query);
                                $i = 0;
                                $meta_ids = array();
                                foreach ($results as $k => $v) {
                                    $meta_ids[] = $v->meta_id;
                                    $i++;
                                }
                            }
                            //print_r($meta_ids);
                            foreach ($meta as $mk_key => $mk_value) {
                                if ($mk_value['meta_key'] == get_option('book.item-meta-date') || $mk_value['meta_key'] == strip_tags(get_option("checkout.item-meta-date")) && in_array($mk_key, $meta_ids)) {
                                    $key = $mk_value['meta_key'];
                                    $meta_id = $mk_value['meta_id'];
                                    //echo $key;
                                    $booking[$key] = $mk_value['meta_value'];
                                    $order_key_exists = 'Y';
                                }
                            }
                            //print_r($meta);exit;
                            if (count($booking) == 0) {
                                foreach ($meta_keys as $mk_key => $mk_value) {
                                    foreach ($meta_values as $mv_key => $mv_value) {
                                        if ($mk_key == $mv_key && in_array($mk_key, $meta_ids)) {
                                            $booking[$mk_value] = $mv_value;
                                            $order_key_exists = 'N';
                                        }
                                    }
                                }
                            }
                            $booking_settings = get_post_meta($post_id, 'woocommerce_booking_settings', true);
                            //echo get_option('book.item-meta-time');
                            //print_r($meta_keys);
                            //print_r($booking);
                            $date_name = get_option('book.item-meta-date');
                            global $bkap_block_booking;
                            $number_of_fixed_price_blocks = $bkap_block_booking->get_fixed_blocks_count($post_id);
                            //print_r($number_of_fixed_price_blocks);exit;
                            $check_out_name = strip_tags(get_option("checkout.item-meta-date"));
                            if (isset($booking_settings['booking_fixed_block_enable']) && $booking_settings['booking_fixed_block_enable'] == 'yes' && (isset($number_of_fixed_price_blocks) && $number_of_fixed_price_blocks > 0) && isset($booking[$check_out_name]) && $booking[$check_out_name] != "") {
                                if (isset($booking[$date_name]) && $booking[$date_name] != "") {
                                    $date_select = $booking[$date_name];
                                    woocommerce_update_order_item_meta($cart_item_key, $date_name, sanitize_text_field($date_select, true));
                                }
                            }
                            $date_checkout_select = '';
                            if (isset($booking[$check_out_name]) && $booking[$check_out_name] != "") {
                                //echo "here in checkout";
                                //print_r($booking[$check_out_name]);exit;
                                $date_checkout_select = $booking[$check_out_name];
                                woocommerce_update_order_item_meta($cart_item_key, $check_out_name, sanitize_text_field($date_checkout_select, true));
                                if ($order_key_exists == 'Y') {
                                    $total_price = $line_subtotal[$cart_item_key];
                                    $line_subtotal[$cart_item_key] = $total_price;
                                } else {
                                    if (isset($_POST['wapbk_admin_hidden_date_checkout_' . $cart_item_key])) {
                                        $checkout_date = $_POST['wapbk_admin_hidden_date_checkout_' . $cart_item_key];
                                    }
                                    if (isset($_POST['wapbk_admin_hidden_date_' . $cart_item_key])) {
                                        $checkin_date = $_POST['wapbk_admin_hidden_date_' . $cart_item_key];
                                    }
                                    $days = (strtotime($checkout_date) - strtotime($checkin_date)) / (60 * 60 * 24);
                                    //echo $days;
                                    //print_r($_POST['']);exit;
                                    if (isset($_POST['wapbk_admin_same_day_' . $cart_item_key]) && $_POST['wapbk_admin_same_day_' . $cart_item_key] == 'on') {
                                        if ($days >= 0) {
                                            //if(is_plugin_active('bkap-rental/rental.php') && isset($booking_settings['booking_charge_per_day']) && $booking_settings['booking_charge_per_day'] == 'on')
                                            if (isset($_POST['add_days_' . $cart_item_key])) {
                                                $days = $days + $_POST['add_days_' . $cart_item_key];
                                            }
                                            //echo $days;exit;
                                            $total_price = $days * $line_subtotal[$cart_item_key] * $values['qty'];
                                        }
                                    } else {
                                        if ($days > 0) {
                                            //if(is_plugin_active('bkap-rental/rental.php') && isset($booking_settings['booking_charge_per_day']) && $booking_settings['booking_charge_per_day'] == 'on')
                                            if (isset($_POST['add_days_' . $cart_item_key])) {
                                                $days = $days + $_POST['add_days_' . $cart_item_key];
                                            }
                                            //echo $days;exit;
                                            $total_price = $days * $line_subtotal[$cart_item_key] * $values['qty'];
                                        }
                                    }
                                    //print_r($number_of_fixed_price_blocks);exit;
                                    if (isset($booking_settings['booking_fixed_block_enable']) && $booking_settings['booking_fixed_block_enable'] == 'yes' && (isset($number_of_fixed_price_blocks) && $number_of_fixed_price_blocks > 0)) {
                                        if (isset($_POST['admin_block_option_price_' . $cart_item_key])) {
                                            $total_price = $_POST['admin_block_option_price_' . $cart_item_key];
                                        } else {
                                            $total_price = '';
                                        }
                                        //echo $total_price;exit;
                                    } else {
                                        if (isset($booking_settings['booking_block_price_enable']) && $booking_settings['booking_block_price_enable'] == 'yes') {
                                            $get_price = $this->get_per_night_price($post_id, $days, $booking_settings, $values['variation_id']);
                                            //echo $get_price;
                                            $price_exploded = explode("-", $get_price);
                                            $total_price = '';
                                            if (isset($price_exploded[1]) && $price_exploded[1] == "per_day") {
                                                $total_price = $days * $price_exploded[0] * $values['qty'];
                                            } else {
                                                if (isset($price_exploded[1]) && $price_exploded[1] == "fixed") {
                                                    $total_price = $price_exploded[0] * $values['qty'];
                                                }
                                            }
                                            //echo $total_price;
                                        }
                                    }
                                    // Round the price if rounding is enabled
                                }
                                $global_settings = json_decode(get_option('woocommerce_booking_global_settings'));
                                if (isset($global_settings->enable_rounding) && $global_settings->enable_rounding == "on") {
                                    $round_price = round($total_price);
                                    $total_price = $round_price;
                                }
                                $line_subtotal[$cart_item_key] = $total_price;
                                //print_r($line_subtotal);
                                $query_update_subtotal = "UPDATE `" . $wpdb->prefix . "woocommerce_order_itemmeta`\n\t\t\t\t\t\t\t\t\tSET meta_value = '" . woocommerce_clean($total_price) . "'\n\t\t\t\t\t\t\t\t\tWHERE order_item_id = '" . $cart_item_key . "'\n\t\t\t\t\t\t\t\t\tAND meta_key = '_line_subtotal'";
                                $wpdb->query($query_update_subtotal);
                                //print_r($query_update_subtotal);
                                $_POST['line_subtotal'] = $line_subtotal;
                                $query_update_total = "UPDATE `" . $wpdb->prefix . "woocommerce_order_itemmeta`\n\t\t\t\t\t\t\t\t\tSET meta_value = '" . woocommerce_clean($total_price) . "'\n\t\t\t\t\t\t\t\t\tWHERE order_item_id = '" . $cart_item_key . "'\n\t\t\t\t\t\t\t\t\tAND meta_key = '_line_total'";
                                $wpdb->query($query_update_total);
                                $_POST['line_total'] = $line_subtotal;
                            }
                            $time_name = get_option('book.item-meta-time');
                            if (isset($booking[$time_name]) && $booking[$time_name] != "") {
                                $time_select = $booking[$time_name];
                                $time_exploded = explode("-", $time_select);
                                $saved_settings = json_decode(get_option('woocommerce_booking_global_settings'));
                                if (isset($saved_settings)) {
                                    $time_format = $saved_settings->booking_time_format;
                                } else {
                                    $time_format = "12";
                                }
                                $time_slot_to_display = '';
                                $from_time = trim($time_exploded[0]);
                                if (isset($time_exploded[1])) {
                                    $to_time = trim($time_exploded[1]);
                                } else {
                                    $to_time = '';
                                }
                                if ($time_format == '12') {
                                    $from_time = date('h:i A', strtotime($time_exploded[0]));
                                    if (isset($time_exploded[1])) {
                                        $to_time = date('h:i A', strtotime($time_exploded[1]));
                                    }
                                }
                                $query_from_time = date('G:i', strtotime($time_exploded[0]));
                                if (isset($time_exploded[1])) {
                                    $query_to_time = date('G:i', strtotime($time_exploded[1]));
                                } else {
                                    $query_to_time = '';
                                }
                                if ($to_time != '') {
                                    $time_slot_to_display = $from_time . ' - ' . $to_time;
                                } else {
                                    $time_slot_to_display = $from_time;
                                }
                                woocommerce_update_order_item_meta($cart_item_key, $time_name, $time_slot_to_display);
                            }
                            $query_update_quantity = "UPDATE `" . $wpdb->prefix . "woocommerce_order_itemmeta`\n\t\t\t\t\t\t\t\t\t\tSET meta_value = '" . woocommerce_clean($quantity) . "'\n\t\t\t\t\t\t\t\t\t\tWHERE order_item_id = '" . $cart_item_key . "'\n\t\t\t\t\t\t\t\t\t\tAND meta_key = '_qty'";
                            //echo $query_update_quantity;
                            $wpdb->query($query_update_quantity);
                            //echo $quantity;
                            $order_item_qty[$cart_item_key] = $quantity;
                            $_POST['order_item_qty'] = $order_item_qty;
                            if ($new_order == false && $edit_order == true) {
                                if (isset($booking_settings['booking_enable_multiple_day']) && $booking_settings['booking_enable_multiple_day'] == 'on') {
                                    $booking_ids = array();
                                    if (in_array($check_out_name, $booking)) {
                                        $start_date = date("Y-m-d", strtotime($booking[$date_name]));
                                        $end_date = date("Y-m-d", strtotime($booking[$check_out_name]));
                                        $query_result = "SELECT COUNT(*) as bookings_done FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND end_date = '" . $end_date . "' AND post_id = " . $post_id;
                                        //echo $query_result;
                                        $item_results_lockout = $wpdb->get_results($query_result);
                                        $lockout = "";
                                        if (isset($booking_settings['booking_date_lockout'])) {
                                            $lockout = $booking_settings['booking_date_lockout'];
                                        }
                                        if (count($item_results_lockout) > 0) {
                                            $booking_available = $lockout - $item_results_lockout[0]->bookings_done;
                                            foreach ($existing_order_result as $ekey => $evalue) {
                                                $booking_id = $evalue->booking_id;
                                                //print_r($evalue);
                                                $query = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tid = {$booking_id} ";
                                                $item_results = $wpdb->get_results($query);
                                                //print_r($item_results);
                                                if (count($item_results) > 0) {
                                                    $booking_ids[] = $booking_id;
                                                }
                                            }
                                            if ($order_key_exists == 'Y') {
                                                if ($existing_quantity < $quantity) {
                                                    if ($quantity <= $booking_available) {
                                                        for ($i = $existing_quantity; $i < $quantity; $i++) {
                                                            $query = "INSERT INTO `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(post_id,weekday,start_date,end_date,from_time,to_time,total_booking,available_booking)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $post_id . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $start_date . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $end_date . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'0',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'0' )";
                                                            $wpdb->query($query);
                                                            $new_booking_id = mysql_insert_id();
                                                            $order_query = "INSERT INTO `" . $wpdb->prefix . "booking_order_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(order_id,booking_id)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $order_id . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $new_booking_id . "' )";
                                                            $wpdb->query($order_query);
                                                        }
                                                    } else {
                                                        if ($lockout != 0) {
                                                            $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                            $wpdb->query($query_date);
                                                            /*$query_checkout_date = "DELETE FROM `".$wpdb->prefix."woocommerce_order_itemmeta` 
                                                            			WHERE 
                                                            			order_item_id = ".$cart_item_key." AND meta_key = '".$check_out_name."'";
                                                            		$wpdb->query( $query_checkout_date);*/
                                                            $post = get_post($post_id);
                                                            //print_r($post);
                                                            $title = $post->post_title;
                                                            print '
															<script type="text/javascript">
															alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected dates. Please reduce the quantity or remove it from your order."); 
															window.history.back();
															//return;
														</script>';
                                                            exit;
                                                        }
                                                    }
                                                } elseif ($existing_quantity > $quantity) {
                                                    for ($i = $quantity; $i < $existing_quantity; $i++) {
                                                        $query = "DELETE FROM `" . $wpdb->prefix . "booking_history` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid = " . $booking_ids[$i];
                                                        $wpdb->query($query);
                                                        $order_query = "DELETE FROM `" . $wpdb->prefix . "booking_order_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE order_id = '" . $order_id . "' \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbooking_id = '" . $booking_ids[$i] . "'";
                                                        $wpdb->query($order_query);
                                                    }
                                                }
                                            } else {
                                                if ($order_key_exists == 'N') {
                                                    if ($quantity <= $booking_available) {
                                                        for ($i = $existing_quantity; $i <= $quantity; $i++) {
                                                            $query = "INSERT INTO `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(post_id,weekday,start_date,end_date,from_time,to_time,total_booking,available_booking)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $post_id . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $start_date . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $end_date . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'0',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'0' )";
                                                            $wpdb->query($query);
                                                            $new_booking_id = mysql_insert_id();
                                                            $order_query = "INSERT INTO `" . $wpdb->prefix . "booking_order_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(order_id,booking_id)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $order_id . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $new_booking_id . "' )";
                                                            $wpdb->query($order_query);
                                                        }
                                                    } else {
                                                        if ($lockout != 0) {
                                                            $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                            $wpdb->query($query_date);
                                                            /*$query_checkout_date = "DELETE FROM `".$wpdb->prefix."woocommerce_order_itemmeta`
                                                            		WHERE
                                                            		order_item_id = ".$cart_item_key." AND meta_key = '".$check_out_name."'";
                                                            		$wpdb->query( $query_checkout_date);
                                                            		$post = get_post($post_id);
                                                            		//print_r($post);*/
                                                            $title = $post->post_title;
                                                            print '
															<script type="text/javascript">
														alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected dates. Please reduce the quantity or remove it from your order.");
														window.history.back();
														//return;
														</script>';
                                                            exit;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    if (isset($booking_settings['booking_enable_time']) && $booking_settings['booking_enable_time'] == 'on') {
                                        if (array_key_exists($date_name, $booking)) {
                                            $start_date = date("Y-m-d", strtotime($booking[$date_name]));
                                        }
                                        if (array_key_exists($time_name, $booking)) {
                                            $time_slot = explode("-", $booking[$time_name]);
                                            $from_time = date("G:i", strtotime($time_slot[0]));
                                            $to_time = date("G:i", strtotime($time_slot[1]));
                                            $query_result = "SELECT available_booking,total_booking FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND from_time = '" . $from_time . "' AND to_time = '" . $to_time . "' AND post_id = " . $post_id . " AND total_booking > 0";
                                            //echo $query_result;
                                            $item_results_lockout = $wpdb->get_results($query_result);
                                            if (count($item_results_lockout) > 0) {
                                                $booking_available = $item_results_lockout[0]->available_booking;
                                                /*foreach ($existing_order_result as $ekey => $evalue)
                                                		{
                                                			$booking_id = $evalue->booking_id;
                                                			//print_r($evalue);
                                                			$query = "SELECT * FROM `".$wpdb->prefix."booking_history`
                                                				WHERE
                                                			id = $booking_id ";
                                                			$item_results = $wpdb->get_results( $query );
                                                			//print_r($item_results);
                                                			if(count($item_results) > 0)
                                                			{
                                                				$booking_ids[] = $booking_id;
                                                			}
                                                		}*/
                                                if ($order_key_exists == 'Y') {
                                                    if ($existing_quantity < $quantity) {
                                                        if ($quantity <= $booking_available) {
                                                            $qty = $quantity - $existing_quantity;
                                                            if ($to_time != "") {
                                                                $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $qty . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                                $wpdb->query($query);
                                                                $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' ";
                                                                $select_results = $wpdb->get_results($select);
                                                                foreach ($select_results as $k => $v) {
                                                                    $details[$post_id] = $v;
                                                                }
                                                            } else {
                                                                $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $qty . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                                $wpdb->query($query);
                                                                $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "'";
                                                                $select_results = $wpdb->get_results($select);
                                                                foreach ($select_results as $k => $v) {
                                                                    $details[$post_id] = $v;
                                                                }
                                                            }
                                                        } else {
                                                            $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                            $wpdb->query($query_date);
                                                            $wpdb->query($query_checkout_date);
                                                            $post = get_post($post_id);
                                                            //print_r($post);
                                                            $title = $post->post_title;
                                                            print '
																<script type="text/javascript">
																alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected date and time slot. Please reduce the quantity or remove it from your order."); 
																window.history.back();
																//return;
																</script>';
                                                            exit;
                                                        }
                                                    } elseif ($existing_quantity > $quantity) {
                                                        $qty = $existing_quantity - $quantity;
                                                        if ($to_time != "") {
                                                            $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking + " . $qty . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                            $wpdb->query($query);
                                                            $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' ";
                                                            $select_results = $wpdb->get_results($select);
                                                            foreach ($select_results as $k => $v) {
                                                                $details[$post_id] = $v;
                                                            }
                                                        } else {
                                                            $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking + " . $qty . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                            $wpdb->query($query);
                                                            $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "'";
                                                            $select_results = $wpdb->get_results($select);
                                                            foreach ($select_results as $k => $v) {
                                                                $details[$post_id] = $v;
                                                            }
                                                        }
                                                    }
                                                } else {
                                                    if ($order_key_exists == 'N') {
                                                        if ($quantity <= $booking_available) {
                                                            if ($to_time != "") {
                                                                $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $quantity . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                                //echo $query;exit;
                                                                $wpdb->query($query);
                                                                $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' ";
                                                                $select_results = $wpdb->get_results($select);
                                                                foreach ($select_results as $k => $v) {
                                                                    $details[$post_id] = $v;
                                                                }
                                                            } else {
                                                                $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $quantity . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                                $wpdb->query($query);
                                                                $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "'";
                                                                $select_results = $wpdb->get_results($select);
                                                                foreach ($select_results as $k => $v) {
                                                                    $details[$post_id] = $v;
                                                                }
                                                            }
                                                        } else {
                                                            $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                            $wpdb->query($query_date);
                                                            $wpdb->query($query_checkout_date);
                                                            $post = get_post($post_id);
                                                            //print_r($post);
                                                            $title = $post->post_title;
                                                            print '
															<script type="text/javascript">
															alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected date and time slot. Please reduce the quantity or remove it from your order."); 
															window.history.back();
															//return;
														</script>';
                                                            exit;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        $start_date = date("Y-m-d", strtotime($booking[$date_name]));
                                        $query_result = "SELECT available_booking,total_booking FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND post_id = " . $post_id . " AND total_booking > 0";
                                        //echo $query_result;
                                        $item_results_lockout = $wpdb->get_results($query_result);
                                        if (count($item_results_lockout) > 0) {
                                            $booking_available = $item_results_lockout[0]->available_booking;
                                            if ($order_key_exists == 'Y') {
                                                if ($existing_quantity < $quantity) {
                                                    if ($quantity <= $booking_available) {
                                                        $qty = $quantity - $existing_quantity;
                                                        $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $qty . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                        $wpdb->query($query);
                                                    } else {
                                                        $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                        $wpdb->query($query_date);
                                                        $post = get_post($post_id);
                                                        //print_r($post);
                                                        $title = $post->post_title;
                                                        print '
															<script type="text/javascript">
															alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected date. Please reduce the quantity or remove it from your order."); 
															window.history.back();
															//return;
															</script>';
                                                        exit;
                                                    }
                                                } else {
                                                    if ($existing_quantity > $quantity) {
                                                        $qty = $existing_quantity - $quantity;
                                                        $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking + " . $qty . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                        $wpdb->query($query);
                                                    }
                                                }
                                            } else {
                                                if ($order_key_exists == 'N') {
                                                    if ($quantity <= $booking_available) {
                                                        $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $quantity . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $start_date . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                        $wpdb->query($query);
                                                    } else {
                                                        $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                        $wpdb->query($query_date);
                                                        $post = get_post($post_id);
                                                        //print_r($post);
                                                        $title = $post->post_title;
                                                        print '
															<script type="text/javascript">
															alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected date. Please reduce the quantity or remove it from your order."); 
															window.history.back();
															//return;
														</script>';
                                                        exit;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                //
                                //echo $booking['wapbk_admin_hidden_date'];exit;
                                if (isset($_POST['wapbk_admin_hidden_date_' . $cart_item_key])) {
                                    $hidden_date = $_POST['wapbk_admin_hidden_date_' . $cart_item_key];
                                    $date_query = date('Y-m-d', strtotime($hidden_date));
                                    if (isset($_POST['wapbk_admin_hidden_date_checkout_' . $cart_item_key])) {
                                        $date_checkout = $_POST['wapbk_admin_hidden_date_checkout_' . $cart_item_key];
                                        $date_checkout_query = date('Y-m-d', strtotime($date_checkout));
                                    }
                                    //echo $_POST['wapbk_admin_hidden_date_'.$cart_item_key];
                                    //echo $_POST['wapbk_admin_hidden_date_checkout_'.$cart_item_key];exit;
                                    //echo "_POST['wapbk_admin_hidden_date_checkout_'".$cart_item_key."]";exit;
                                    if (isset($booking_settings['booking_enable_multiple_day']) && $booking_settings['booking_enable_multiple_day'] == 'on') {
                                        $query_result = "SELECT COUNT(*) as bookings_done FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND end_date = '" . $date_checkout_query . "' AND post_id = " . $post_id;
                                        //echo $query_result;
                                        $item_results_lockout = $wpdb->get_results($query_result);
                                        $lockout = "";
                                        if (isset($booking_settings['booking_date_lockout'])) {
                                            $lockout = $booking_settings['booking_date_lockout'];
                                        }
                                        if (count($item_results_lockout) > 0) {
                                            $booking_available = $lockout - $item_results_lockout[0]->bookings_done;
                                            if ($quantity <= $booking_available) {
                                                for ($i = $existing_quantity; $i <= $quantity; $i++) {
                                                    $query = "INSERT INTO `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t(post_id,weekday,start_date,end_date,from_time,to_time,total_booking,available_booking)\n\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $post_id . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $date_query . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $date_checkout_query . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'0',\n\t\t\t\t\t\t\t\t\t\t\t\t\t'0' )";
                                                    $wpdb->query($query);
                                                    $new_booking_id = mysql_insert_id();
                                                    $order_query = "INSERT INTO `" . $wpdb->prefix . "booking_order_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t(order_id,booking_id)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $order_id . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'" . $new_booking_id . "' )";
                                                    $wpdb->query($order_query);
                                                }
                                            } else {
                                                if ($lockout != 0) {
                                                    $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta`\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                    $wpdb->query($query_date);
                                                    //$wpdb->query( $query_checkout_date);
                                                    $post = get_post($post_id);
                                                    //print_r($post);
                                                    $title = $post->post_title;
                                                    print '
															<script type="text/javascript">
													alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected dates. Please reduce the quantity or remove it from your order.");
													window.history.back();
													//return;
													</script>';
                                                    exit;
                                                }
                                            }
                                        }
                                    } else {
                                        if (isset($booking[$time_name]) && $booking[$time_name] != "") {
                                            //echo $item_name;
                                            //print_r($booking);exit;
                                            $time_slot = explode("-", $booking[$time_name]);
                                            $from_time = date("G:i", strtotime($time_slot[0]));
                                            if (isset($time_slot[1])) {
                                                $to_time = date("G:i", strtotime($time_slot[1]));
                                            } else {
                                                $to_time = '';
                                            }
                                            $query_result = "SELECT available_booking,total_booking FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND from_time = '" . $from_time . "' AND to_time = '" . $to_time . "' AND post_id = " . $post_id . " AND total_booking > 0";
                                            //echo $query_result;
                                            $item_results_lockout = $wpdb->get_results($query_result);
                                            if (count($item_results_lockout) > 0) {
                                                $booking_available = $item_results_lockout[0]->available_booking;
                                                if ($quantity <= $booking_available) {
                                                    if ($to_time != "") {
                                                        $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $quantity . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                        $wpdb->query($query);
                                                        $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $to_time . "' ";
                                                        $select_results = $wpdb->get_results($select);
                                                        foreach ($select_results as $k => $v) {
                                                            $details[$post_id] = $v;
                                                        }
                                                    } else {
                                                        $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $quantity . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                        $wpdb->query($query);
                                                        $select = "SELECT * FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $from_time . "'";
                                                        $select_results = $wpdb->get_results($select);
                                                        foreach ($select_results as $k => $v) {
                                                            $details[$post_id] = $v;
                                                        }
                                                    }
                                                } else {
                                                    $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                    $wpdb->query($query_date);
                                                    $post = get_post($post_id);
                                                    //print_r($post);
                                                    $title = $post->post_title;
                                                    print '
															<script type="text/javascript">
															alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected date and time slot. Please reduce the quantity or remove it from your order."); 
															window.history.back();
															//return;
														</script>';
                                                    exit;
                                                }
                                            }
                                        } else {
                                            //$start_date = date("Y-m-d",strtotime($booking[$date_name]));
                                            $query_result = "SELECT available_booking,total_booking FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND post_id = " . $post_id . " AND total_booking > 0";
                                            //echo $query_result;exit;
                                            $item_results_lockout = $wpdb->get_results($query_result);
                                            $booking_available = $item_results_lockout[0]->available_booking;
                                            if ($quantity <= $booking_available) {
                                                $query = "UPDATE `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\t\tSET available_booking = available_booking - " . $quantity . "\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_booking > 0";
                                                $wpdb->query($query);
                                            } else {
                                                $query_date = "DELETE FROM `" . $wpdb->prefix . "woocommerce_order_itemmeta` \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torder_item_id = " . $cart_item_key . " AND meta_key = 'Name'";
                                                $wpdb->query($query_date);
                                                $post = get_post($post_id);
                                                //print_r($post);
                                                $title = $post->post_title;
                                                print '
																<script type="text/javascript">
															alert("The item you changed the quantity for ' . $title . ', exceeds the quantity available for your selected date. Please reduce the quantity or remove it from your order."); 
															window.history.back();
															//return;
														</script>';
                                                exit;
                                            }
                                        }
                                    }
                                    if (isset($booking[$time_name]) && $booking[$time_name] != "") {
                                        if ($query_to_time != '') {
                                            $order_select_query = "SELECT id FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $query_from_time . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\tto_time = '" . $query_to_time . "' ";
                                            $order_results = $wpdb->get_results($order_select_query);
                                        } else {
                                            $order_select_query = "SELECT id FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\tfrom_time = '" . $query_from_time . "'";
                                            $order_results = $wpdb->get_results($order_select_query);
                                        }
                                    } else {
                                        $order_select_query = "SELECT id FROM `" . $wpdb->prefix . "booking_history`\n\t\t\t\t\t\t\t\t\t\t\tWHERE post_id = '" . $post_id . "' AND\n\t\t\t\t\t\t\t\t\t\t\t\tstart_date = '" . $date_query . "'";
                                        $order_results = $wpdb->get_results($order_select_query);
                                    }
                                    $j = 0;
                                    foreach ($order_results as $k => $v) {
                                        $booking_id = $order_results[$j]->id;
                                        $order_query = "INSERT INTO `" . $wpdb->prefix . "booking_order_history`\n\t\t\t\t\t\t\t\t\t\t\t(order_id,booking_id)\n\t\t\t\t\t\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t\t\t\t\t'" . $order_id . "',\n\t\t\t\t\t\t\t\t\t\t\t'" . $booking_id . "' )";
                                        $wpdb->query($order_query);
                                        $j++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //exit;
        }
 /**
  * If the subscription being generated is synced, set the syncing related meta data correctly.
  *
  * @since 1.5
  */
 public static function prefill_order_item_meta($item, $item_id)
 {
     $product_id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
     if (self::is_product_synced($product_id)) {
         $order_id = $_POST['order_id'];
         // If the date the subscription is being added is not the sync date, make sure the line total is only equal to the sign up fee (or $0 if no sign up fee)
         if (!self::is_today(self::calculate_first_payment_date($product_id, 'timestamp')) && !self::is_product_prorated(get_product($product_id))) {
             $line_total_keys = array('line_subtotal', 'line_total');
             foreach ($line_total_keys as $line_total_key) {
                 $item[$line_total_key] = WC_Subscriptions_Product::get_sign_up_fee($product_id);
                 woocommerce_update_order_item_meta($item_id, '_' . $line_total_key, $item[$line_total_key]);
             }
         }
         update_post_meta($order_id, '_order_contains_synced_subscription', 'true');
     }
     return $item;
 }
 /**
  * Takes a subscription key and array of subscription details and updates the users subscription details accordingly.
  *
  * @uses wp_parse_args To allow only part of a subscription's details to be updated, like status.
  * @param string $subscription_key A subscription key of the form created by @see self::get_subscription_key()
  * @param array $new_subscription_details An array of arrays with a subscription key and corresponding 'detail' => 'value' pair. Can alter any of these details:
  *        'start_date'          The date the subscription was activated
  *        'expiry_date'         The date the subscription expires or expired, false if the subscription will never expire
  *        'failed_payments'     The date the subscription's trial expires or expired, false if the subscription has no trial period
  *        'end_date'            The date the subscription ended, false if the subscription has not yet ended
  *        'status'              Subscription status can be: cancelled, active, expired or failed
  *        'completed_payments'  An array of MySQL formatted dates for all payments that have been made on the subscription
  *        'failed_payments'     An integer representing a count of failed payments
  *        'suspension_count'    An integer representing a count of the number of times the subscription has been suspended for this billing period
  * @since 1.4
  */
 public static function update_subscription($subscription_key, $new_subscription_details)
 {
     $subscription = self::get_subscription($subscription_key);
     $item_id = WC_Subscriptions_Order::get_item_id_by_subscription_key($subscription_key);
     $item = WC_Subscriptions_Order::get_item_by_id($item_id);
     if (isset($new_subscription_details['status']) && 'deleted' == $new_subscription_details['status']) {
         woocommerce_delete_order_item($item_id);
     } else {
         $subscription_meta = array('start_date', 'expiry_date', 'trial_expiry_date', 'end_date', 'status', 'failed_payments', 'completed_payments', 'suspension_count');
         foreach ($subscription_meta as $meta_key) {
             if (isset($new_subscription_details[$meta_key]) && $new_subscription_details[$meta_key] != $subscription[$meta_key]) {
                 $subscription[$meta_key] = $new_subscription_details[$meta_key];
                 woocommerce_update_order_item_meta($item_id, '_subscription_' . $meta_key, $new_subscription_details[$meta_key]);
             }
         }
     }
     do_action('updated_users_subscription', $subscription_key, $new_subscription_details);
     return $subscription;
 }
Exemplo n.º 5
0
/**
 * Save the order data meta box.
 *
 * @access public
 * @param mixed $post_id
 * @param mixed $post
 * @return void
 */
function woocommerce_process_shop_order_meta($post_id, $post)
{
    global $wpdb, $woocommerce, $woocommerce_errors;
    // Add key
    add_post_meta($post_id, '_order_key', uniqid('order_'), true);
    // Update post data
    update_post_meta($post_id, '_billing_first_name', woocommerce_clean($_POST['_billing_first_name']));
    update_post_meta($post_id, '_billing_last_name', woocommerce_clean($_POST['_billing_last_name']));
    update_post_meta($post_id, '_billing_company', woocommerce_clean($_POST['_billing_company']));
    update_post_meta($post_id, '_billing_address_1', woocommerce_clean($_POST['_billing_address_1']));
    update_post_meta($post_id, '_billing_address_2', woocommerce_clean($_POST['_billing_address_2']));
    update_post_meta($post_id, '_billing_city', woocommerce_clean($_POST['_billing_city']));
    update_post_meta($post_id, '_billing_postcode', woocommerce_clean($_POST['_billing_postcode']));
    update_post_meta($post_id, '_billing_country', woocommerce_clean($_POST['_billing_country']));
    update_post_meta($post_id, '_billing_state', woocommerce_clean($_POST['_billing_state']));
    update_post_meta($post_id, '_billing_email', woocommerce_clean($_POST['_billing_email']));
    update_post_meta($post_id, '_billing_phone', woocommerce_clean($_POST['_billing_phone']));
    update_post_meta($post_id, '_shipping_first_name', woocommerce_clean($_POST['_shipping_first_name']));
    update_post_meta($post_id, '_shipping_last_name', woocommerce_clean($_POST['_shipping_last_name']));
    update_post_meta($post_id, '_shipping_company', woocommerce_clean($_POST['_shipping_company']));
    update_post_meta($post_id, '_shipping_address_1', woocommerce_clean($_POST['_shipping_address_1']));
    update_post_meta($post_id, '_shipping_address_2', woocommerce_clean($_POST['_shipping_address_2']));
    update_post_meta($post_id, '_shipping_city', woocommerce_clean($_POST['_shipping_city']));
    update_post_meta($post_id, '_shipping_postcode', woocommerce_clean($_POST['_shipping_postcode']));
    update_post_meta($post_id, '_shipping_country', woocommerce_clean($_POST['_shipping_country']));
    update_post_meta($post_id, '_shipping_state', woocommerce_clean($_POST['_shipping_state']));
    update_post_meta($post_id, '_order_shipping', woocommerce_clean($_POST['_order_shipping']));
    update_post_meta($post_id, '_cart_discount', woocommerce_clean($_POST['_cart_discount']));
    update_post_meta($post_id, '_order_discount', woocommerce_clean($_POST['_order_discount']));
    update_post_meta($post_id, '_order_total', woocommerce_clean($_POST['_order_total']));
    update_post_meta($post_id, '_customer_user', absint($_POST['customer_user']));
    if (isset($_POST['_order_tax'])) {
        update_post_meta($post_id, '_order_tax', woocommerce_clean($_POST['_order_tax']));
    }
    if (isset($_POST['_order_shipping_tax'])) {
        update_post_meta($post_id, '_order_shipping_tax', woocommerce_clean($_POST['_order_shipping_tax']));
    }
    // Shipping method handling
    if (get_post_meta($post_id, '_shipping_method', true) !== stripslashes($_POST['_shipping_method'])) {
        $shipping_method = woocommerce_clean($_POST['_shipping_method']);
        update_post_meta($post_id, '_shipping_method', $shipping_method);
    }
    if (get_post_meta($post_id, '_shipping_method_title', true) !== stripslashes($_POST['_shipping_method_title'])) {
        $shipping_method_title = woocommerce_clean($_POST['_shipping_method_title']);
        if (!$shipping_method_title) {
            $shipping_method = esc_attr($_POST['_shipping_method']);
            $methods = $woocommerce->shipping->load_shipping_methods();
            if (isset($methods) && isset($methods[$shipping_method])) {
                $shipping_method_title = $methods[$shipping_method]->get_title();
            }
        }
        update_post_meta($post_id, '_shipping_method_title', $shipping_method_title);
    }
    // Payment method handling
    if (get_post_meta($post_id, '_payment_method', true) !== stripslashes($_POST['_payment_method'])) {
        $methods = $woocommerce->payment_gateways->payment_gateways();
        $payment_method = woocommerce_clean($_POST['_payment_method']);
        $payment_method_title = $payment_method;
        if (isset($methods) && isset($methods[$payment_method])) {
            $payment_method_title = $methods[$payment_method]->get_title();
        }
        update_post_meta($post_id, '_payment_method', $payment_method);
        update_post_meta($post_id, '_payment_method_title', $payment_method_title);
    }
    // Update date
    if (empty($_POST['order_date'])) {
        $date = current_time('timestamp');
    } else {
        $date = strtotime($_POST['order_date'] . ' ' . (int) $_POST['order_date_hour'] . ':' . (int) $_POST['order_date_minute'] . ':00');
    }
    $date = date_i18n('Y-m-d H:i:s', $date);
    $wpdb->query($wpdb->prepare("UPDATE {$wpdb->posts} SET post_date = %s, post_date_gmt = %s WHERE ID = %s", $date, get_gmt_from_date($date), $post_id));
    // Tax rows
    if (isset($_POST['order_taxes_id'])) {
        $get_values = array('order_taxes_id', 'order_taxes_rate_id', 'order_taxes_amount', 'order_taxes_shipping_amount');
        foreach ($get_values as $value) {
            ${$value} = isset($_POST[$value]) ? $_POST[$value] : array();
        }
        foreach ($order_taxes_id as $item_id) {
            $item_id = absint($item_id);
            $rate_id = absint($order_taxes_rate_id[$item_id]);
            if ($rate_id) {
                $rate = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $rate_id));
                $label = $rate->tax_rate_name ? $rate->tax_rate_name : $woocommerce->countries->tax_or_vat();
                $compound = $rate->tax_rate_compound ? 1 : 0;
                $code = array();
                $code[] = $rate->tax_rate_country;
                $code[] = $rate->tax_rate_state;
                $code[] = $rate->tax_rate_name ? $rate->tax_rate_name : 'TAX';
                $code[] = absint($rate->tax_rate_priority);
                $code = strtoupper(implode('-', array_filter($code)));
            } else {
                $code = '';
                $label = $woocommerce->countries->tax_or_vat();
            }
            $wpdb->update($wpdb->prefix . "woocommerce_order_items", array('order_item_name' => woocommerce_clean($code)), array('order_item_id' => $item_id), array('%s'), array('%d'));
            woocommerce_update_order_item_meta($item_id, 'rate_id', $rate_id);
            woocommerce_update_order_item_meta($item_id, 'label', $label);
            woocommerce_update_order_item_meta($item_id, 'compound', $compound);
            if (isset($order_taxes_amount[$item_id])) {
                woocommerce_update_order_item_meta($item_id, 'tax_amount', woocommerce_clean($order_taxes_amount[$item_id]));
            }
            if (isset($order_taxes_shipping_amount[$item_id])) {
                woocommerce_update_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($order_taxes_shipping_amount[$item_id]));
            }
        }
    }
    // Order items + fees
    if (isset($_POST['order_item_id'])) {
        $get_values = array('order_item_id', 'order_item_name', 'order_item_qty', 'line_subtotal', 'line_subtotal_tax', 'line_total', 'line_tax', 'order_item_tax_class');
        foreach ($get_values as $value) {
            ${$value} = isset($_POST[$value]) ? $_POST[$value] : array();
        }
        foreach ($order_item_id as $item_id) {
            $item_id = absint($item_id);
            if (isset($order_item_name[$item_id])) {
                $wpdb->update($wpdb->prefix . "woocommerce_order_items", array('order_item_name' => woocommerce_clean($order_item_name[$item_id])), array('order_item_id' => $item_id), array('%s'), array('%d'));
            }
            if (isset($order_item_qty[$item_id])) {
                woocommerce_update_order_item_meta($item_id, '_qty', apply_filters('woocommerce_stock_amount', $order_item_qty[$item_id]));
            }
            if (isset($item_tax_class[$item_id])) {
                woocommerce_update_order_item_meta($item_id, '_tax_class', woocommerce_clean($item_tax_class[$item_id]));
            }
            if (isset($line_subtotal[$item_id])) {
                woocommerce_update_order_item_meta($item_id, '_line_subtotal', woocommerce_clean($line_subtotal[$item_id]));
            }
            if (isset($line_subtotal_tax[$item_id])) {
                woocommerce_update_order_item_meta($item_id, '_line_subtotal_tax', woocommerce_clean($line_subtotal_tax[$item_id]));
            }
            if (isset($line_total[$item_id])) {
                woocommerce_update_order_item_meta($item_id, '_line_total', woocommerce_clean($line_total[$item_id]));
            }
            if (isset($line_tax[$item_id])) {
                woocommerce_update_order_item_meta($item_id, '_line_tax', woocommerce_clean($line_tax[$item_id]));
            }
            // Clear meta cache
            wp_cache_delete($item_id, 'order_item_meta');
        }
    }
    // Save meta
    $meta_keys = isset($_POST['meta_key']) ? $_POST['meta_key'] : array();
    $meta_values = isset($_POST['meta_value']) ? $_POST['meta_value'] : array();
    foreach ($meta_keys as $id => $meta_key) {
        $meta_value = empty($meta_values[$id]) && !is_numeric($meta_values[$id]) ? '' : $meta_values[$id];
        $wpdb->update($wpdb->prefix . "woocommerce_order_itemmeta", array('meta_key' => $meta_key, 'meta_value' => $meta_value), array('meta_id' => $id), array('%s', '%s'), array('%d'));
    }
    // Order data saved, now get it so we can manipulate status
    $order = new WC_Order($post_id);
    // Order status
    $order->update_status($_POST['order_status']);
    // Handle button actions
    if (!empty($_POST['wc_order_action'])) {
        $action = woocommerce_clean($_POST['wc_order_action']);
        if (strstr($action, 'send_email_')) {
            do_action('woocommerce_before_resend_order_emails', $order);
            $mailer = $woocommerce->mailer();
            $email_to_send = str_replace('send_email_', '', $action);
            $mails = $mailer->get_emails();
            if (!empty($mails)) {
                foreach ($mails as $mail) {
                    if ($mail->id == $email_to_send) {
                        $mail->trigger($order->id);
                    }
                }
            }
            do_action('woocommerce_after_resend_order_email', $order, $email_to_send);
        } else {
            do_action('woocommerce_order_action_' . sanitize_title($action), $order);
        }
    }
    delete_transient('woocommerce_processing_order_count');
}
 /**
  * When a new order is inserted, add subscriptions related order meta.
  *
  * @since 1.0
  */
 public static function add_order_meta($order_id, $posted)
 {
     global $woocommerce;
     if (!WC_Subscriptions_Cart::cart_contains_subscription_renewal('child') && WC_Subscriptions_Order::order_contains_subscription($order_id)) {
         // This works because the 'woocommerce_add_order_item_meta' runs before the 'woocommerce_checkout_update_order_meta' hook
         // Set the recurring totals so totals display correctly on order page
         update_post_meta($order_id, '_order_recurring_discount_cart', WC_Subscriptions_Cart::get_recurring_discount_cart());
         update_post_meta($order_id, '_order_recurring_discount_cart_tax', WC_Subscriptions_Cart::get_recurring_discount_cart_tax());
         update_post_meta($order_id, '_order_recurring_discount_total', WC_Subscriptions_Cart::get_recurring_discount_total());
         update_post_meta($order_id, '_order_recurring_shipping_tax_total', WC_Subscriptions_Cart::get_recurring_shipping_tax_total());
         update_post_meta($order_id, '_order_recurring_shipping_total', WC_Subscriptions_Cart::get_recurring_shipping_total());
         update_post_meta($order_id, '_order_recurring_tax_total', WC_Subscriptions_Cart::get_recurring_total_tax());
         update_post_meta($order_id, '_order_recurring_total', WC_Subscriptions_Cart::get_recurring_total());
         // Set the recurring payment method - it starts out the same as the original by may change later
         update_post_meta($order_id, '_recurring_payment_method', get_post_meta($order_id, '_payment_method', true));
         update_post_meta($order_id, '_recurring_payment_method_title', get_post_meta($order_id, '_payment_method_title', true));
         $order = new WC_Order($order_id);
         $order_fees = $order->get_fees();
         // the fee order items have already been set, we just need to to add the recurring total meta
         $cart_fees = $woocommerce->cart->get_fees();
         foreach ($order->get_fees() as $item_id => $order_fee) {
             // Find the matching fee in the cart
             foreach ($cart_fees as $fee_index => $cart_fee) {
                 if (sanitize_title($order_fee['name']) == $cart_fee->id) {
                     woocommerce_add_order_item_meta($item_id, '_recurring_line_total', wc_format_decimal($cart_fee->recurring_amount));
                     woocommerce_add_order_item_meta($item_id, '_recurring_line_tax', wc_format_decimal($cart_fee->recurring_tax));
                     unset($cart_fees[$fee_index]);
                     break;
                 }
             }
         }
         // Get recurring taxes into same format as _order_taxes
         $order_recurring_taxes = array();
         foreach (WC_Subscriptions_Cart::get_recurring_taxes() as $tax_key => $tax_amount) {
             $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => WC_Tax::get_rate_code($tax_key), 'order_item_type' => 'recurring_tax'));
             if ($item_id) {
                 wc_add_order_item_meta($item_id, 'rate_id', $tax_key);
                 wc_add_order_item_meta($item_id, 'label', WC_Tax::get_rate_label($tax_key));
                 wc_add_order_item_meta($item_id, 'compound', absint(WC_Tax::is_compound($tax_key) ? 1 : 0));
                 wc_add_order_item_meta($item_id, 'tax_amount', wc_format_decimal(isset(WC()->cart->recurring_taxes[$tax_key]) ? WC()->cart->recurring_taxes[$tax_key] : 0));
                 wc_add_order_item_meta($item_id, 'shipping_tax_amount', wc_format_decimal(isset(WC()->cart->recurring_shipping_taxes[$tax_key]) ? WC()->cart->recurring_shipping_taxes[$tax_key] : 0));
             }
         }
         $payment_gateways = $woocommerce->payment_gateways->payment_gateways();
         if ('yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_turn_off_automatic_payments', 'no')) {
             update_post_meta($order_id, '_wcs_requires_manual_renewal', 'true');
         } elseif (isset($payment_gateways[$posted['payment_method']]) && !$payment_gateways[$posted['payment_method']]->supports('subscriptions')) {
             update_post_meta($order_id, '_wcs_requires_manual_renewal', 'true');
         }
         $cart_item = WC_Subscriptions_Cart::cart_contains_subscription_renewal();
         if (isset($cart_item['subscription_renewal']) && 'parent' == $cart_item['subscription_renewal']['role']) {
             update_post_meta($order_id, '_original_order', $cart_item['subscription_renewal']['original_order']);
         }
         // WC 2.1+
         if (!WC_Subscriptions::is_woocommerce_pre('2.1')) {
             // Recurring coupons
             if ($applied_coupons = $woocommerce->cart->get_coupons()) {
                 foreach ($applied_coupons as $code => $coupon) {
                     if (!isset($woocommerce->cart->recurring_coupon_discount_amounts[$code])) {
                         continue;
                     }
                     $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $code, 'order_item_type' => 'recurring_coupon'));
                     // Add line item meta
                     if ($item_id) {
                         woocommerce_add_order_item_meta($item_id, 'discount_amount', isset($woocommerce->cart->recurring_coupon_discount_amounts[$code]) ? $woocommerce->cart->recurring_coupon_discount_amounts[$code] : 0);
                     }
                 }
             }
             // Add recurring shipping order items
             if (WC_Subscriptions_Cart::cart_contains_subscriptions_needing_shipping()) {
                 $packages = $woocommerce->shipping->get_packages();
                 $checkout = $woocommerce->checkout();
                 foreach ($packages as $i => $package) {
                     if (isset($package['rates'][$checkout->shipping_methods[$i]])) {
                         $method = $package['rates'][$checkout->shipping_methods[$i]];
                         $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $method->label, 'order_item_type' => 'recurring_shipping'));
                         if ($item_id) {
                             woocommerce_add_order_item_meta($item_id, 'method_id', $method->id);
                             woocommerce_add_order_item_meta($item_id, 'cost', WC_Subscriptions::format_total($method->cost));
                             woocommerce_add_order_item_meta($item_id, 'taxes', array_map('wc_format_decimal', $method->taxes));
                             do_action('woocommerce_subscriptions_add_recurring_shipping_order_item', $order_id, $item_id, $i);
                         }
                     }
                 }
             }
             // Remove shipping on original order if it was added but is not required
             if (!WC_Subscriptions_Cart::charge_shipping_up_front()) {
                 foreach ($order->get_shipping_methods() as $order_item_id => $shipping_method) {
                     woocommerce_update_order_item_meta($order_item_id, 'cost', WC_Subscriptions::format_total(0));
                 }
             }
         } else {
             update_post_meta($order_id, '_recurring_shipping_method', get_post_meta($order_id, '_shipping_method', true), true);
             update_post_meta($order_id, '_recurring_shipping_method_title', get_post_meta($order_id, '_shipping_method_title', true), true);
         }
     }
 }
 /**
  * Add subscription related order item meta when a subscription product is added as an item to an order via Ajax.
  *
  * @param item_id int An order_item_id as returned by the insert statement of @see woocommerce_add_order_item()
  * @since 1.2.5
  * @version 1.4
  * @return void
  */
 public static function prefill_order_item_meta($item, $item_id)
 {
     $order_id = $_POST['order_id'];
     $product_id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
     if ($item_id && WC_Subscriptions_Product::is_subscription($product_id)) {
         $order = new WC_Order($order_id);
         $_product = get_product($product_id);
         $recurring_amount = $_product->get_price_excluding_tax();
         $sign_up_fee = $_product->get_sign_up_fee_excluding_tax();
         $free_trial_length = WC_Subscriptions_Product::get_trial_length($product_id);
         woocommerce_add_order_item_meta($item_id, '_subscription_period', WC_Subscriptions_Product::get_period($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_interval', WC_Subscriptions_Product::get_interval($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_length', WC_Subscriptions_Product::get_length($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_trial_length', $free_trial_length);
         woocommerce_add_order_item_meta($item_id, '_subscription_trial_period', WC_Subscriptions_Product::get_trial_period($product_id));
         woocommerce_add_order_item_meta($item_id, '_subscription_recurring_amount', $recurring_amount);
         woocommerce_add_order_item_meta($item_id, '_subscription_sign_up_fee', $sign_up_fee);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_total', $recurring_amount);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_tax', 0);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_subtotal', $recurring_amount);
         woocommerce_add_order_item_meta($item_id, '_recurring_line_subtotal_tax', 0);
         WC_Subscriptions_Manager::create_pending_subscription_for_order($order_id, $item['product_id']);
         switch ($order->status) {
             case 'completed':
             case 'processing':
                 woocommerce_update_order_item_meta($item_id, '_subscription_status', 'active');
                 break;
             case 'on-hold':
                 woocommerce_update_order_item_meta($item_id, '_subscription_status', 'on-hold');
                 break;
             case 'failed':
             case 'cancelled':
                 woocommerce_add_order_item_meta($item_id, '_subscription_status', 'cancelled');
                 break;
         }
         // We need to override the line totals to $0 when there is a free trial
         if ($free_trial_length > 0 || $sign_up_fee > 0) {
             $line_total_keys = array('line_subtotal', 'line_total');
             // Make sure sign up fees are included in the total (or $0 if no sign up fee and a free trial)
             foreach ($line_total_keys as $line_total_key) {
                 $item[$line_total_key] = $sign_up_fee;
             }
             // If there is no free trial, make sure line totals include sign up fee and recurring fees
             if (0 == $free_trial_length) {
                 foreach ($line_total_keys as $line_total_key) {
                     $item[$line_total_key] += $recurring_amount;
                 }
             }
             foreach ($line_total_keys as $line_total_key) {
                 $item[$line_total_key] = WC_Subscriptions::format_total($item[$line_total_key], 2);
             }
         } else {
             $item['line_subtotal'] = $recurring_amount;
             $item['line_total'] = $recurring_amount;
         }
         woocommerce_update_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
         woocommerce_update_order_item_meta($item_id, '_line_total', $item['line_total']);
     }
     return $item;
 }
Exemplo n.º 8
0
 function bp_course_disable_access($order_id)
 {
     $order = new WC_Order($order_id);
     $items = $order->get_items();
     $user_id = $order->user_id;
     foreach ($items as $item) {
         $product_id = $item['product_id'];
         $subscribed = get_post_meta($product_id, 'vibe_subscription', true);
         $courses = vibe_sanitize(get_post_meta($product_id, 'vibe_courses', false));
         if (isset($courses) && is_array($courses)) {
             foreach ($courses as $course) {
                 delete_post_meta($course, $user_id);
                 delete_user_meta($user_id, $course);
                 $group_id = get_post_meta($course, 'vibe_group', true);
                 if (isset($group_id) && function_exists('groups_remove_member')) {
                     groups_remove_member($user_id, $group_id);
                 } else {
                     $group_id = '';
                 }
                 $instructors = apply_filters('wplms_course_instructors', get_post_field('post_author', $course, 'raw'), $course);
                 if (is_array($instructors)) {
                     foreach ($instructors as $instructor) {
                         woocommerce_update_order_item_meta($item_id, 'commission' . $instructor, 0);
                         //Nulls the commission
                     }
                 }
                 do_action('wplms_course_unsubscribe', $course_id, $user_id, $group_id);
             }
         }
     }
 }
 /**
  * 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 and certain order items are not set, like taxes, shipping as they need to be set in teh calling function, like @see WC_Subscriptions_Checkout::filter_woocommerce_create_order(). 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.', 'woocommerce-subscriptions'));
         $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', 'woocommerce-subscriptions'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'woocommerce-subscriptions'))), '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);
     $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);
     $failed_payment_multiplier = 1;
     if (false == $args['checkout_renewal']) {
         // 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);
         }
         // 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);
         // Set shipping for orders created with WC 2.0.n (or when we are using WC 2.0.n)
         if (WC_Subscriptions::is_woocommerce_pre_2_1() || isset($original_order->recurring_shipping_method)) {
             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);
             // Also set recurring shipping as it's a parent renewal order
             if ('parent' == $args['new_order_role']) {
                 update_post_meta($renewal_order_id, '_recurring_shipping_method', $original_order->recurring_shipping_method);
                 update_post_meta($renewal_order_id, '_recurring_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) {
             $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']);
                 }
             }
         }
         // Set up shipping items on renewal order
         $recurring_shipping_items = WC_Subscriptions_Order::get_recurring_shipping_methods($original_order);
         foreach ($recurring_shipping_items as $index => $recurring_shipping_item) {
             $item_ids = array();
             $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_shipping_item['name'], 'order_item_type' => 'shipping'));
             // Also set recurring shipping as it's a parent renewal order
             if ('parent' == $args['new_order_role']) {
                 $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_shipping_item['name'], 'order_item_type' => 'recurring_shipping'));
             }
             // Add shipping item meta
             foreach ($item_ids as $item_id) {
                 woocommerce_add_order_item_meta($item_id, 'method_id', $recurring_shipping_item['method_id']);
                 woocommerce_add_order_item_meta($item_id, 'cost', woocommerce_clean($failed_payment_multiplier * $recurring_shipping_item['cost']));
             }
         }
     }
     // 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']);
     if (true === $args['checkout_renewal']) {
         $cart_items = $woocommerce->cart->get_cart();
     }
     foreach ($order_items as $item_index => $order_item) {
         if ('child' == $args['new_order_role']) {
             $renewal_order_item_name = sprintf(__('Renewal of "%s" purchased in Order %s', 'woocommerce-subscriptions'), $order_item['name'], $original_order->get_order_number());
         } else {
             $renewal_order_item_name = $order_item['name'];
         }
         $renewal_order_item_name = apply_filters('woocommerce_subscriptions_renewal_order_item_name', $renewal_order_item_name, $order_item, $original_order);
         // 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'));
         if (true === $args['checkout_renewal']) {
             $cart_item = array();
             foreach ($cart_items as $item) {
                 if ($item['product_id'] == $order_item['product_id'] && (empty($order_item['variation_id']) || $item['variation_id'] == $order_item['variation_id'])) {
                     $cart_item = $item;
                 }
             }
             if (!empty($cart_item)) {
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_total', woocommerce_format_decimal($cart_item['line_total']));
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_tax', woocommerce_format_decimal($cart_item['line_tax']));
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_subtotal', woocommerce_format_decimal($cart_item['line_subtotal']));
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_subtotal_tax', woocommerce_format_decimal($cart_item['line_subtotal_tax']));
                 if (is_object($cart_item['data'])) {
                     woocommerce_update_order_item_meta($recurring_item_id, '_tax_class', $cart_item['data']->get_tax_class());
                 }
             }
             $cart_items = $woocommerce->cart->get_cart();
         }
         $item_meta = new WC_Order_Item_Meta($order_item['item_meta']);
         // 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];
             if (false === $args['checkout_renewal']) {
                 // Already set earlier
                 // 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_update_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_update_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_update_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_update_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);
             }
         }
     }
     if (false == $args['checkout_renewal']) {
         // Add fees
         foreach ($original_order->get_fees() as $item_id => $order_fee) {
             if (!isset($order_fee['recurring_line_total'])) {
                 continue;
             }
             $item_id = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $order_fee['name'], 'order_item_type' => 'fee'));
             woocommerce_add_order_item_meta($item_id, '_tax_class', $order_fee['tax_class']);
             woocommerce_add_order_item_meta($item_id, '_line_total', WC_Subscriptions::format_total($order_fee['recurring_line_total']));
             woocommerce_add_order_item_meta($item_id, '_line_tax', WC_Subscriptions::format_total($order_fee['recurring_line_tax']));
         }
     }
     // 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.', 'woocommerce-subscriptions'), $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']);
 }
 /**
  * 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');
 }
Exemplo n.º 11
0
/** Update Member Plan **/
function upd_mem_plan()
{
    global $current_user, $woocommerce, $wpdb;
    $mess = array();
    $mess['act'] = 'success';
    parse_str($_POST['form_data'], $d);
    get_currentuserinfo();
    $product_id = $d['meal_plan_type'];
    $arr = array();
    $cur_user_subscription = WC_Subscriptions_Manager::get_users_subscriptions(get_current_user_id());
    /* $current_subscription To Cancel all users previous subscription */
    foreach ($cur_user_subscription as $suk => $suv) {
        $orderID = $suv['order_id'];
        $suv['product_id'] = $d['meal_plan'];
        $arr[$suv['order_id'] . '_' . $d['meal_plan']] = $suv;
        update_user_meta(get_current_user_id(), 'wp_woocommerce_subscriptions', $arr);
        break;
    }
    // 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.
    $product_id = $d['meal_plan_type'];
    $_product = new WC_Product($product_id);
    // Set values
    $item = array();
    // Add line item
    $srOW = $wpdb->get_row("select * FROM wp_woocommerce_order_items WHERE order_id = " . $orderID);
    $item_id = $srOW->order_item_id;
    $args = array('post_type' => 'product', 'post_status' => 'publish');
    $loop = new WP_Query($args);
    $i = 0;
    if ($loop->have_posts()) {
        while ($loop->have_posts()) {
            $loop->the_post();
            $____product = get_product(get_the_ID());
            $_var[get_the_ID()] = $____product->get_available_variations();
        }
    }
    wp_reset_query();
    foreach ($_var as $_k => $_variations) {
        foreach ($_variations as $_vk => $_vv) {
            if ($_vv['variation_id'] == $product_id) {
                $variation_name = $_vv['attributes']['attribute_servings'];
                $p = strip_tags($_vv['price_html']);
            }
        }
    }
    // update post meta for pricing
    update_post_meta($orderID, '_order_total', get_post_meta($product_id, '_price', true));
    update_post_meta($orderID, '_order_recurring_total', get_post_meta($product_id, '_subscription_price', true));
    // Add subscription details so order state persists even when a product is changed
    $period = WC_Subscriptions_Product::get_period($product_id);
    $interval = WC_Subscriptions_Product::get_interval($product_id);
    $length = WC_Subscriptions_Product::get_length($product_id);
    $trial_length = WC_Subscriptions_Product::get_trial_length($product_id);
    $trial_period = WC_Subscriptions_Product::get_trial_period($product_id);
    $sign_up_fee = WC_Subscriptions_Product::get_sign_up_fee($product_id);
    woocommerce_update_order_item_meta($item_id, '_qty', 1);
    woocommerce_update_order_item_meta($item_id, '_tax_class', '');
    woocommerce_update_order_item_meta($item_id, '_product_id', $d['meal_plan']);
    woocommerce_update_order_item_meta($item_id, '_variation_id', $product_id);
    woocommerce_update_order_item_meta($item_id, '_line_subtotal', get_post_meta($product_id, '_price', true));
    woocommerce_update_order_item_meta($item_id, '_line_total', get_post_meta($product_id, '_subscription_price', true));
    // WC_Subscriptions_Product::get_price() would return a price without filters applied
    woocommerce_update_order_item_meta($item_id, '_line_tax', 0);
    woocommerce_update_order_item_meta($item_id, '_line_subtotal_tax', 0);
    // WC_Subscriptions_Product::get_price() would return a price without filters applied
    woocommerce_update_order_item_meta($item_id, 'Servings:', $variation_name);
    woocommerce_update_order_item_meta($item_id, '_subscription_period', $period);
    woocommerce_update_order_item_meta($item_id, '_subscription_interval', $interval);
    woocommerce_update_order_item_meta($item_id, '_subscription_length', $length);
    woocommerce_update_order_item_meta($item_id, '_subscription_trial_length', $trial_length);
    woocommerce_update_order_item_meta($item_id, '_subscription_trial_period', $trial_period);
    woocommerce_update_order_item_meta($item_id, '_subscription_recurring_amount', get_post_meta($product_id, '_subscription_price', true));
    // WC_Subscriptions_Product::get_price() would return a price without filters applied
    woocommerce_update_order_item_meta($item_id, '_subscription_sign_up_fee', $sign_up_fee);
    // Calculated recurring amounts for the item
    woocommerce_update_order_item_meta($item_id, '_recurring_line_total', number_format((double) get_post_meta($product_id, '_price', true), 2, '.', ''));
    woocommerce_update_order_item_meta($item_id, '_recurring_line_tax', '');
    woocommerce_update_order_item_meta($item_id, '_recurring_line_subtotal', number_format((double) get_post_meta($product_id, '_regular_price', true), 2, '.', ''));
    woocommerce_update_order_item_meta($item_id, '_recurring_line_subtotal_tax', '');
    $odr = $orderID;
    /* Fetch Oder Details */
    //if(($_vv['variation_id'] ==  $vari_ID))
    $mealOrder = woocommerce_get_order_item_meta($srOW->order_item_id, 'Servings:', true);
    $mealType = woocommerce_get_order_item_meta($srOW->order_item_id, '_subscription_period', true);
    $mealTotal = woocommerce_get_order_item_meta($srOW->order_item_id, '_recurring_line_subtotal', true);
    $vari_ID = woocommerce_get_order_item_meta($srOW->order_item_id, '_variation_id', true);
    $_product = get_product($product_id);
    $srOW = $wpdb->get_row("UPDATE wp_woocommerce_order_items SET order_item_name = '" . $_product->post->post_title . "' WHERE order_item_id=" . $item_id);
    $html = '<div class="info_heading">Meal Plan</div>
                <div class="info_values">
                    <p>' . $_product->post->post_title . '</p>
                </div>
                <div class="info_heading">Subscriptions Type</div>
                <div class="info_values">
                    <p>' . $variation_name . '</p>
                </div>
                <div class="info_heading">Price</div>
                <div class="info_values">
                    <p>' . $p . '</p>
                </div>';
    $mess['message'] = $html;
    echo json_encode($mess);
    exit;
}
Exemplo n.º 12
0
 /**
  * When an order is added or updated from the admin interface, check if a subscription product
  * has been manually added to the order or the details of the subscription have been modified, 
  * and create/update the subscription as required.
  *
  * Save subscription order meta items
  *
  * @param $post_id int The ID of the post which is the WC_Order object.
  * @param $post Object The post object of the order.
  * @since 1.1
  */
 public static function pre_process_shop_order_meta($post_id, $post)
 {
     global $woocommerce, $wpdb;
     $order_contains_subscription = false;
     $order = new WC_Order($post_id);
     $existing_product_ids = array();
     foreach ($order->get_items() as $existing_item) {
         $existing_product_ids[] = self::get_items_product_id($existing_item);
     }
     $product_ids = array();
     // WC <> 2.0 compatible posted product IDs
     if (isset($_POST['order_item_id'])) {
         foreach ($_POST['order_item_id'] as $order_item_id) {
             // WC 2.0+ has unique order item IDs and the product ID is a piece of meta
             $product_ids[$order_item_id] = woocommerce_get_order_item_meta($order_item_id, '_product_id');
         }
     } elseif (isset($_POST['item_id'])) {
         $product_ids = $_POST['item_id'];
     }
     // WC 1.x treated order item IDs as product IDs
     // Check if there are new subscription products to be added, or the order already has a subscription item
     foreach (array_merge($product_ids, $existing_product_ids) as $order_item_id => $product_id) {
         $is_existing_item = false;
         if (in_array($product_id, $existing_product_ids)) {
             $is_existing_item = true;
         }
         // If this is a new item and it's a subscription product, we have a subscription
         if (!$is_existing_item && WC_Subscriptions_Product::is_subscription($product_id)) {
             $order_contains_subscription = true;
         }
         // If this is an existing item and it's a subscription item, we have a subscription
         if ($is_existing_item && WC_Subscriptions_Order::is_item_subscription($order, $product_id)) {
             $order_contains_subscription = true;
         }
     }
     if (!$order_contains_subscription) {
         return $post_id;
     }
     // If the payment method is changing, make sure we have correct manual payment flag set
     $chosen_payment_method = stripslashes($_POST['_payment_method']);
     $existing_payment_method = get_post_meta($post_id, '_payment_method', true);
     if ($chosen_payment_method != $existing_payment_method || empty($chosen_payment_method)) {
         $payment_gateways = $woocommerce->payment_gateways->payment_gateways();
         if (isset($payment_gateways[$chosen_payment_method]) && $payment_gateways[$chosen_payment_method]->supports('subscriptions')) {
             $manual_renewal = 'false';
         } else {
             $manual_renewal = 'true';
         }
         update_post_meta($post_id, '_wcs_requires_manual_renewal', $manual_renewal);
     }
     // Make sure the recurring order totals are correct
     update_post_meta($post_id, '_order_recurring_discount_cart', stripslashes($_POST['_order_recurring_discount_cart']));
     update_post_meta($post_id, '_order_recurring_discount_total', stripslashes($_POST['_order_recurring_discount_total']));
     update_post_meta($post_id, '_order_recurring_tax_total', stripslashes($_POST['_order_recurring_tax_total']));
     update_post_meta($post_id, '_order_recurring_total', stripslashes($_POST['_order_recurring_total']));
     if (isset($_POST['recurring_order_taxes_id'])) {
         // WC 2.0+
         $tax_keys = array('recurring_order_taxes_id', 'recurring_order_taxes_rate_id', 'recurring_order_taxes_amount', 'recurring_order_taxes_shipping_amount');
         foreach ($tax_keys as $tax_key) {
             ${$tax_key} = isset($_POST[$tax_key]) ? $_POST[$tax_key] : array();
         }
         foreach ($recurring_order_taxes_id as $item_id) {
             $item_id = absint($item_id);
             $rate_id = absint($recurring_order_taxes_rate_id[$item_id]);
             if ($rate_id) {
                 $rate = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $rate_id));
                 $label = $rate->tax_rate_name ? $rate->tax_rate_name : $woocommerce->countries->tax_or_vat();
                 $compound = $rate->tax_rate_compound ? 1 : 0;
                 $code = array();
                 $code[] = $rate->tax_rate_country;
                 $code[] = $rate->tax_rate_state;
                 $code[] = $rate->tax_rate_name ? $rate->tax_rate_name : 'TAX';
                 $code[] = absint($rate->tax_rate_priority);
                 $code = strtoupper(implode('-', array_filter($code)));
             } else {
                 $code = '';
                 $label = $woocommerce->countries->tax_or_vat();
             }
             $wpdb->update($wpdb->prefix . "woocommerce_order_items", array('order_item_name' => woocommerce_clean($code)), array('order_item_id' => $item_id), array('%s'), array('%d'));
             woocommerce_update_order_item_meta($item_id, 'rate_id', $rate_id);
             woocommerce_update_order_item_meta($item_id, 'label', $label);
             woocommerce_update_order_item_meta($item_id, 'compound', $compound);
             if (isset($recurring_order_taxes_amount[$item_id])) {
                 woocommerce_update_order_item_meta($item_id, 'tax_amount', woocommerce_clean($recurring_order_taxes_amount[$item_id]));
             }
             if (isset($recurring_order_taxes_shipping_amount[$item_id])) {
                 woocommerce_update_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($recurring_order_taxes_shipping_amount[$item_id]));
             }
         }
     } else {
         // WC 1.x
         if (!isset($_POST['_order_recurring_taxes'])) {
             $_POST['_order_recurring_taxes'] = array();
         }
         foreach ($_POST['_order_recurring_taxes'] as $index => $tax_details) {
             if (!isset($tax_details['compound'])) {
                 $_POST['_order_recurring_taxes'][$index]['compound'] = 0;
             }
         }
         update_post_meta($post_id, '_order_recurring_taxes', $_POST['_order_recurring_taxes']);
     }
     // Check if all the subscription products on the order have associated subscriptions on the user's account, and if not, add a new one
     foreach ($product_ids as $order_item_id => $product_id) {
         $is_existing_item = false;
         if (in_array($product_id, $existing_product_ids)) {
             $is_existing_item = true;
         }
         // If this is a new item and it's not a subscription product, ignore it
         if (!$is_existing_item && !WC_Subscriptions_Product::is_subscription($product_id)) {
             continue;
         }
         // If this is an existing item and it's not a subscription, ignore it
         if ($is_existing_item && !WC_Subscriptions_Order::is_item_subscription($order, $product_id)) {
             continue;
         }
         $subscription_key = WC_Subscriptions_Manager::get_subscription_key($post_id, $product_id);
         $subscription = array();
         // If order customer changed, move the subscription from the old customer's account to the new customer
         if (!empty($order->customer_user) && $order->customer_user != (int) $_POST['customer_user']) {
             $subscription = WC_Subscriptions_Manager::remove_users_subscription($order->customer_user, $subscription_key);
             if (!empty($subscription)) {
                 $subscriptions = WC_Subscriptions_Manager::get_users_subscriptions((int) $_POST['customer_user']);
                 $subscriptions[$subscription_key] = $subscription;
                 WC_Subscriptions_Manager::update_users_subscriptions((int) $_POST['customer_user'], $subscriptions);
             }
         }
         // In case it's a new order or the customer has changed
         $order->customer_user = $order->user_id = (int) $_POST['customer_user'];
         $subscription = WC_Subscriptions_Manager::get_users_subscription($order->customer_user, $subscription_key);
         if (empty($subscription)) {
             // Add a new subscription
             // The order may not exist yet, so we need to set a few things ourselves
             if (empty($order->order_key)) {
                 $order->order_key = uniqid('order_');
                 add_post_meta($post_id, '_order_key', $order->order_key, true);
             }
             if (empty($_POST['order_date'])) {
                 $start_date = gmdate('Y-m-d H:i:s');
             } else {
                 $start_date = get_gmt_from_date($_POST['order_date'] . ' ' . (int) $_POST['order_date_hour'] . ':' . (int) $_POST['order_date_minute'] . ':00');
             }
             WC_Subscriptions_Manager::create_pending_subscription_for_order($order, $product_id, array('start_date' => $start_date));
             // Add the subscription meta for this item to the order
             $functions_and_meta = array('get_period' => '_order_subscription_periods', 'get_interval' => '_order_subscription_intervals', 'get_length' => '_order_subscription_lengths');
             foreach ($functions_and_meta as $function_name => $meta_key) {
                 $subscription_meta = self::get_meta($order, $meta_key, array());
                 $subscription_meta[$product_id] = WC_Subscriptions_Product::$function_name($product_id);
                 update_post_meta($order->id, $meta_key, $subscription_meta);
             }
             // This works because process_shop_order_item_meta saves item meta to workaround a WC 1.x bug and in WC 2.0+ meta is added when the item is added via Ajax
             self::process_shop_order_item_meta($post_id, $post);
             // If the order's existing status is something other than pending and the order status is not being changed, manually set the subscription's status (otherwise, it will be handled when WC transitions the order's status)
             if ($order->status == $_POST['order_status'] && 'pending' != $order->status) {
                 switch ($order->status) {
                     case 'completed':
                     case 'processing':
                         WC_Subscriptions_Manager::activate_subscription($order->customer_user, $subscription_key);
                         break;
                     case 'refunded':
                     case 'cancelled':
                         WC_Subscriptions_Manager::cancel_subscription($order->customer_user, $subscription_key);
                         break;
                     case 'failed':
                         WC_Subscriptions_Manager::failed_subscription_signup($order->customer_user, $subscription_key);
                         break;
                 }
             }
         }
     }
     // Determine whether we need to update any subscription dates for existing subscriptions (before the item meta is updated)
     if (!empty($product_ids)) {
         $start_date = $_POST['order_date'] . ' ' . (int) $_POST['order_date_hour'] . ':' . (int) $_POST['order_date_minute'] . ':00';
         // Start date changed for an existing order
         if (!empty($order->order_date) && $order->order_date != $start_date) {
             self::$requires_update['expiration_date'] = array_values($product_ids);
             self::$requires_update['trial_expiration'] = array_values($product_ids);
             self::$requires_update['next_billing_date'] = array_values($product_ids);
         } elseif (isset($_POST['meta_key'])) {
             // WC 2.0+
             $item_meta_keys = isset($_POST['meta_key']) ? $_POST['meta_key'] : array();
             $new_meta_values = isset($_POST['meta_value']) ? $_POST['meta_value'] : array();
             foreach ($item_meta_keys as $item_meta_id => $meta_key) {
                 $meta_data = self::get_item_meta_data($item_meta_id);
                 $product_id = woocommerce_get_order_item_meta($meta_data->order_item_id, '_product_id');
                 // Set flags to update payment dates if required
                 switch ($meta_key) {
                     case '_subscription_period':
                     case '_subscription_interval':
                         if ($new_meta_values[$item_meta_id] != $meta_data->meta_value) {
                             self::$requires_update['next_billing_date'][] = $product_id;
                         }
                         break;
                     case '_subscription_trial_length':
                     case '_subscription_trial_period':
                         if ($new_meta_values[$item_meta_id] != $meta_data->meta_value) {
                             self::$requires_update['expiration_date'][] = $product_id;
                             self::$requires_update['trial_expiration'][] = $product_id;
                             self::$requires_update['next_billing_date'][] = $product_id;
                         }
                         break;
                     case '_subscription_length':
                         if ($new_meta_values[$item_meta_id] != $meta_data->meta_value) {
                             self::$requires_update['expiration_date'][] = $product_id;
                             self::$requires_update['next_billing_date'][] = $product_id;
                         }
                         break;
                 }
             }
         } elseif (isset($_POST['meta_name'])) {
             // WC 1.x
             $item_meta_names = isset($_POST['meta_name']) ? $_POST['meta_name'] : '';
             $item_meta_values = isset($_POST['meta_value']) ? $_POST['meta_value'] : '';
             $item_id_count = count($item_ids);
             for ($i = 0; $i < $item_id_count; $i++) {
                 if (!isset($item_ids[$i]) || !$item_ids[$i]) {
                     continue;
                 } elseif (!in_array($item_ids[$i], $existing_product_ids)) {
                     // New subscriptions throw a false positive
                     continue;
                 }
                 // Meta
                 $item_meta = new WC_Order_Item_Meta();
                 if (isset($item_meta_names[$i]) && isset($item_meta_values[$i])) {
                     $meta_names = $item_meta_names[$i];
                     $meta_values = $item_meta_values[$i];
                     $meta_names_count = count($meta_names);
                     for ($ii = 0; $ii < $meta_names_count; $ii++) {
                         $meta_name = esc_attr($meta_names[$ii]);
                         $meta_value = esc_attr($meta_values[$ii]);
                         if (!isset($meta_name) || !isset($meta_value)) {
                             continue;
                         }
                         // Set flags to update payment dates if required
                         switch ($meta_name) {
                             case '_subscription_period':
                             case '_subscription_interval':
                                 if ($meta_value != self::get_item_meta($order, $meta_name, $item_ids[$i])) {
                                     self::$requires_update['next_billing_date'][] = $item_ids[$i];
                                 }
                                 break;
                             case '_subscription_trial_length':
                             case '_subscription_trial_period':
                                 if ($meta_value != self::get_item_meta($order, $meta_name, $item_ids[$i])) {
                                     self::$requires_update['expiration_date'][] = $item_ids[$i];
                                     self::$requires_update['trial_expiration'][] = $item_ids[$i];
                                     self::$requires_update['next_billing_date'][] = $item_ids[$i];
                                 }
                                 break;
                             case '_subscription_length':
                                 if ($meta_value != self::get_item_meta($order, $meta_name, $item_ids[$i])) {
                                     self::$requires_update['expiration_date'][] = $item_ids[$i];
                                     self::$requires_update['next_billing_date'][] = $item_ids[$i];
                                 }
                                 break;
                         }
                     }
                 }
             }
         }
     }
 }
 public static function update_service_fee_subtotal_on_order_creation($order_id, $posted)
 {
     $order = new WC_Order($order_id);
     foreach ($order->get_fees() as $oiid => $fee) {
         if (woocommerce_get_order_item_meta($oiid, '_line_subtotal', true) === '') {
             woocommerce_update_order_item_meta($oiid, '_line_subtotal', woocommerce_get_order_item_meta($oiid, '_line_total', true));
         }
     }
 }
 /**
  * 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 and certain order items are not set, like taxes, shipping as they need to be set in teh calling function, like @see WC_Subscriptions_Checkout::filter_woocommerce_create_order(). 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.', 'woocommerce-subscriptions'));
         $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', 'woocommerce-subscriptions'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'woocommerce-subscriptions'))), 'ping_status' => 'closed', 'post_excerpt' => $original_order->customer_note, 'post_author' => 1, 'post_password' => $renewal_order_key);
     $create_new_order = true;
     if (!WC_Subscriptions::is_woocommerce_pre('2.2')) {
         // WC 2.2 order status
         $renewal_order_data['post_status'] = 'wc-pending';
     } else {
         $renewal_order_data['post_status'] = 'publish';
     }
     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'];
             if (WC_Subscriptions::is_woocommerce_pre('2.2')) {
                 // WC 2.1  - need to use taxonomy
                 /* 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';
             } else {
                 // WC 2.2+
                 $failed_order = wc_get_order($failed_order_id);
                 $order_status = $failed_order->get_status();
             }
             /* If paying on a pending order, we are resuming */
             if ($order_status == 'pending') {
                 $renewal_order_id = $failed_order_id;
             }
         }
         if ($renewal_order_id) {
             if (WC_Subscriptions::is_woocommerce_pre('2.2')) {
                 // WC 2.1  - need to use taxonomy
                 /* 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';
             } else {
                 // WC 2.2+
                 $existing_order = wc_get_order($renewal_order_id);
                 $order_status = $existing_order->get_status();
             }
             // 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);
     }
     if (WC_Subscriptions::is_woocommerce_pre('2.2')) {
         // WC 2.1 order status
         // 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);
     $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', '_wc_points_earned', '_transaction_id')";
     // 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);
     $failed_payment_multiplier = 1;
     if (false == $args['checkout_renewal']) {
         // 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);
         }
         // Set order totals based on recurring totals from the original order
         $cart_discount = $failed_payment_multiplier * wc_format_decimal(get_post_meta($original_order->id, '_order_recurring_discount_cart', true));
         $order_discount = $failed_payment_multiplier * wc_format_decimal(get_post_meta($original_order->id, '_order_recurring_discount_total', true));
         $order_shipping_tax = $failed_payment_multiplier * wc_format_decimal(get_post_meta($original_order->id, '_order_recurring_shipping_tax_total', true));
         $order_shipping = $failed_payment_multiplier * wc_format_decimal(get_post_meta($original_order->id, '_order_recurring_shipping_total', true));
         $order_tax = $failed_payment_multiplier * wc_format_decimal(get_post_meta($original_order->id, '_order_recurring_tax_total', true));
         $order_total = $failed_payment_multiplier * wc_format_decimal(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);
         // Set shipping for orders created with WC 2.0.n (or when we are using WC 2.0.n)
         if (WC_Subscriptions::is_woocommerce_pre('2.1') || isset($original_order->recurring_shipping_method)) {
             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);
             // Also set recurring shipping as it's a parent renewal order
             if ('parent' == $args['new_order_role']) {
                 update_post_meta($renewal_order_id, '_recurring_shipping_method', $original_order->recurring_shipping_method);
                 update_post_meta($renewal_order_id, '_recurring_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) {
             $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', $failed_payment_multiplier * WC_Subscriptions::format_total($recurring_order_tax['tax_amount']));
                 woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', $failed_payment_multiplier * WC_Subscriptions::format_total($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']);
                 }
             }
         }
         // Set up shipping items on renewal order
         $recurring_shipping_items = WC_Subscriptions_Order::get_recurring_shipping_methods($original_order);
         foreach ($recurring_shipping_items as $recurring_shipping_item_id => $recurring_shipping_item) {
             $item_ids = array();
             $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_shipping_item['name'], 'order_item_type' => 'shipping'));
             // Also set recurring shipping as it's a parent renewal order
             if ('parent' == $args['new_order_role']) {
                 $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_shipping_item['name'], 'order_item_type' => 'recurring_shipping'));
             }
             // Add shipping item meta
             foreach ($item_ids as $item_id) {
                 woocommerce_add_order_item_meta($item_id, 'method_id', $recurring_shipping_item['method_id']);
                 woocommerce_add_order_item_meta($item_id, 'cost', $failed_payment_multiplier * WC_Subscriptions::format_total($recurring_shipping_item['cost']));
                 // Set line taxes for shipping
                 if (isset($recurring_shipping_item['taxes'])) {
                     $taxes = maybe_unserialize($recurring_shipping_item['taxes']);
                 } else {
                     // try to determine recurring shipping taxes from original order's shipping taxes
                     $taxes = array();
                     foreach ($original_order->get_shipping_methods() as $original_shipping_item_id => $original_shipping_item) {
                         // We need to use the amount of the same shipping method as this one
                         if ($recurring_shipping_item['method_id'] != $original_shipping_item['method_id']) {
                             continue;
                         }
                         // If we don't have taxes on the matching shipping item, there's nothing we can do
                         if (!isset($original_shipping_item['taxes'])) {
                             break;
                         }
                         $original_shipping_item['taxes'] = maybe_unserialize($original_shipping_item['taxes']);
                         // Make sure we account for any amount on the original original shipping not applied to renewals by determining what proportion of the initial amount the recurring total represents
                         if (0 != $original_shipping_item['cost'] && $recurring_shipping_item['cost'] != $original_shipping_item['cost']) {
                             $recurring_ratio = $recurring_shipping_item['cost'] / $original_shipping_item['cost'];
                             foreach ($original_shipping_item['taxes'] as $tax_id => $tax_amount) {
                                 $original_shipping_item['taxes'][$tax_id] = $recurring_ratio * $tax_amount;
                             }
                         }
                         foreach ($original_shipping_item['taxes'] as $tax_id => $tax_amount) {
                             $taxes[$tax_id] = WC_Subscriptions::format_total($failed_payment_multiplier * $tax_amount);
                         }
                     }
                 }
                 woocommerce_add_order_item_meta($item_id, 'taxes', $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']);
     if (true === $args['checkout_renewal']) {
         $cart_items = $woocommerce->cart->get_cart();
     }
     foreach ($order_items as $item_index => $order_item) {
         $renewal_order_item_name = apply_filters('woocommerce_subscriptions_renewal_order_item_name', $order_item['name'], $order_item, $original_order);
         // 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'));
         if (true === $args['checkout_renewal']) {
             $cart_item = array();
             foreach ($cart_items as $item) {
                 if ($item['product_id'] == $order_item['product_id'] && (empty($order_item['variation_id']) || $item['variation_id'] == $order_item['variation_id'])) {
                     $cart_item = $item;
                 }
             }
             if (!empty($cart_item)) {
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_total', woocommerce_format_decimal($cart_item['line_total']));
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_tax', woocommerce_format_decimal($cart_item['line_tax']));
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_subtotal', woocommerce_format_decimal($cart_item['line_subtotal']));
                 woocommerce_update_order_item_meta($recurring_item_id, '_line_subtotal_tax', woocommerce_format_decimal($cart_item['line_subtotal_tax']));
                 if (is_object($cart_item['data'])) {
                     woocommerce_update_order_item_meta($recurring_item_id, '_tax_class', $cart_item['data']->get_tax_class());
                 }
             }
             $cart_items = $woocommerce->cart->get_cart();
         }
         if (WC_Subscriptions::is_woocommerce_pre('2.4')) {
             $item_meta = new WC_Order_Item_Meta($order_item['item_meta']);
         } else {
             $item_meta = new WC_Order_Item_Meta($order_item);
         }
         // Remove recurring line items and set item totals based on recurring line totals
         foreach ($item_meta->meta as $meta_key => $meta) {
             // meta value might be an array. If it is, we need to preserve all values
             foreach ($meta as $key => $value) {
                 $meta_values[$key] = maybe_unserialize($value);
             }
             if (false === $args['checkout_renewal']) {
                 // Already set earlier
                 // Map line item totals based on recurring line totals
                 switch ($meta_key) {
                     case '_recurring_line_total':
                         woocommerce_update_order_item_meta($recurring_item_id, '_line_total', $failed_payment_multiplier * woocommerce_format_decimal($meta_values[0]));
                         break;
                     case '_recurring_line_tax':
                         woocommerce_update_order_item_meta($recurring_item_id, '_line_tax', $failed_payment_multiplier * woocommerce_format_decimal($meta_values[0]));
                         break;
                     case '_recurring_line_subtotal':
                         woocommerce_update_order_item_meta($recurring_item_id, '_line_subtotal', $failed_payment_multiplier * woocommerce_format_decimal($meta_values[0]));
                         break;
                     case '_recurring_line_subtotal_tax':
                         woocommerce_update_order_item_meta($recurring_item_id, '_line_subtotal_tax', $failed_payment_multiplier * woocommerce_format_decimal($meta_values[0]));
                         break;
                     case '_line_tax_data':
                         // Copy line tax data if the order doesn't have a _recurring_line_tax_data (for backward compatibility)
                         if (!array_key_exists('_recurring_line_tax_data', $item_meta->meta)) {
                             $meta_value = $meta_values[0];
                             $line_total = $item_meta->meta['_line_total'][0];
                             $recurring_line_total = $item_meta->meta['_recurring_line_total'][0];
                             // There will only be recurring tax data if the recurring amount is > 0 and we can only retroactively calculate recurring amount from initial amoutn if it is > 0
                             if ($line_total > 0 && $recurring_line_total > 0) {
                                 // Make sure we account for any sign-up fees by determining what proportion of the initial amount the recurring total represents
                                 $recurring_ratio = $recurring_line_total / $line_total;
                                 $recurring_tax_data = array();
                                 $tax_data_keys = array('total', 'subtotal');
                                 foreach ($tax_data_keys as $tax_data_key) {
                                     foreach ($meta_value[$tax_data_key] as $tax_index => $tax_value) {
                                         // Use total tax amount for both total and subtotal because we don't want any initial discounts to be applied to recurring amounts
                                         $total_tax_amount = $meta_value['total'][$tax_index];
                                         $recurring_tax_data[$tax_data_key][$tax_index] = woocommerce_format_decimal($failed_payment_multiplier * ($recurring_ratio * $total_tax_amount));
                                     }
                                 }
                             } else {
                                 $recurring_tax_data = array('total' => array(), 'subtotal' => array());
                             }
                             woocommerce_update_order_item_meta($recurring_item_id, '_line_tax_data', $recurring_tax_data);
                         }
                         break;
                     case '_recurring_line_tax_data':
                         $meta_value = $meta_values[0];
                         $recurring_tax_data = array();
                         $tax_data_keys = array('total', 'subtotal');
                         foreach ($tax_data_keys as $tax_data_key) {
                             foreach ($meta_value[$tax_data_key] as $tax_index => $tax_value) {
                                 $recurring_tax_data[$tax_data_key][$tax_index] = woocommerce_format_decimal($failed_payment_multiplier * $tax_value);
                             }
                         }
                         woocommerce_update_order_item_meta($recurring_item_id, '_line_tax_data', $recurring_tax_data);
                         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 '_recurring_line_tax_data':
                 case '_line_tax_data':
                 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) {
                 // cast it to an array. Arrays will be kept, strings will be an array. Tested back to PHP 5.2.16
                 foreach ($meta_values as $meta_value) {
                     woocommerce_add_order_item_meta($recurring_item_id, $meta_key, $meta_value);
                 }
             }
         }
     }
     if (false == $args['checkout_renewal']) {
         // Add fees
         foreach ($original_order->get_fees() as $item_id => $order_fee) {
             if (!isset($order_fee['recurring_line_total'])) {
                 continue;
             }
             $item_id = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $order_fee['name'], 'order_item_type' => 'fee'));
             woocommerce_add_order_item_meta($item_id, '_tax_class', $order_fee['tax_class']);
             woocommerce_add_order_item_meta($item_id, '_line_total', WC_Subscriptions::format_total($order_fee['recurring_line_total']));
             woocommerce_add_order_item_meta($item_id, '_line_tax', WC_Subscriptions::format_total($order_fee['recurring_line_tax']));
         }
     }
     // 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.', 'woocommerce-subscriptions'), $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']);
 }