function bepro_listings_save($post_id = false, $return_post_id = false)
{
    global $wpdb;
    if (!empty($_POST["save_bepro_listing"])) {
        //get settings
        $wp_upload_dir = wp_upload_dir();
        $data = get_option("bepro_listings");
        $user_data = wp_get_current_user();
        $default_user_id = $data["default_user_id"];
        $success_message = $data["success_message"];
        $num_images = $data["num_images"];
        $query_type = $data["map_query_type"];
        $default_status = empty($data["default_status"]) ? "pending" : $data["default_status"];
        $return_message = false;
        $item_name = $wpdb->escape($_POST["item_name"]);
        $content = $wpdb->escape(strip_tags($_POST["content"]));
        $categories = $wpdb->escape($_POST["categories"]);
        $username = $wpdb->escape(strip_tags($_POST["username"]));
        $password = $wpdb->escape(strip_tags($_POST["password"]));
        $post_id = empty($post_id) ? $wpdb->escape($_POST["bepro_post_id"]) : $post_id;
        $cost = trim(addslashes(strip_tags($_POST["cost"])));
        $cost = str_replace(array("\$", ","), array("", ""), $cost);
        $cost = !is_numeric($cost) || $cost < 0 ? "NULL" : $cost;
        //Figure out user_id
        if (is_user_logged_in()) {
            $user_id = $user_data->ID;
        } elseif (isset($username) && !empty($password)) {
            $user_id = wp_create_user($username, $password, $email);
        }
        if (empty($user_id)) {
            $user_id = $default_user_id;
        }
        $user_id = apply_filters("bl_save_listing_user_id_overide", $user_id);
        if (!empty($user_id) && $user_id != 0) {
            if (empty($post_id)) {
                $post = array('post_author' => $user_id, 'post_content' => $content, 'post_status' => $default_status, 'post_title' => $item_name, 'post_type' => "bepro_listings");
                //Create post
                $post_id = wp_insert_post($post, $wp_error);
            } else {
                if (!is_admin()) {
                    $wpdb->query("UPDATE " . $wpdb->prefix . "posts SET post_content = '" . $content . "' WHERE ID=" . $post_id);
                }
            }
            if (empty($wp_error)) {
                $post_data = get_post($post_id);
                //setup custom bepro listing post categories
                if (!empty($categories)) {
                    wp_set_post_terms($post_id, $categories, 'bepro_listing_types');
                }
                //setup post images
                if ($num_images) {
                    //delete images
                    $counter = 0;
                    while ($counter < $num_images) {
                        if (is_numeric($_POST["delete_image_" . $counter]) && $post_data->post_author == $user_data->ID) {
                            wp_delete_attachment($_POST["delete_image_" . $counter], true);
                        }
                        $counter++;
                    }
                    $counter = 1;
                    $attachments = get_children(array('post_parent' => $post_id));
                    if (!function_exists("wp_generate_attachment_metadata")) {
                        require ABSPATH . 'wp-admin/includes/image.php';
                    }
                    if (!function_exists("media_upload_tabs")) {
                        require ABSPATH . 'wp-admin/includes/media.php';
                    }
                    while ($counter <= $num_images && count($attachments) <= $num_images) {
                        if (!empty($_FILES["bepro_form_image_" . $counter]) && !$_FILES["bepro_form_image_" . $counter]["error"]) {
                            $full_filename = $wp_upload_dir['path'] . "/" . $_FILES["bepro_form_image_" . $counter]["name"];
                            $check_move = @move_uploaded_file($_FILES["bepro_form_image_" . $counter]["tmp_name"], $full_filename);
                            if ($check_move) {
                                $filename = basename($_FILES["bepro_form_image_" . $counter]["name"]);
                                $filename = preg_replace('/\\.[^.]+$/', '', $filename);
                                $wp_filetype = wp_check_filetype(basename($full_filename), null);
                                $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => $filename, 'post_content' => '', 'post_status' => 'inherit');
                                $attach_id = wp_insert_attachment($attachment, $full_filename, $post_id);
                                $attach_data = wp_generate_attachment_metadata($attach_id, $full_filename);
                                wp_update_attachment_metadata($attach_id, $attach_data);
                                if ($counter == 1) {
                                    update_post_meta($post_id, '_thumbnail_id', $attach_id);
                                }
                            }
                        }
                        $counter++;
                    }
                }
                //manage lat/lon
                if (is_numeric($_POST['lat']) && is_numeric($_POST['lon'])) {
                    $lat = $_POST['lat'];
                    $lon = $_POST['lon'];
                } else {
                    $latlon = get_bepro_lat_lon();
                    $lat = $latlon["lat"];
                    $lon = $latlon["lon"];
                }
                $post_data = $_POST;
                $post_data["post_id"] = $post_id;
                $post_data["lat"] = $lat;
                $post_data["lon"] = $lon;
                $post_data["cost"] = $cost;
                $listing = $wpdb->get_row("SELECT id FROM " . $wpdb->prefix . BEPRO_LISTINGS_TABLE_NAME . " WHERE post_id =" . $post_id);
                if ($listing) {
                    $result = bepro_update_post($post_data);
                } else {
                    $result = bepro_add_post($post_data);
                }
                if (!$wp_error) {
                    $return_message = true;
                } else {
                    $return_message = false;
                }
            }
        } else {
            $return_message = false;
        }
    }
    if ($return_post_id) {
        return $post_id;
    }
    return $return_message;
}
function bepro_listings_save($post_id = false, $return_post_id = false)
{
    global $wpdb;
    if (!empty($_POST["save_bepro_listing"])) {
        //tie in for custom and addon error checking
        $check = apply_filters("scan_incoming_bl_listing", array());
        if (@$check && !empty($check)) {
            return false;
        }
        //get settings
        $wp_upload_dir = wp_upload_dir();
        $data = get_option("bepro_listings");
        $user_data = wp_get_current_user();
        $default_user_id = $data["default_user_id"];
        $success_message = $data["success_message"];
        $num_images = $data["num_images"];
        $query_type = $data["map_query_type"];
        $default_status = empty($data["default_status"]) ? "pending" : $data["default_status"];
        $return_message = false;
        //retrieve variables
        $item_name = addslashes(strip_tags($_POST["item_name"]));
        $content = is_admin() && is_user_logged_in() ? $_POST["content"] : addslashes(strip_tags(strip_shortcodes($_POST["content"])));
        $categories = $wpdb->escape($_POST["categories"]);
        $username = $wpdb->escape(strip_tags($_POST["username"]));
        $password = $wpdb->escape(strip_tags($_POST["password"]));
        $email = $wpdb->escape(strip_tags($_POST["email"]));
        $post_id = empty($post_id) ? $wpdb->escape($_POST["bepro_post_id"]) : $post_id;
        $cost = trim(addslashes(strip_tags($_POST["cost"])));
        $cost = str_replace(array("\$", ","), array("", ""), $cost);
        $cost = !is_numeric($cost) || $cost < 0 ? "NULL" : $cost;
        $duration = 0;
        $fee = 0;
        //Figure out user_id
        if (is_user_logged_in()) {
            $user_id = $user_data->ID;
        } elseif (isset($username) && !empty($password)) {
            $user_id = wp_create_user($username, $password, $email);
            if (is_numeric($user_id)) {
                wp_set_current_user($user_id);
            }
        }
        if (empty($user_id)) {
            $user_id = $default_user_id;
        }
        $user_id = apply_filters("bl_save_listing_user_id_overide", $user_id);
        //create listing in wordpress
        if (!empty($user_id) && $user_id != 0) {
            //Check for the post_id and create one if we don't have a valid one
            $new_post = false;
            if (empty($post_id)) {
                $new_post = true;
            }
            if (get_post($post_id)) {
                $wpdb->query("UPDATE " . $wpdb->prefix . "posts SET post_content = '" . $content . "' WHERE ID=" . $post_id);
            } else {
                $new_post = true;
            }
            //if post_id is empty or wasn't found then create a new one
            if ($new_post) {
                $post = array('post_author' => $user_id, 'post_content' => $content, 'post_status' => $default_status, 'post_title' => $item_name, 'post_type' => "bepro_listings");
                //Create post
                $post_id = wp_insert_post($post, $wp_error);
            }
            //once we figured out a post_id then proceed
            if (empty($wp_error) && is_numeric($post_id)) {
                $post_data = get_post($post_id);
                /*
                	//setup custom bepro listing post categories
                	1. If we get category names instead of ID's then we need to find the id's or create them
                	2. Once we have an array of category ID's, we can assign them to the current listing
                */
                if (!is_array($categories) && !empty($categories)) {
                    $categories = explode(",", $categories);
                    if (!is_numeric($categories[0])) {
                        $cat_array = array();
                        foreach ($categories as $category) {
                            $check_cat = wp_insert_term($category, "bepro_listing_types");
                            if (is_array($check_cat) && !isset($check_cat["errors"])) {
                                $cat_array[] = $check_cat["term_id"];
                            } elseif (is_wp_error($check_cat)) {
                                $cat = get_term_by("name", $category, "bepro_listing_types");
                                $cat_array[] = $cat->term_id;
                            }
                        }
                        $categories = $cat_array;
                    }
                }
                if (!empty($categories)) {
                    wp_set_post_terms($post_id, $categories, 'bepro_listing_types');
                }
                //setup post images
                if ($num_images) {
                    //delete images
                    $counter = 0;
                    while ($counter < $num_images) {
                        if (is_numeric($_POST["delete_image_" . $counter]) && $post_data->post_author == $user_data->ID) {
                            wp_delete_attachment($_POST["delete_image_" . $counter], true);
                        }
                        $counter++;
                    }
                    $counter = 1;
                    $attachments = get_children(array('post_parent' => $post_id));
                    if (!function_exists("wp_generate_attachment_metadata")) {
                        require ABSPATH . 'wp-admin/includes/image.php';
                    }
                    if (!function_exists("media_upload_tabs")) {
                        require ABSPATH . 'wp-admin/includes/media.php';
                    }
                    while ($counter <= $num_images && count($attachments) <= $num_images) {
                        if (!empty($_FILES["bepro_form_image_" . $counter]) && !$_FILES["bepro_form_image_" . $counter]["error"]) {
                            $full_filename = $wp_upload_dir['path'] . "/" . $_FILES["bepro_form_image_" . $counter]["name"];
                            $check_move = @move_uploaded_file($_FILES["bepro_form_image_" . $counter]["tmp_name"], $full_filename);
                            if ($check_move) {
                                $filename = basename($_FILES["bepro_form_image_" . $counter]["name"]);
                                $filename = preg_replace('/\\.[^.]+$/', '', $filename);
                                $wp_filetype = wp_check_filetype(basename($full_filename), null);
                                $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => $filename, 'post_content' => '', 'post_status' => 'inherit');
                                $attach_id = wp_insert_attachment($attachment, $full_filename, $post_id);
                                $attach_data = wp_generate_attachment_metadata($attach_id, $full_filename);
                                wp_update_attachment_metadata($attach_id, $attach_data);
                                if ($counter == 1) {
                                    update_post_meta($post_id, '_thumbnail_id', $attach_id);
                                }
                            }
                        }
                        $counter++;
                    }
                    if (!empty($data["show_imgs"])) {
                        BL_Meta_Box_Listing_Images::save($post_id, $post_after);
                    }
                }
                //manage lat/lon
                if (is_numeric($_POST['lat']) && is_numeric($_POST['lon'])) {
                    $lat = $_POST['lat'];
                    $lon = $_POST['lon'];
                } else {
                    $latlon = get_bepro_lat_lon();
                    if (sizeof($latlon) > 0) {
                        $lat = $latlon["lat"];
                        $lon = $latlon["lon"];
                    }
                }
                //prepare for save to BePro Listings tables
                $listing = bpl_get_listing_by_post_id($post_id);
                $post_status = $post_data->post_status;
                $post_data = $_POST;
                $post_data["post_id"] = $post_id;
                $post_data["lat"] = @$lat;
                $post_data["lon"] = @$lon;
                $post_data["cost"] = $cost;
                $package_id = is_numeric($_POST["bpl_package"]) ? $_POST["bpl_package"] : "";
                $bl_order_id = "";
                /*
                	Figuring out payment stuff if applicable to this listing.
                */
                //calculate cost and duration
                if (is_numeric($data["require_payment"]) && $data["require_payment"] > 0) {
                    //Get package cost and duration
                    if (!empty($data["require_payment"]) && $data["require_payment"] == 1) {
                        //if category already has an order ID then reuse it
                        if (@$listing && $listing->bl_order_id) {
                            $bl_order_id = $listing->bl_order_id;
                        } else {
                            $bl_order_id = bl_get_vacant_order_id($user_id, $data["require_payment"]);
                        }
                        //calculate for categories
                        $fee = bepro_get_total_cat_cost($post_id);
                        $duration = $data["cat_fee_duration"];
                        //If there is no cost but there is a duration set, then set the duration
                        if (@is_numeric($duration) && $duration != 0 && (!$fee || $fee == 0)) {
                            $expires = date('Y-m-d H:i:s', strtotime("+" . $duration . " days"));
                        }
                        bl_create_payment_order(array("bl_order_id" => $bl_order_id, "feature_id" => $post_id, "cust_user_id" => $user_id, "feature_type" => 1, "status" => 2, "expires" => $expires));
                    } else {
                        if (is_numeric($package_id) && !empty($data["require_payment"]) && $data["require_payment"] == 2) {
                            $pay_fee = true;
                            $status = 2;
                            // post status
                            //if we already created an order ID lets make some checks
                            if (@$listing && $listing->bl_order_id) {
                                $order = bl_get_payment_order($listing->bl_order_id);
                                //check order to see if its the same package selected
                                if (@$order->feature_id == $package_id) {
                                    $bl_order_id = $listing->bl_order_id;
                                    //set this listng as published since its paid
                                    if ($order->status == 1 && !empty($data["publish_after_payment"])) {
                                        remove_action('post_updated', "bepro_admin_save_details");
                                        wp_update_post(array("ID" => $post_id, "post_status" => "publish"));
                                        remove_action('post_updated', "bepro_admin_save_details");
                                        $pay_fee = false;
                                    }
                                } else {
                                    //go find/create a new order ID capable of accomodating this request
                                    $bl_order_id = bl_get_vacant_order_id($user_id, $data["require_payment"], $package_id);
                                }
                            } else {
                                $bl_order_id = bl_get_vacant_order_id($user_id, $data["require_payment"], $package_id);
                                $order = bl_get_payment_order($bl_order_id);
                                if ($order->status == 1 && !empty($data["publish_after_payment"])) {
                                    remove_action('post_updated', "bepro_admin_save_details");
                                    wp_update_post(array("ID" => $post_id, "post_status" => "publish"));
                                    remove_action('post_updated', "bepro_admin_save_details");
                                    $pay_fee = false;
                                }
                            }
                            if ($pay_fee) {
                                $fee = get_post_meta($package_id, "package_cost", true);
                            } else {
                                //this is paid so active status
                                $status = 1;
                            }
                            //Calculate expiration
                            $duration = get_post_meta($package_id, "package_duration", true);
                            if (@is_numeric($duration) && $duration != 0 && (!$fee || $fee == 0)) {
                                $expires = date('Y-m-d H:i:s', strtotime("+" . $duration . " days"));
                            }
                            //add info to order table
                            bl_create_payment_order(array("bl_order_id" => $bl_order_id, "feature_id" => $package_id, "cust_user_id" => $user_id, "feature_type" => 2, "status" => $status, "expires" => $expires));
                        }
                    }
                    //save purchase association info to bepro listing
                    $post_data["bl_order_id"] = $bl_order_id;
                }
                if ($listing) {
                    $result = bepro_update_post($post_data);
                } else {
                    $result = bepro_add_post($post_data);
                }
                if ($result === false) {
                    $return_message = false;
                } else {
                    $return_message = true;
                    //everything updated ok
                }
            }
        } else {
            $return_message = false;
        }
    }
    if ($return_post_id) {
        return $post_id;
    }
    return $return_message;
}