function get_order_report_data($start_date, $end_date)
 {
     global $wpdb;
     $order_item_meta_table = $wpdb->prefix . 'woocommerce_order_itemmeta';
     $order_items_table = $wpdb->prefix . 'woocommerce_order_items';
     $inst_commissions = $wpdb->get_results("SELECT order_items.order_id,order_meta.meta_key as instructor,order_meta.meta_value as commission\n\t\t\tFROM {$wpdb->posts} as posts\n\t\t\tLEFT JOIN {$order_items_table} as order_items ON posts.ID = order_items.order_id\n\t\t\tLEFT JOIN {$order_item_meta_table} as order_meta ON order_items.order_item_id = order_meta.order_item_id\n\t\t\tWHERE posts.post_type='shop_order'\n\t\t\tAND posts.post_status='wc-completed'\n\t\t\tAND posts.post_date BETWEEN '{$start_date}' AND '{$end_date}'\n\t\t\tAND order_meta.meta_key LIKE 'commission%'");
     if (is_array($inst_commissions)) {
         foreach ($inst_commissions as $inst_commission) {
             $order_ids[] = $inst_commission->order_id;
             $inst = explode('commission', $inst_commission->instructor);
             if (is_numeric($inst[1])) {
                 $instructor_commissions[$inst[1]] += $inst_commission->commission;
             }
         }
         if (is_array($order_ids)) {
             $order_id_string = implode(',', $order_ids);
         }
     }
     $query = "SELECT order_items.order_item_id,order_meta.meta_value as total_sales\n\t\t\tFROM {$wpdb->posts} as posts\n\t\t\tLEFT JOIN {$order_items_table} as order_items ON posts.ID = order_items.order_id\n\t\t\tLEFT JOIN {$order_item_meta_table} as order_meta ON order_items.order_item_id = order_meta.order_item_id\n\t\t\tWHERE posts.post_type='shop_order'\n\t\t\tAND posts.post_status='wc-completed'\n\t\t\tAND posts.post_date BETWEEN '{$start_date}' AND '{$end_date}'\n\t\t\tAND order_meta.meta_key = '_line_total'";
     if (isset($order_id_string)) {
         $query .= "AND posts.ID NOT IN ({$order_id_string})";
     }
     $inst_commissions = $wpdb->get_results($query);
     $commissions = get_option('instructor_commissions');
     foreach ($inst_commissions as $inst_commission) {
         $oid = $inst_commission->order_item_id;
         $pid = woocommerce_get_order_item_meta($oid, '_product_id', true);
         $courses = vibe_sanitize(get_post_meta($pid, 'vibe_courses', false));
         if (isset($courses) && is_array($courses) && count($courses)) {
             $n = count($courses);
             foreach ($courses as $course) {
                 $instructors = apply_filters('wplms_course_instructors', get_post_field('post_author', $course), $course);
                 if (is_numeric($instructors)) {
                     if (!isset($commission[$course][$instructors])) {
                         $commission[$course][$instructors] = 70;
                     }
                     echo $commission[$course][$instructors] * $inst_commission->total_sales;
                     $instructor_commissions[$instructors] += $commission[$course][$instructors] * $inst_commission->total_sales;
                 } else {
                     if (is_Array($instructors)) {
                         $k = count($instructors);
                         foreach ($instructors as $instructor) {
                             if (!isset($commission[$course][$instructor])) {
                                 $commission[$course][$instructor] = floor(70 / $k);
                             }
                             $instructor_commissions[$instructor] += $commission[$course][$instructor] * $inst_commission->total_sales;
                         }
                     }
                 }
             }
         }
     }
     return $instructor_commissions;
 }
        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;
        }
 /**
  * Calculate recurring line taxes when a store manager clicks the "Calc Line Tax" button on the "Edit Order" page.
  *
  * Based on the @see woocommerce_calc_line_taxes() function.
  * @since 1.2.4
  * @return void
  */
 public static function calculate_recurring_line_taxes()
 {
     global $woocommerce, $wpdb;
     check_ajax_referer('woocommerce-subscriptions', 'security');
     $tax = new WC_Tax();
     $taxes = $tax_rows = $item_taxes = $shipping_taxes = $return = array();
     $item_tax = 0;
     $order_id = absint($_POST['order_id']);
     $country = strtoupper(esc_attr($_POST['country']));
     $state = strtoupper(esc_attr($_POST['state']));
     $postcode = strtoupper(esc_attr($_POST['postcode']));
     $tax_class = esc_attr($_POST['tax_class']);
     if (isset($_POST['city'])) {
         $city = sanitize_title(esc_attr($_POST['city']));
     }
     $shipping = $_POST['shipping'];
     $line_subtotal = isset($_POST['line_subtotal']) ? esc_attr($_POST['line_subtotal']) : 0;
     $line_total = isset($_POST['line_total']) ? esc_attr($_POST['line_total']) : 0;
     $product_id = '';
     if (isset($_POST['order_item_id'])) {
         $product_id = woocommerce_get_order_item_meta($_POST['order_item_id'], '_product_id');
     } elseif (isset($_POST['product_id'])) {
         $product_id = esc_attr($_POST['product_id']);
     }
     if (!empty($product_id) && WC_Subscriptions_Product::is_subscription($product_id)) {
         // Get product details
         $product = WC_Subscriptions::get_product($product_id);
         $item_tax_status = $product->get_tax_status();
         if ($item_tax_status == 'taxable') {
             $tax_rates = $tax->find_rates(array('country' => $country, 'state' => $state, 'postcode' => $postcode, 'city' => $city, 'tax_class' => $tax_class));
             $line_subtotal_taxes = $tax->calc_tax($line_subtotal, $tax_rates, false);
             $line_taxes = $tax->calc_tax($line_total, $tax_rates, false);
             $line_subtotal_tax = $tax->round(array_sum($line_subtotal_taxes));
             $line_tax = $tax->round(array_sum($line_taxes));
             if ($line_subtotal_tax < 0) {
                 $line_subtotal_tax = 0;
             }
             if ($line_tax < 0) {
                 $line_tax = 0;
             }
             $return = array('recurring_line_subtotal_tax' => $line_subtotal_tax, 'recurring_line_tax' => $line_tax);
             // Sum the item taxes
             foreach (array_keys($taxes + $line_taxes) as $key) {
                 $taxes[$key] = (isset($line_taxes[$key]) ? $line_taxes[$key] : 0) + (isset($taxes[$key]) ? $taxes[$key] : 0);
             }
         }
         // Now calculate shipping tax
         $matched_tax_rates = array();
         $tax_rates = $tax->find_rates(array('country' => $country, 'state' => $state, 'postcode' => $postcode, 'city' => $city, 'tax_class' => ''));
         if ($tax_rates) {
             foreach ($tax_rates as $key => $rate) {
                 if (isset($rate['shipping']) && $rate['shipping'] == 'yes') {
                     $matched_tax_rates[$key] = $rate;
                 }
             }
         }
         $shipping_taxes = $tax->calc_shipping_tax($shipping, $matched_tax_rates);
         $shipping_tax = $tax->round(array_sum($shipping_taxes));
         $return['recurring_shipping_tax'] = $shipping_tax;
         // Remove old tax rows
         $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'recurring_tax' )", $order_id));
         $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'recurring_tax'", $order_id));
         // Get tax rates
         $rates = $wpdb->get_results("SELECT tax_rate_id, tax_rate_country, tax_rate_state, tax_rate_name, tax_rate_priority FROM {$wpdb->prefix}woocommerce_tax_rates ORDER BY tax_rate_name");
         $tax_codes = array();
         foreach ($rates as $rate) {
             $code = array();
             $code[] = $rate->tax_rate_country;
             $code[] = $rate->tax_rate_state;
             $code[] = $rate->tax_rate_name ? sanitize_title($rate->tax_rate_name) : 'TAX';
             $code[] = absint($rate->tax_rate_priority);
             $tax_codes[$rate->tax_rate_id] = strtoupper(implode('-', array_filter($code)));
         }
         // Now merge to keep tax rows
         ob_start();
         foreach (array_keys($taxes + $shipping_taxes) as $key) {
             $item = array();
             $item['rate_id'] = $key;
             $item['name'] = $tax_codes[$key];
             $item['label'] = $tax->get_rate_label($key);
             $item['compound'] = $tax->is_compound($key) ? 1 : 0;
             $item['tax_amount'] = $tax->round(isset($taxes[$key]) ? $taxes[$key] : 0);
             $item['shipping_tax_amount'] = $tax->round(isset($shipping_taxes[$key]) ? $shipping_taxes[$key] : 0);
             if (!$item['label']) {
                 $item['label'] = $woocommerce->countries->tax_or_vat();
             }
             // Add line item
             $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'recurring_tax'));
             // Add line item meta
             if ($item_id) {
                 woocommerce_add_order_item_meta($item_id, 'rate_id', $item['rate_id']);
                 woocommerce_add_order_item_meta($item_id, 'label', $item['label']);
                 woocommerce_add_order_item_meta($item_id, 'compound', $item['compound']);
                 woocommerce_add_order_item_meta($item_id, 'tax_amount', $item['tax_amount']);
                 woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', $item['shipping_tax_amount']);
             }
             include plugin_dir_path(WC_Subscriptions::$plugin_file) . 'templates/admin/post-types/writepanels/order-tax-html.php';
         }
         $return['tax_row_html'] = ob_get_clean();
         echo json_encode($return);
     }
     die;
 }
 /**
  * Add email to the queue
  *
  * @param $order_id
  * @param $triggers
  * @param string $subs_key
  * @param string $user_id
  */
 public static function add_to_queue($order_id, $triggers, $subs_key = '', $user_id = '')
 {
     $emails = fue_get_emails('any', FUE_Email::STATUS_ACTIVE, array('meta_query' => array(array('key' => '_interval_type', 'value' => $triggers, 'compare' => 'IN'))));
     foreach ($emails as $email) {
         $interval = (int) $email->interval_num;
         $add = FUE_Sending_Scheduler::get_time_to_add($interval, $email->interval_duration);
         $send_on = current_time('timestamp') + $add;
         $prod_id = 0;
         if ($subs_key) {
             $item_id = WC_Subscriptions_Order::get_item_id_by_subscription_key($subs_key);
             $product_id = woocommerce_get_order_item_meta($item_id, '_product_id', true);
             $variation_id = woocommerce_get_order_item_meta($item_id, '_variation_id', true);
             $meta = maybe_unserialize($email->meta);
             $include_variations = isset($meta['include_variations']) && $meta['include_variations'] == 'yes';
             $match = false;
             // exact product match
             if ($email->product_id == $product_id) {
                 $match = true;
             } elseif ($email->product_id == $variation_id) {
                 $match = true;
             }
             if (!$match) {
                 continue;
             }
         }
         $insert = array('send_on' => $send_on, 'email_id' => $email->id, 'product_id' => $prod_id, 'order_id' => $order_id);
         if ($subs_key) {
             $insert['meta']['subs_key'] = $subs_key;
         }
         if ($user_id) {
             $user = new WP_User($user_id);
             $insert['user_id'] = $user_id;
             $insert['user_email'] = $user->user_email;
         }
         FUE_Sending_Scheduler::queue_email($insert, $email);
     }
 }
Exemplo n.º 5
0
    }
    ?>
				<span class="<?php 
    echo $clas;
    ?>
">Edit</span>			
			</h2>
            <div class="plan_information">
                <?php 
    $_product = get_product($current_subscription['product_id']);
    /* Fetch Oder Details */
    $srOW = $wpdb->get_row("select * FROM wp_woocommerce_order_items WHERE order_id = " . $odr);
    $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);
    /**/
    $args = array('post_type' => 'product', 'post_status' => 'publish');
    $loop = new WP_Query($args);
    $_var = array();
    $i = 0;
    if ($loop->have_posts()) {
        while ($loop->have_posts()) {
            $loop->the_post();
            $p = get_product(get_the_ID());
            if ($p->product_type == 'variable-subscription' && $_product->product_type == 'variable-subscription') {
                $_var[get_the_ID()] = $_product->get_available_variations();
            }
        }
    }
    wp_reset_query();
 /**
  * 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 $order WC_Order | int The WC_Order object or ID of the order for which the a new order should be created.
  * @param $product_id string The ID of the subscription product in the order which needs to be added to the new order.
  * @param $args array (optional) An array of name => value flags:
  *         'new_order_role' string A flag to indicate whether the new order should become the master order for the subscription. Accepts either 'parent' or 'child'. Defaults to 'parent' - replace the existing order.
  *         'checkout_renewal' bool Indicates if invoked from an interactive cart/checkout session. Default false.
  *         'failed_order_id' int For checkout_renewal true, indicates order id being replaced
  * @since 1.2
  */
 public static function generate_renewal_order($original_order, $product_id, $args = array())
 {
     global $wpdb, $woocommerce;
     if (!is_object($original_order)) {
         $original_order = new WC_Order($original_order);
     }
     if (!WC_Subscriptions_Order::order_contains_subscription($original_order) || !WC_Subscriptions_Order::is_item_subscription($original_order, $product_id)) {
         return false;
     }
     if (self::is_renewal($original_order, array('order_role' => 'child'))) {
         $original_order = self::get_parent_order($original_order);
     }
     if (!is_array($args)) {
         _deprecated_argument(__CLASS__ . '::' . __FUNCTION__, '1.3', __('Third parameter is now an array of name => value pairs. Use array( "new_order_role" => "parent" ) instead.', WC_Subscriptions::$text_domain));
         $args = array('new_order_role' => $args);
     }
     $args = wp_parse_args($args, array('new_order_role' => 'parent', 'checkout_renewal' => false));
     $renewal_order_key = uniqid('order_');
     // Create the new order
     $renewal_order_data = array('post_type' => 'shop_order', 'post_title' => sprintf(__('Subscription Renewal Order &ndash; %s', WC_Subscriptions::$text_domain), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', WC_Subscriptions::$text_domain))), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => $original_order->customer_note, 'post_author' => 1, 'post_password' => $renewal_order_key);
     $create_new_order = true;
     if ('child' == $args['new_order_role']) {
         $renewal_order_data['post_parent'] = $original_order->id;
     }
     if (true === $args['checkout_renewal']) {
         $renewal_order_id = null;
         if ($woocommerce->session->order_awaiting_payment > 0) {
             $renewal_order_id = absint($woocommerce->session->order_awaiting_payment);
         } elseif (isset($args['failed_order_id'])) {
             $failed_order_id = $args['failed_order_id'];
             /* Check order is unpaid by getting its status */
             $terms = wp_get_object_terms($failed_order_id, 'shop_order_status', array('fields' => 'slugs'));
             $order_status = isset($terms[0]) ? $terms[0] : 'pending';
             /* If paying on a pending order, we are resuming */
             if ($order_status == 'pending') {
                 $renewal_order_id = $failed_order_id;
             }
         }
         if ($renewal_order_id) {
             /* Check order is unpaid by getting its status */
             $terms = wp_get_object_terms($renewal_order_id, 'shop_order_status', array('fields' => 'slugs'));
             $order_status = isset($terms[0]) ? $terms[0] : 'pending';
             // Resume the unpaid order if its pending
             if ($order_status == 'pending' || $order_status == 'failed') {
                 // Update the existing order as we are resuming it
                 $create_new_order = false;
                 $renewal_order_data['ID'] = $renewal_order_id;
                 wp_update_post($renewal_order_data);
                 // Clear the old line items - we'll add these again in case they changed
                 $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d )", $renewal_order_id));
                 $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d", $renewal_order_id));
             }
         }
     }
     if ($create_new_order) {
         $renewal_order_id = wp_insert_post($renewal_order_data);
     }
     // Set the order as pending
     wp_set_object_terms($renewal_order_id, 'pending', 'shop_order_status');
     // Set a unique key for this order
     update_post_meta($renewal_order_id, '_order_key', $renewal_order_key);
     if (true === $args['checkout_renewal']) {
         $checkout_object = $woocommerce->checkout;
         $customer_id = $original_order->customer_user;
         // Save posted billing fields to both renewal and original order
         if ($checkout_object->checkout_fields['billing']) {
             foreach ($checkout_object->checkout_fields['billing'] as $key => $field) {
                 update_post_meta($renewal_order_id, '_' . $key, $checkout_object->posted[$key]);
                 update_post_meta($original_order->id, '_' . $key, $checkout_object->posted[$key]);
                 // User
                 if ($customer_id && !empty($checkout_object->posted[$key])) {
                     update_user_meta($customer_id, $key, $checkout_object->posted[$key]);
                     // Special fields
                     switch ($key) {
                         case "billing_email":
                             if (!email_exists($checkout_object->posted[$key])) {
                                 wp_update_user(array('ID' => $customer_id, 'user_email' => $checkout_object->posted[$key]));
                             }
                             break;
                         case "billing_first_name":
                             wp_update_user(array('ID' => $customer_id, 'first_name' => $checkout_object->posted[$key]));
                             break;
                         case "billing_last_name":
                             wp_update_user(array('ID' => $customer_id, 'last_name' => $checkout_object->posted[$key]));
                             break;
                     }
                 }
             }
         }
         // Save posted shipping fields to both renewal and original order
         if ($checkout_object->checkout_fields['shipping'] && ($woocommerce->cart->needs_shipping() || get_option('woocommerce_require_shipping_address') == 'yes')) {
             foreach ($checkout_object->checkout_fields['shipping'] as $key => $field) {
                 $postvalue = false;
                 if ($checkout_object->posted['shiptobilling']) {
                     if (isset($checkout_object->posted[str_replace('shipping_', 'billing_', $key)])) {
                         $postvalue = $checkout_object->posted[str_replace('shipping_', 'billing_', $key)];
                         update_post_meta($renewal_order_id, '_' . $key, $postvalue);
                         update_post_meta($original_order->id, '_' . $key, $postvalue);
                     }
                 } else {
                     $postvalue = $checkout_object->posted[$key];
                     update_post_meta($renewal_order_id, '_' . $key, $postvalue);
                     update_post_meta($original_order->id, '_' . $key, $postvalue);
                 }
                 // User
                 if ($postvalue && $customer_id) {
                     update_user_meta($customer_id, $key, $postvalue);
                 }
             }
         }
     }
     $order_meta_query = "SELECT `meta_key`, `meta_value` FROM {$wpdb->postmeta} WHERE `post_id` = {$original_order->id} 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')";
     } else {
         $order_meta_query .= " AND `meta_key` NOT LIKE '_order_recurring_%'";
     }
     // Allow extensions to add/remove order meta
     $order_meta_query = apply_filters('woocommerce_subscriptions_renewal_order_meta_query', $order_meta_query, $original_order->id, $renewal_order_id, $args['new_order_role']);
     // Carry all the required meta from the old order over to the new order
     $order_meta = $wpdb->get_results($order_meta_query, 'ARRAY_A');
     $order_meta = apply_filters('woocommerce_subscriptions_renewal_order_meta', $order_meta, $original_order->id, $renewal_order_id, $args['new_order_role']);
     foreach ($order_meta as $meta_item) {
         add_post_meta($renewal_order_id, $meta_item['meta_key'], maybe_unserialize($meta_item['meta_value']), true);
     }
     $outstanding_balance = WC_Subscriptions_Order::get_outstanding_balance($original_order, $product_id);
     if (true === $args['checkout_renewal']) {
         $failed_payment_multiplier = 1;
         update_post_meta($renewal_order_id, '_order_shipping', woocommerce_format_total($woocommerce->cart->shipping_total));
         update_post_meta($renewal_order_id, '_order_discount', woocommerce_format_total($woocommerce->cart->get_order_discount_total()));
         update_post_meta($renewal_order_id, '_cart_discount', woocommerce_format_total($woocommerce->cart->get_cart_discount_total()));
         update_post_meta($renewal_order_id, '_order_tax', woocommerce_format_total($woocommerce->cart->tax_total));
         update_post_meta($renewal_order_id, '_order_shipping_tax', woocommerce_format_total($woocommerce->cart->shipping_tax_total));
         update_post_meta($renewal_order_id, '_order_total', woocommerce_format_total($woocommerce->cart->total));
         update_post_meta($renewal_order_id, '_checkout_renewal', 'yes');
     } else {
         // If there are outstanding payment amounts, add them to the order, otherwise set the order details to the values of the recurring totals
         if ($outstanding_balance > 0 && 'yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_add_outstanding_balance', 'no')) {
             $failed_payment_multiplier = WC_Subscriptions_Order::get_failed_payment_count($original_order, $product_id);
         } else {
             $failed_payment_multiplier = 1;
         }
         // Set order totals based on recurring totals from the original order
         $cart_discount = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_discount_cart', true);
         $order_discount = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_discount_total', true);
         $order_shipping_tax = $failed_payment_multiplier * get_post_meta($original_order->id, '_order_recurring_shipping_tax_total', true);
         $order_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_tax', $order_tax);
         update_post_meta($renewal_order_id, '_order_total', $order_total);
     }
     // Set order taxes based on recurring taxes from the original order
     $recurring_order_taxes = WC_Subscriptions_Order::get_recurring_taxes($original_order);
     foreach ($recurring_order_taxes as $index => $recurring_order_tax) {
         if (function_exists('woocommerce_update_order_item_meta')) {
             // WC 2.0+
             $item_ids = array();
             $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_order_tax['name'], 'order_item_type' => 'tax'));
             // Also set recurring taxes on parent renewal orders
             if ('parent' == $args['new_order_role']) {
                 $item_ids[] = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $recurring_order_tax['name'], 'order_item_type' => 'recurring_tax'));
             }
             // Add line item meta
             foreach ($item_ids as $item_id) {
                 woocommerce_add_order_item_meta($item_id, 'compound', absint(isset($recurring_order_tax['compound']) ? $recurring_order_tax['compound'] : 0));
                 woocommerce_add_order_item_meta($item_id, 'tax_amount', woocommerce_clean($failed_payment_multiplier * $recurring_order_tax['tax_amount']));
                 woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($failed_payment_multiplier * $recurring_order_tax['shipping_tax_amount']));
                 if (isset($recurring_order_tax['rate_id'])) {
                     woocommerce_add_order_item_meta($item_id, 'rate_id', $recurring_order_tax['rate_id']);
                 }
                 if (isset($recurring_order_tax['label'])) {
                     woocommerce_add_order_item_meta($item_id, 'label', $recurring_order_tax['label']);
                 }
             }
         } else {
             // WC 1.x
             if (isset($recurring_order_tax['cart_tax']) && $recurring_order_tax['cart_tax'] > 0) {
                 $recurring_order_taxes[$index]['cart_tax'] = $failed_payment_multiplier * $recurring_order_tax['cart_tax'];
             } else {
                 $recurring_order_taxes[$index]['cart_tax'] = 0;
             }
             if (isset($recurring_order_tax['shipping_tax']) && $recurring_order_tax['shipping_tax'] > 0) {
                 $recurring_order_taxes[$index]['shipping_tax'] = $failed_payment_multiplier * $recurring_order_tax['shipping_tax'];
             } else {
                 $recurring_order_taxes[$index]['shipping_tax'] = 0;
             }
             // Inefficient but keeps WC 1.x code grouped together
             update_post_meta($renewal_order_id, '_order_taxes', $recurring_order_taxes);
         }
     }
     // Set line totals to be recurring line totals and remove the subscription/recurring related item meta from each order item
     $order_items = WC_Subscriptions_Order::get_recurring_items($original_order);
     // Allow extensions to add/remove items or item meta
     $order_items = apply_filters('woocommerce_subscriptions_renewal_order_items', $order_items, $original_order->id, $renewal_order_id, $product_id, $args['new_order_role']);
     foreach ($order_items as $item_index => $order_item) {
         $item_meta = new WC_Order_Item_Meta($order_item['item_meta']);
         // WC 2.0+ order item structure - as of WC 2.0 item_meta is stored as $key => meta pairs, not 'meta_name'/'meta_value'
         if (function_exists('woocommerce_add_order_item_meta')) {
             if ('child' == $args['new_order_role']) {
                 $renewal_order_item_name = sprintf(__('Renewal of "%s" purchased in Order %s', WC_Subscriptions::$text_domain), $order_item['name'], $original_order->get_order_number());
             } else {
                 $renewal_order_item_name = $order_item['name'];
             }
             // Create order line item on the renewal order
             $recurring_item_id = woocommerce_add_order_item($renewal_order_id, array('order_item_name' => $renewal_order_item_name, 'order_item_type' => 'line_item'));
             // Remove recurring line items and set item totals based on recurring line totals
             foreach ($item_meta->meta as $meta_key => $meta) {
                 // $meta is an array, so the item needs to be extracted from $meta[0] (just like order meta on a WC Order)
                 $meta_value = $meta[0];
                 // Map line item totals based on recurring line totals
                 switch ($meta_key) {
                     case '_recurring_line_total':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_total');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_total', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     case '_recurring_line_tax':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_tax');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_tax', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     case '_recurring_line_subtotal':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_subtotal');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_subtotal', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     case '_recurring_line_subtotal_tax':
                         woocommerce_delete_order_item_meta($recurring_item_id, '_line_subtotal_tax');
                         woocommerce_add_order_item_meta($recurring_item_id, '_line_subtotal_tax', woocommerce_format_decimal($failed_payment_multiplier * $meta_value));
                         break;
                     default:
                         break;
                 }
                 // Copy over line item meta data, with some parent/child role based exceptions for recurring amounts
                 $copy_to_renewal_item = true;
                 switch ($meta_key) {
                     case '_recurring_line_total':
                     case '_recurring_line_tax':
                     case '_recurring_line_subtotal':
                     case '_recurring_line_subtotal_tax':
                     case '_subscription_recurring_amount':
                     case '_subscription_sign_up_fee':
                     case '_subscription_period':
                     case '_subscription_interval':
                     case '_subscription_length':
                     case '_subscription_trial_period':
                         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;
                     default:
                         break;
                 }
                 // Copy existing item over to new recurring order item
                 if ($copy_to_renewal_item) {
                     woocommerce_add_order_item_meta($recurring_item_id, $meta_key, $meta_value);
                 }
             }
         } else {
             // WC 1.x order item structure
             foreach ($item_meta->meta as $meta_index => $meta_item) {
                 switch ($meta_item['meta_name']) {
                     case '_recurring_line_total':
                         $order_items[$item_index]['line_total'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_tax':
                         $order_items[$item_index]['line_tax'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_subtotal':
                         $order_items[$item_index]['line_subtotal'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_subtotal_tax':
                         $order_items[$item_index]['line_subtotal_tax'] = $failed_payment_multiplier * $meta_item['meta_value'];
                     case '_recurring_line_total':
                     case '_recurring_line_tax':
                     case '_recurring_line_subtotal':
                     case '_recurring_line_subtotal_tax':
                     case '_recurring_line_subtotal_tax':
                     case '_subscription_recurring_amount':
                     case '_subscription_sign_up_fee':
                     case '_subscription_period':
                     case '_subscription_interval':
                     case '_subscription_length':
                     case '_subscription_trial_length':
                     case '_subscription_trial_period':
                         if ('child' == $args['new_order_role']) {
                             unset($item_meta->meta[$meta_index]);
                         }
                         break;
                     case '_subscription_trial_length':
                         // We never want to duplicate free trials on renewal orders
                         if ('child' == $args['new_order_role']) {
                             unset($item_meta->meta[$meta_index]);
                         } else {
                             $item_meta->meta[$meta_index] = 0;
                         }
                         break;
                 }
                 if ('child' == $args['new_order_role']) {
                     $order_items[$item_index]['name'] = sprintf(__('Renewal of "%s" purchased in Order %s', WC_Subscriptions::$text_domain), $order_item['name'], $original_order->get_order_number());
                 }
                 $order_items[$item_index]['item_meta'] = $item_meta->meta;
             }
             // Save the item meta on the new order
             update_post_meta($renewal_order_id, '_order_items', $order_items);
         }
     }
     // Keep a record of the original order's ID on the renewal order
     update_post_meta($renewal_order_id, '_original_order', $original_order->id, true);
     // Code by soumya for restore the order price as product value
     $prev_recurring_price = $wpdb->get_row("SELECT order_item_id FROM wp_woocommerce_order_items WHERE order_id = {$original_order->id} AND order_item_type = 'line_item' LIMIT 0,1;");
     $recurring_price = woocommerce_get_order_item_meta($prev_recurring_price->order_item_id, '_subscription_recurring_amount', true);
     update_post_meta($original_order->id, '_order_recurring_total', $recurring_price);
     /**/
     $renewal_order = new WC_Order($renewal_order_id);
     if ('parent' == $args['new_order_role']) {
         WC_Subscriptions_Manager::process_subscriptions_on_checkout($renewal_order_id);
         $original_order->add_order_note(sprintf(__('Order superseded by Renewal Order %s.', WC_Subscriptions::$text_domain), $renewal_order->get_order_number()));
     }
     do_action('woocommerce_subscriptions_renewal_order_created', $renewal_order, $original_order, $product_id, $args['new_order_role']);
     return apply_filters('woocommerce_subscriptions_renewal_order_id', $renewal_order_id, $original_order, $product_id, $args['new_order_role']);
 }
 /**
  * Update recurring line taxes via AJAX
  * @see WC_Subscriptions_Order::calculate_recurring_line_taxes()
  * 
  * @since 4.4
  * @return JSON object with updated tax data
  */
 public static function ajax_update_recurring_tax()
 {
     global $wpdb;
     $woo_22_plus = version_compare(WOOCOMMERCE_VERSION, '2.2', '>=');
     check_ajax_referer('woocommerce-subscriptions', 'security');
     $order_id = absint($_POST['order_id']);
     $country = strtoupper(esc_attr($_POST['country']));
     // Step out of the way if the customer is not located in the US
     if ($country != 'US') {
         return;
     }
     $shipping = $_POST['shipping'];
     $line_subtotal = isset($_POST['line_subtotal']) ? esc_attr($_POST['line_subtotal']) : 0;
     $line_total = isset($_POST['line_total']) ? esc_attr($_POST['line_total']) : 0;
     // Set up WC_WooTax_Order object
     $order = self::get_order($order_id);
     // We only need to instantiate a WC_Tax object if we are using WooCommerce < 2.3
     if (!$woo_22_plus) {
         $tax = new WC_Tax();
     }
     $taxes = $shipping_taxes = array();
     $return = array();
     $item_data = array();
     $type_array = array();
     $product_id = '';
     if (isset($_POST['order_item_id'])) {
         $product_id = woocommerce_get_order_item_meta($_POST['order_item_id'], '_product_id');
     } elseif (isset($_POST['product_id'])) {
         $product_id = esc_attr($_POST['product_id']);
     }
     if (!empty($product_id) && WC_Subscriptions_Product::is_subscription($product_id)) {
         // Get product details
         $product = WC_Subscriptions::get_product($product_id);
         // Add product to items array
         $tic = get_post_meta($product->id, 'wootax_tic', true);
         $item_info = array('Index' => '', 'ItemID' => isset($_POST['order_item_id']) ? $_POST['order_item_id'] : $product_id, 'Qty' => 1, 'Price' => $line_subtotal > 0 ? $line_subtotal : $product->get_price(), 'Type' => 'cart');
         if (!empty($tic) && $tic) {
             $item_info['TIC'] = $tic;
         }
         $item_data[] = $item_info;
         $type_array[$_POST['order_item_id']] = 'cart';
         // Add shipping to items array
         if ($shipping > 0) {
             $item_data[] = array('Index' => '', 'ItemID' => WT_SHIPPING_ITEM, 'TIC' => WT_SHIPPING_TIC, 'Qty' => 1, 'Price' => $shipping, 'Type' => 'shipping');
             $type_array[WT_SHIPPING_ITEM] = 'shipping';
         }
         // Issue Lookup request
         $res = $order->do_lookup($item_data, $type_array, true);
         if (is_array($res)) {
             $return['recurring_shipping_tax'] = 0;
             $return['recurring_line_subtotal_tax'] = 0;
             $return['recurring_line_tax'] = 0;
             foreach ($res as $item) {
                 $item_id = $item->ItemID;
                 $item_tax = $item->TaxAmount;
                 if ($item_id == WT_SHIPPING_ITEM) {
                     $return['recurring_shipping_tax'] += $item_tax;
                 } else {
                     $return['recurring_line_subtotal_tax'] += $item_tax;
                     $return['recurring_line_tax'] += $item_tax;
                 }
             }
             $taxes[WT_RATE_ID] = $return['recurring_line_tax'];
             $shipping_taxes[WT_RATE_ID] = $return['recurring_shipping_tax'];
             // Get tax rates
             $tax_codes = array(WT_RATE_ID => apply_filters('wootax_rate_code', 'WOOTAX-RATE-DO-NOT-REMOVE'));
             // Remove old tax rows
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'recurring_tax' )", $order_id));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'recurring_tax'", $order_id));
             // Now merge to keep tax rows
             ob_start();
             foreach (array_keys($taxes + $shipping_taxes) as $key) {
                 $item = array();
                 $item['rate_id'] = $key;
                 $item['name'] = $tax_codes[$key];
                 $item['label'] = $woo_22_plus ? WC_Tax::get_rate_label($key) : $tax->get_rate_label($key);
                 $item['compound'] = $woo_22_plus ? WC_Tax::is_compound($key) : $tax->is_compound($key) ? 1 : 0;
                 $item['tax_amount'] = wc_round_tax_total(isset($taxes[$key]) ? $taxes[$key] : 0);
                 $item['shipping_tax_amount'] = wc_round_tax_total(isset($shipping_taxes[$key]) ? $shipping_taxes[$key] : 0);
                 if (!$item['label']) {
                     $item['label'] = WC()->countries->tax_or_vat();
                 }
                 // Add line item
                 $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'recurring_tax'));
                 // Add line item meta
                 if ($item_id) {
                     woocommerce_add_order_item_meta($item_id, 'rate_id', $item['rate_id']);
                     woocommerce_add_order_item_meta($item_id, 'label', $item['label']);
                     woocommerce_add_order_item_meta($item_id, 'compound', $item['compound']);
                     woocommerce_add_order_item_meta($item_id, 'tax_amount', $item['tax_amount']);
                     woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', $item['shipping_tax_amount']);
                 }
                 include plugin_dir_path(WC_Subscriptions::$plugin_file) . 'templates/admin/post-types/writepanels/order-tax-html.php';
             }
             $return['tax_row_html'] = ob_get_clean();
             echo json_encode($return);
         }
     }
     die;
 }
Exemplo n.º 8
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;
}
 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));
         }
     }
 }
Exemplo n.º 10
0
) );
$odr = $customer_orders[0]->ID;
*/
$cur_user_subscription = get_user_meta(get_current_user_id(), 'wp_woocommerce_subscriptions', true);
foreach ($cur_user_subscription as $suk => $suv) {
    //$subscriptionID = $suv['order_id'] . '_' . $suv['product_id'];
    $subscriptionID = $suk;
    $odr = $suv['order_id'];
    $f____d = date_i18n('l', strtotime($suv['start_date']));
    break;
    /* use because one time subscription */
}
/* Fetch Oder Details */
$srOW = $wpdb->get_row("select * FROM wp_woocommerce_order_items WHERE order_id = " . $odr);
$mealOrder = woocommerce_get_order_item_meta($srOW->order_item_id, 'Servings:', true);
$mealTotal = woocommerce_get_order_item_meta($srOW->order_item_id, '_recurring_line_subtotal', true);
/**/
/* Get user Joining Information */
global $current_user;
get_currentuserinfo();
$user_join_date = $current_user->user_registered;
$user_join_date = explode(' ', $user_join_date);
$user_join_date = str_replace('-', '', $user_join_date[0]);
/***/
$dd = explode(' ', get_post_meta($odr, 'Delivery Date', true));
$dd = explode('/', $dd[0]);
$dd[2] = '20' . $dd[2];
$temp = $dd[0];
$dd[0] = $dd[2];
$dd[2] = $temp;
$temp = $dd[1];
Exemplo n.º 11
0
 /**
  * Send emails that are in the email queue
  */
 public static function send_emails()
 {
     global $wpdb, $woocommerce;
     global $sfnFollowUpEmails;
     // get start and end times
     $to = current_time('timestamp');
     $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}followup_email_orders` WHERE `is_sent` = 0 AND `send_on` <= %s", $to));
     foreach ($results as $email_order) {
         $sfn_report = array();
         $user_id = 0;
         if (!$email_order->email_id || $email_order->email_id == 0) {
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}followup_email_orders WHERE id = %d", $email_order->id));
             continue;
         }
         $email = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}followup_emails` WHERE `id` = '%d'", $email_order->email_id));
         // allow other extensions to "skip" sending this email
         $skip = apply_filters('fue_skip_email_sending', false, $email, $email_order);
         if ($skip) {
             continue;
         }
         if ($email_order->order_id != 0) {
             // order
             $order = new WC_Order($email_order->order_id);
             // if this is an "Order Status" email, make sure that the order is still
             // in the same status as the one it was originally intended for
             // e.g. Do not send "on-hold" order status emails if the order status has
             // been changed to "completed" before sending the email
             $order_statuses_array = (array) get_terms('shop_order_status', array('hide_empty' => 0, 'orderby' => 'id'));
             $all_statuses = array();
             foreach ($order_statuses_array as $status) {
                 $all_statuses[] = $status->slug;
             }
             if (in_array($email->interval_type, $all_statuses) && $email->interval_type !== $order->status) {
                 // order status looks to have been changed already
                 $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}followup_email_orders WHERE id = %d AND is_sent = 0", $email_order->id));
                 continue;
             }
             if (isset($order->user_id) && $order->user_id > 0) {
                 $user_id = $order->user_id;
                 $wp_user = new WP_User($order->user_id);
                 $email_to = $wp_user->user_email;
                 $first_name = $wp_user->first_name;
                 $last_name = $wp_user->last_name;
                 $cname = $first_name . ' ' . $last_name;
             } else {
                 $email_to = $order->billing_email;
                 $first_name = $order->billing_first_name;
                 $last_name = $order->billing_last_name;
             }
             $cname = $first_name . ' ' . $last_name;
             $order_date = date(get_option('date_format'), strtotime($order->order_date));
             $order_datetime = date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($order->order_date));
         } else {
             $order_date = '';
             $order_datetime = '';
             if ($email->email_type == 'manual') {
                 $meta = maybe_unserialize($email_order->meta);
                 $email_to = $meta['email_address'];
                 $order = false;
             } else {
                 $order = false;
                 $user_id = $email_order->user_id;
                 $wp_user = new WP_User($email_order->user_id);
                 $email_to = $wp_user->user_email;
                 $first_name = $wp_user->first_name;
                 $last_name = $wp_user->last_name;
                 $cname = $first_name . ' ' . $last_name;
                 if (empty($first_name) && empty($last_name)) {
                     $first_name = $wp_user->user_nicename;
                     $cname = $wp_user->user_nicename;
                 }
                 // non-order related email. make sure user is not opted-out
                 $opt_out = get_user_meta($email_order->user_id, 'wcfu_opted_out', true);
                 $opt_out = apply_filters('fue_user_opt_out', $opt_out, $email_order->user_id);
                 if ($opt_out) {
                     // user opted out, delete this email_order
                     $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}followup_email_orders WHERE `id` = %d", $email_order->id));
                     continue;
                 }
             }
         }
         // check if the email address is on the excludes list
         $sql = $wpdb->prepare("SELECT COUNT(*) FROM `{$wpdb->prefix}followup_email_excludes` WHERE `email` = '%s'", $email_to);
         if ($wpdb->get_var($sql) > 0) {
             // delete and go to the next entry
             do_action('fue_email_excluded', $email_to, $email_order->id);
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}followup_email_orders WHERE `id` = %d", $email_order->id));
             continue;
         }
         if ($email->email_type == 'generic') {
             if ($order) {
                 $used_cats = array();
                 $item_list = '<ul>';
                 $item_cats = '<ul>';
                 $items = $order->get_items();
                 foreach ($items as $item) {
                     $item_id = isset($item['product_id']) ? $item['product_id'] : $item['id'];
                     $item_list .= apply_filters('fue_email_item_list', '<li><a href="' . self::create_email_url($email_order->id, $email->id, $user_id, $email_to, get_permalink($item_id)) . '">' . get_the_title($item_id) . '</a></li>', $email_order->id, $item);
                     $cats = get_the_terms($item_id, 'product_cat');
                     if (is_array($cats) && !empty($cats)) {
                         foreach ($cats as $cat) {
                             if (!in_array($cat->term_id, $used_cats)) {
                                 $item_cats .= apply_filters('fue_email_cat_list', '<li>' . $cat->name . '</li>', $email_order->id, $cat);
                             }
                         }
                     }
                 }
                 $item_list .= '</ul>';
                 $item_cats .= '</ul>';
             } else {
                 $item_list = '';
                 $item_cats = '';
             }
         } else {
             if (!empty($email_order->product_id)) {
                 $item = sfn_get_product($email_order->product_id);
                 $cats = get_the_terms($item->id, 'product_cat');
                 $categories = '';
                 if (is_array($cats) && !empty($cats)) {
                     foreach ($cats as $cat) {
                         $categories .= $cat->name . ', ';
                     }
                     $categories = rtrim($categories, ', ');
                 }
             } else {
             }
         }
         // process variable replacements
         $tracking = $email->tracking_code;
         $codes = array();
         if (!empty($tracking)) {
             parse_str($tracking, $codes);
             foreach ($codes as $key => $val) {
                 $codes[$key] = urlencode($val);
             }
         }
         $store_url = home_url();
         $store_name = get_bloginfo('name');
         $page_id = woocommerce_get_page_id('followup_unsubscribe');
         $unsubscribe = add_query_arg('wcfu', $email_to, get_permalink($page_id));
         // convert urls
         $store_url = self::create_email_url($email_order->id, $email->id, $user_id, $email_to, $store_url);
         $unsubscribe = self::create_email_url($email_order->id, $email->id, $user_id, $email_to, $unsubscribe);
         if (!empty($codes)) {
             $store_url = add_query_arg($codes, $store_url);
             $unsubscribe = add_query_arg($codes, $unsubscribe);
         }
         $order_id = '';
         if (0 != $email_order->order_id) {
             $order_id = apply_filters('woocommerce_order_number', $email_order->order_id, $order);
         }
         $subject = $email->subject;
         $message = $email->message;
         if ($email->email_type == 'generic') {
             /* Code by soumya */
             /* Get order Total */
             $order_t = get_post_meta($email_order->order_id, '_order_total', true);
             if (empty($order_t)) {
                 $order_t = 0;
             }
             $order_t = '$' . $order_t;
             /** get servings details **/
             $srOW = $wpdb->get_row("select * FROM wp_woocommerce_order_items WHERE order_id = " . $email_order->order_id);
             $mealOrder_serving = woocommerce_get_order_item_meta($srOW->order_item_id, 'Servings:', true);
             /* get delivery date */
             $order_dd = get_post_meta($email_order->order_id, 'Delivery Date', true);
             if (empty($order_dd)) {
                 $order_dd = '';
             }
             $vars = array('{order_number}', '{order_date}', '{order_datetime}', '{store_url}', '{store_name}', '{customer_first_name}', '{customer_name}', '{customer_email}', '{item_names}', '{item_categories}', '{unsubscribe_url}', '{order_total}', '{order_delivery_date}', '{order_servings}');
             $reps = array($order_id, $order_date, $order_datetime, $store_url, $store_name, $first_name, $first_name . ' ' . $last_name, $email_to, $item_list, $item_cats, $unsubscribe, $order_t, $order_dd, $mealOrder_serving);
         } elseif ($email->email_type == 'signup') {
             $vars = array('{store_url}', '{store_name}', '{customer_first_name}', '{customer_name}', '{customer_email}', '{unsubscribe_url}');
             $reps = array($store_url, $store_name, $first_name, $cname, $email_to, $unsubscribe);
         } elseif ($email->email_type == 'customer') {
             if ($user_id > 0) {
                 $customer = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}followup_customers WHERE user_id = %d", $user_id));
                 $spent_order = woocommerce_price($order->order_total);
                 $spent_total = woocommerce_price($customer->total_purchase_price);
                 $num_orders = $customer->total_orders;
                 $last_order_date = $wpdb->get_var($wpdb->prepare("SELECT p.post_date FROM {$wpdb->posts} p, {$wpdb->prefix}followup_customer_orders co WHERE co.followup_customer_id = %d AND co.order_id = p.ID AND p.post_status = 'publish' ORDER BY p.ID DESC LIMIT 1", $user_id));
                 $last_purchase = date(get_option('date_format'), strtotime($last_order_date));
             } else {
                 $customer = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}followup_customers WHERE email_address = %s", $email_to));
                 $spent_order = woocommerce_price($order->order_total);
                 $spent_total = woocommerce_price($customer->total_purchase_price);
                 $num_orders = $customer->total_orders;
                 $last_order_date = $wpdb->get_var($wpdb->prepare("SELECT p.post_date FROM {$wpdb->posts} p, {$wpdb->postmeta} pm WHERE pm.meta_key = '_billing_email' AND pm.meta_value = %d AND pm.post_id = p.ID AND p.post_status = 'publish' ORDER BY p.ID DESC LIMIT 1", $email_to));
                 $last_purchase = date(get_option('date_format'), strtotime($last_order_date));
             }
             $vars = array('{order_number}', '{order_date}', '{order_datetime}', '{store_url}', '{store_name}', '{customer_first_name}', '{customer_name}', '{customer_email}', '{unsubscribe_url}', '{dollars_spent_order}', '{dollars_spent_total}', '{number_orders}', '{last_purchase_date}');
             $reps = array($order_id, $order_date, $order_datetime, $store_url, $store_name, $first_name, $first_name . ' ' . $last_name, $email_to, $unsubscribe, $spent_order, $spent_total, $num_orders, $last_purchase);
         } elseif ($email->email_type == 'manual') {
             $meta = maybe_unserialize($email_order->meta);
             $store_url = home_url();
             $store_name = get_bloginfo('name');
             $page_id = woocommerce_get_page_id('followup_unsubscribe');
             $unsubscribe = add_query_arg('wcfu', $email_to, get_permalink($page_id));
             // convert urls
             $store_url = self::create_email_url($email_order->id, $email->id, $user_id, $email_to, $store_url);
             $unsubscribe = self::create_email_url($email_order->id, $email->id, $user_id, $email_to, $unsubscribe);
             if (!empty($codes)) {
                 $store_url = add_query_arg($codes, $store_url);
                 $unsubscribe = add_query_arg($codes, $unsubscribe);
             }
             $names = explode(' ', $meta['user_name']);
             $first_name = isset($names[0]) ? $names[0] : $meta['user_name'];
             $vars = array('{store_url}', '{store_name}', '{customer_first_name}', '{customer_name}', '{customer_email}', '{unsubscribe_url}');
             $reps = array($store_url, $store_name, $first_name, $meta['user_name'], $email_to, $unsubscribe);
             $subject = $meta['subject'];
             $message = $meta['message'];
         } else {
             $item_url = self::create_email_url($email_order->id, $email->id, $user_id, $email_to, get_permalink($item->id));
             if (!empty($codes)) {
                 add_query_arg($codes, $item_url);
             }
             $order_id = '';
             if (0 != $email_order->order_id) {
                 $order_id = apply_filters('woocommerce_order_number', $email_order->order_id, $order);
             }
             /* Code by soumya */
             /* Get order Total */
             $order_t = get_post_meta($email_order->order_id, '_order_total', true);
             if (empty($order_t)) {
                 $order_t = 0;
             }
             $order_t = '$' . $order_t;
             /** get servings details **/
             $srOW = $wpdb->get_row("select * FROM wp_woocommerce_order_items WHERE order_id = " . $email_order->order_id);
             $mealOrder_serving = woocommerce_get_order_item_meta($srOW->order_item_id, 'Servings:', true);
             /* get delivery date */
             $order_dd = get_post_meta($email_order->order_id, 'Delivery Date', true);
             if (empty($order_dd)) {
                 $order_dd = '';
             }
             $vars = array('{order_number}', '{order_date}', '{order_datetime}', '{store_url}', '{store_name}', '{customer_first_name}', '{customer_name}', '{customer_email}', '{item_name}', '{item_category}', '{unsubscribe_url}', '{order_total}', '{order_delivery_date}', '{order_servings}');
             $reps = array($order_id, $order_date, $order_datetime, $store_url, $store_name, $first_name, $first_name . ' ' . $last_name, $email_to, '<a href="' . $item_url . '">' . get_the_title($item->id) . '</a>', $categories, $unsubscribe, $order_t, $order_dd, $mealOrder_serving);
             /* soumya code ended */
             /*      $vars       = array('{order_number}', '{order_date}', '{order_datetime}', '{store_url}', '{store_name}', '{customer_first_name}', '{customer_name}', '{customer_email}', '{item_name}', '{item_category}', '{unsubscribe_url}');
                             $reps       = array(
                                 $order_id,
                                 $order_date,
                                 $order_datetime,
                                 $store_url,
                                 $store_name,
                                 $first_name,
                                 $first_name .' '. $last_name,
                                 $email_to,
                                 '<a href="'. $item_url .'">'. get_the_title($item->id) .'</a>',
                                 $categories,
                                 $unsubscribe
                             );
             			*/
         }
         //$email->message = self::url_to_links( $email->message, $email_order->id, $email->id, $user_id, $email_to );
         if ($email_order->order_id > 0 && $email->email_type == 'reminder') {
             // count the total emails and the number of sent emails
             $total_emails = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}followup_email_orders WHERE order_id = %d AND email_id = %d", $email_order->order_id, $email->id));
             $sent_emails = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}followup_email_orders WHERE order_id = %d AND email_id = %d AND is_sent = 1", $email_order->order_id, $email->id));
             if ($total_emails == 1) {
                 $messages = self::str_search('{first_email}', '{/first_email}', $message);
                 if (empty($messages)) {
                     continue;
                 }
                 $message = $messages[0];
             } elseif ($total_emails == 2) {
                 if ($sent_emails == 0) {
                     $messages = self::str_search('{first_email}', '{/first_email}', $message);
                     if (empty($messages)) {
                         continue;
                     }
                     $message = $messages[0];
                 } else {
                     $messages = self::str_search('{final_email}', '{/final_email}', $message);
                     if (empty($messages)) {
                         continue;
                     }
                     $message = $messages[0];
                 }
             } else {
                 if ($sent_emails == 0) {
                     $messages = self::str_search('{first_email}', '{/first_email}', $message);
                     if (empty($messages)) {
                         continue;
                     }
                     $message = $messages[0];
                 } elseif ($sent_emails == $total_emails - 1) {
                     $messages = self::str_search('{final_email}', '{/final_email}', $message);
                     if (empty($messages)) {
                         continue;
                     }
                     $message = $messages[0];
                 } else {
                     $messages = self::str_search('{quantity_email}', '{/quantity_email}', $message);
                     if (empty($messages)) {
                         continue;
                     }
                     $message = $messages[0];
                 }
             }
         }
         $subject = apply_filters('fue_email_subject', $subject, $email, $email_order);
         $message = apply_filters('fue_email_message', $message, $email, $email_order);
         $subject = strip_tags(str_replace($vars, $reps, $subject));
         $message = str_replace($vars, $reps, $message);
         // hook to variable replacement
         $subject = apply_filters('fue_send_email_subject', $subject, $email_order);
         $message = apply_filters('fue_send_email_message', $message, $email_order);
         // look for custom fields
         $message = preg_replace_callback('|\\{cf ([0-9]+) ([^}]*)\\}|', 'fue_add_custom_fields', $message);
         // look for post id
         $message = preg_replace_callback('|\\{post_id=([^}]+)\\}|', 'fue_add_post', $message);
         // look for links
         $replacer = new FUE_Link_Replacement($email_order->id, $email->id, $user_id, $email_to);
         $message = preg_replace_callback('|\\{link url=([^}]+)\\}|', array($replacer, 'replace'), $message);
         // look for store_url with path
         $sfnFollowUpEmails->link_meta = array('email_order_id' => $email_order->id, 'email_id' => $email->id, 'user_id' => $user_id, 'user_email' => $email_to, 'codes' => $codes);
         $message = preg_replace_callback('|\\{store_url=([^}]+)\\}|', 'FUE::add_store_url', $message);
         do_action('fue_before_email_send', $subject, $message, $email_order);
         // send the email
         $disable_wrap = get_option('fue_disable_wrapping', 0);
         $mailer = $woocommerce->mailer();
         if (!$disable_wrap) {
             $message = $mailer->wrap_message($subject, $message);
         }
         $mailer->send($email_to, $subject, $message);
         $oid = $order ? $email_order->order_id : 0;
         if ($email->email_type == 'manual') {
             $email_trigger = __('Manual Email', 'wc_followup_emails');
         } else {
             if ($email->interval_type == 'date') {
                 $email_trigger = sprintf(__('Send on %s'), $email->send_date . ' ' . $email->send_date_hour . ':' . $email->send_date_minute);
             } elseif ($email->interval_type == 'signup') {
                 $email_trigger = sprintf(__('%d %s after user signs up', 'wc_followup_emails'), $email->interval_num, $email->interval_duration);
             } else {
                 $email_trigger = sprintf(__('%d %s %s'), $email->interval_num, $email->interval_duration, SFN_FollowUpEmails::get_trigger_name($email->interval_type));
             }
         }
         $email_trigger = apply_filters('fue_interval_str', $email_trigger, $email);
         do_action('fue_after_email_sent', $subject, $message, $email_order);
         do_action('fue_email_sent_details', $email_order, $email_order->user_id, $email, $email_to, $cname, $email_trigger);
         // increment usage count
         $wpdb->query($wpdb->prepare("UPDATE `{$wpdb->prefix}followup_emails` SET `usage_count` = `usage_count` + 1 WHERE `id` = %d", $email->id));
         // update the email order
         $now = date('Y-m-d H:i:s');
         $wpdb->query($wpdb->prepare("UPDATE `{$wpdb->prefix}followup_email_orders` SET `is_sent` = 1, `date_sent` = %s, `email_trigger` = %s WHERE `id` = %d", $now, $email_trigger, $email_order->id));
         do_action('fue_email_order_sent', $email_order->id);
     }
 }
 /**
  * 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_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' => $woocommerce->cart->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()->cart->tax->get_rate_label($tax_key));
                 wc_add_order_item_meta($item_id, 'compound', absint(WC()->cart->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) {
                     $item_id = woocommerce_get_order_item_meta($order_id, array('order_item_name' => $code, 'order_item_type' => 'coupon'));
                     // Add line item meta
                     if ($item_id) {
                         woocommerce_add_order_item_meta($item_id, 'recurring_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));
                             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) {
                     wc_delete_order_item($order_item_id);
                 }
             }
         } 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);
         }
     }
 }