/**
 * wpmlm buy now button code products function
 * Sorry about the ugly code, this is just to get the functionality back, buy now will soon be overhauled, and this function will then be completely different
 * @return string - html displaying one or more products
 */
function wpmlm_buy_now_button($product_id, $replaced_shortcode = false)
{
    $product = get_post($product_id);
    $supported_gateways = array('wpmlm_merchant_paypal_standard', 'paypal_multiple');
    $selected_gateways = get_option('custom_gateway_options');
    if (in_array('wpmlm_merchant_paypal_standard', (array) $selected_gateways)) {
        if ($product_id > 0) {
            $post_meta = get_post_meta($product_id, '_wpmlm_product_metadata', true);
            $shipping = $post_meta['shipping']['local'];
            $price = get_post_meta($product_id, '_wpmlm_price', true);
            $special_price = get_post_meta($product_id, '_wpmlm_special_price', true);
            if ($special_price) {
                $price = $special_price;
            }
            if (wpmlm_uses_shipping()) {
                $handling = get_option('base_local_shipping');
            } else {
                $handling = $shipping;
            }
            $output .= "<form onsubmit='log_paypal_buynow(this)' target='paypal' action='" . get_option('paypal_multiple_url') . "' method='post' />\n\t\t\t\t<input type='hidden' name='business' value='" . get_option('paypal_multiple_business') . "' />\n\t\t\t\t<input type='hidden' name='cmd' value='_xclick' />\n\t\t\t\t<input type='hidden' name='item_name' value='" . $product->post_title . "' />\n\t\t\t\t<input type='hidden' id='item_number' name='item_number' value='" . $product_id . "' />\n\t\t\t\t<input type='hidden' id='amount' name='amount' value='" . $price . "' />\n\t\t\t\t<input type='hidden' id='unit' name='unit' value='" . $price . "' />\n\t\t\t\t<input type='hidden' id='shipping' name='ship11' value='" . $shipping . "' />\n\t\t\t\t<input type='hidden' name='handling' value='" . $handling . "' />\n\t\t\t\t<input type='hidden' name='currency_code' value='" . get_option('paypal_curcode') . "' />";
            if (get_option('multi_add') == 1) {
                $output .= "<label for='quantity'>" . __('Quantity', 'wpmlm') . "</label>";
                $output .= "<input type='text' size='4' id='quantity' name='quantity' value='' /><br />";
            } else {
                $output .= "<input type='hidden' name='undefined_quantity' value='0' />";
            }
            $output .= "<input type='image' name='submit' border='0' src='https://www.paypal.com/en_US/i/btn/btn_buynow_LG.gif' alt='PayPal - The safer, easier way to pay online' />\n\t\t\t\t<img alt='' border='0' width='1' height='1' src='https://www.paypal.com/en_US/i/scr/pixel.gif' />\n\t\t\t</form>\n\r";
        }
    }
    if ($replaced_shortcode == true) {
        return $output;
    } else {
        echo $output;
    }
}
/**
 * submit checkout function, used through ajax and in normal page loading.
 * No parameters, returns nothing
 */
function wpmlm_submit_checkout()
{
    global $wpdb, $wpmlm_cart, $user_ID, $nzshpcrt_gateways, $wpmlm_shipping_modules, $wpmlm_gateways;
    $num_items = 0;
    $use_shipping = 0;
    $disregard_shipping = 0;
    do_action('wpmlm_before_submit_checkout');
    $_SESSION['wpmlm_checkout_misc_error_messages'] = array();
    $wpmlm_checkout = new wpmlm_checkout();
    $selected_gateways = get_option('custom_gateway_options');
    $submitted_gateway = $_POST['custom_gateway'];
    $options = get_option('custom_shipping_options');
    $form_validity = $wpmlm_checkout->validate_forms();
    //echo "<pre>";print_r($form_validity); exit;
    extract($form_validity);
    // extracts $is_valid and $error_messages
    if ($_POST['agree'] != 'yes') {
        $_SESSION['wpmlm_checkout_misc_error_messages'][] = __('Please agree to the terms and conditions, otherwise we cannot process your order.', 'wpmlm');
        $is_valid = false;
    }
    $selectedCountry = $wpdb->get_results($wpdb->prepare("SELECT id, country FROM `" . WPMLM_TABLE_CURRENCY_LIST . "` WHERE isocode = '%s' ", $_SESSION['wpmlm_delivery_country']), ARRAY_A);
    foreach ($wpmlm_cart->cart_items as $cartitem) {
        if (!empty($cartitem->meta[0]['no_shipping'])) {
            continue;
        }
        $categoriesIDs = $cartitem->category_id_list;
        foreach ((array) $categoriesIDs as $catid) {
            if (is_array($catid)) {
                $countries = wpmlm_get_meta($catid[0], 'target_market', 'wpmlm_category');
            } else {
                $countries = wpmlm_get_meta($catid, 'target_market', 'wpmlm_category');
            }
            if (!empty($countries) && !in_array($selectedCountry[0]['id'], (array) $countries)) {
                $errormessage = sprintf(__('%s cannot be shipped to %s. To continue with your transaction please remove this product from the list below.', 'wpmlm'), $cartitem->product_name, $selectedCountry[0]['country']);
                $_SESSION['categoryAndShippingCountryConflict'] = $errormessage;
                $is_valid = false;
            }
        }
        //count number of items, and number of items using shipping
        $num_items++;
        if ($cartitem->uses_shipping != 1) {
            $disregard_shipping++;
        } else {
            $use_shipping++;
        }
    }
    if (array_search($submitted_gateway, $selected_gateways) !== false) {
        $_SESSION['wpmlm_previous_selected_gateway'] = $submitted_gateway;
    } else {
        $is_valid = false;
    }
    if (get_option('do_not_use_shipping') == 0 && ($wpmlm_cart->selected_shipping_method == null || $wpmlm_cart->selected_shipping_option == null) && $num_items != $disregard_shipping) {
        $_SESSION['wpmlm_checkout_misc_error_messages'][] = __('You must select a shipping method, otherwise we cannot process your order.', 'wpmlm');
        $is_valid = false;
    }
    if (get_option('do_not_use_shipping') != 1 && in_array('ups', (array) $options) && $_SESSION['wpmlm_zipcode'] == '' && $num_items != $disregard_shipping) {
        $_SESSION['categoryAndShippingCountryConflict'] = __('Please enter a Zipcode and click calculate to proceed', 'wpmlm');
        $is_valid = false;
    }
    if ($is_valid == true) {
        //echo "test2";exit;
        $_SESSION['categoryAndShippingCountryConflict'] = '';
        // check that the submitted gateway is in the list of selected ones
        $sessionid = mt_rand(100, 999) . time();
        $_SESSION['wpmlm_sessionid'] = $sessionid;
        $subtotal = $wpmlm_cart->calculate_subtotal();
        if ($wpmlm_cart->has_total_shipping_discount() == false) {
            $base_shipping = $wpmlm_cart->calculate_base_shipping();
        } else {
            $base_shipping = 0;
        }
        $delivery_country = $wpmlm_cart->delivery_country;
        $delivery_region = $wpmlm_cart->delivery_region;
        if (wpmlm_uses_shipping()) {
            $shipping_method = $wpmlm_cart->selected_shipping_method;
            $shipping_option = $wpmlm_cart->selected_shipping_option;
        } else {
            $shipping_method = '';
            $shipping_option = '';
        }
        if (isset($_POST['how_find_us'])) {
            $find_us = $_POST['how_find_us'];
        } else {
            $find_us = '';
        }
        //keep track of tax if taxes are exclusive
        $wpec_taxes_controller = new wpec_taxes_controller();
        if (!$wpec_taxes_controller->wpec_taxes_isincluded()) {
            $tax = $wpmlm_cart->calculate_total_tax();
            $tax_percentage = $wpmlm_cart->tax_percentage;
        } else {
            $tax = 0.0;
            $tax_percentage = 0.0;
        }
        $total = $wpmlm_cart->calculate_total_price();
        $total_point_value = $wpmlm_cart->calculate_total_point_value();
        $wpdb->insert(WPMLM_TABLE_PURCHASE_LOGS, array('totalprice' => $total, 'totalpointvalue' => $total_point_value, 'statusno' => '0', 'sessionid' => $sessionid, 'user_ID' => (int) $user_ID, 'date' => time(), 'gateway' => $submitted_gateway, 'billing_country' => $wpmlm_cart->selected_country, 'shipping_country' => $delivery_country, 'billing_region' => $wpmlm_cart->selected_region, 'shipping_region' => $delivery_region, 'base_shipping' => $base_shipping, 'shipping_method' => $shipping_method, 'shipping_option' => $shipping_option, 'plugin_version' => WPMLM_VERSION, 'discount_value' => $wpmlm_cart->coupons_amount, 'discount_data' => $wpmlm_cart->coupons_name, 'find_us' => $find_us, 'wpec_taxes_total' => $tax, 'wpec_taxes_rate' => $tax_percentage));
        /********| MLM USERS |*********/
        $user_tbl = mysql_query("SELECT id, user_key, parent_key,sponsor_key,leg, payment_status, banned \n\t\t\t\t\t\t\t\tFROM " . WPMLM_TABLE_USER . " WHERE user_id ='" . $user_ID . "'");
        $row = mysql_fetch_array($user_tbl);
        $user_key = $row['user_key'];
        $parent_key = $row['parent_key'];
        $payment_status = $row['payment_status'];
        $banned = $row['banned'];
        $sponsor_key = $row['sponsor_key'];
        $leg = $row['leg'];
        /*Now the below  if condition is not in use 
        		Entry are going when user registerd
        		*/
        if ($banned == 1 && $parent_key == '') {
            do {
                $parentquery = mysql_query("SELECT `user_key` FROM " . WPMLM_TABLE_USER . " \n\t\t\t\t\t\t\t\t\t\t\tWHERE parent_key = '" . $sponsor_key . "' AND \n\t\t\t\t\t\t\t\t\t\t\tleg = '" . $leg . "' AND banned = '0'");
                $num = mysql_num_rows($parentquery);
                if ($num) {
                    $ref1 = mysql_fetch_array($parentquery);
                    $sponsor_key = $ref1['key'];
                }
            } while ($num == 1);
            $parent_key = $sponsor_key;
            /*Update the mlm user table */
            $query = "UPDATE \n\t\t\t\t\t\t\t" . WPMLM_TABLE_USER . " \n\t\t\t\t\t\tSET \n\t\t\t\t\t\t\tbanned \t\t= '0' ,\n\t\t\t\t\t\t\tparent_key \t= '" . $parent_key . "'\n\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t`user_id` = '" . $user_ID . "'";
            $rs_query = mysql_query($query);
            //entry on left leg and Right leg
            if ($leg == 0) {
                mysql_query("INSERT INTO `" . WPMLM_TABLE_LEFT_LEG . "` \n\t\t\t\t\t(`id`, `pkey`,`ukey`) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t('', '" . $parent_key . "','" . $user_key . "')");
            } else {
                if ($leg == 1) {
                    mysql_query("INSERT INTO `" . WPMLM_TABLE_RIGHT_LEG . "` \n\t\t\t\t\t\t\t(`id`, `pkey`,`ukey`)\n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t ('', '" . $parent_key . "','" . $user_key . "')");
                }
            }
            while ($parent_key != '0') {
                $query = mysql_query("SELECT `parent_key`, `leg` FROM " . WPMLM_TABLE_USER . " WHERE `user_key` = '" . $parent_key . "'");
                $num_rows = mysql_num_rows($query);
                if ($num_rows) {
                    $result = mysql_fetch_array($query);
                    if ($result['parent_key'] != '0') {
                        if ($result['leg'] == 1) {
                            mysql_query("INSERT INTO `" . WPMLM_TABLE_RIGHT_LEG . "` (`id`, `pkey`,`ukey`) \n\t\t\t\t\t\t\tVALUES ('','" . $result['parent_key'] . "','" . $user_key . "')");
                        } else {
                            mysql_query("INSERT INTO `" . WPMLM_TABLE_LEFT_LEG . "` (`id`, `pkey`,`ukey`) \n\t\t\t\t\t\t\tVALUES ('','" . $result['parent_key'] . "','" . $user_key . "')");
                        }
                    }
                    $parent_key = $result['parent_key'];
                } else {
                    $parent_key = '0';
                }
            }
        }
        /*end of the entry for mlm table */
        $purchase_log_id = $wpdb->insert_id;
        $wpmlm_checkout->save_forms_to_db($purchase_log_id);
        $wpmlm_cart->save_to_db($purchase_log_id);
        $wpmlm_cart->submit_stock_claims($purchase_log_id);
        if (get_option('wpmlm_also_bought') == 1) {
            wpmlm_populate_also_bought_list();
        }
        if (!isset($our_user_id) && isset($user_ID)) {
            $our_user_id = $user_ID;
        }
        $wpmlm_cart->log_id = $purchase_log_id;
        do_action('wpmlm_submit_checkout', array("purchase_log_id" => $purchase_log_id, "our_user_id" => $our_user_id));
        if (get_option('permalink_structure') != '') {
            $separator = "?";
        } else {
            $separator = "&";
        }
        // submit to gateway
        $current_gateway_data =& $wpmlm_gateways[$submitted_gateway];
        if (isset($current_gateway_data['api_version']) && $current_gateway_data['api_version'] >= 2.0) {
            $merchant_instance = new $current_gateway_data['class_name']($purchase_log_id);
            $merchant_instance->construct_value_array();
            do_action_ref_array('wpmlm_pre_submit_gateway', array(&$merchant_instance));
            $merchant_instance->submit();
        } elseif ($current_gateway_data['internalname'] == $submitted_gateway && $current_gateway_data['internalname'] != 'google') {
            $gateway_used = $current_gateway_data['internalname'];
            $wpdb->update(WPMLM_TABLE_PURCHASE_LOGS, array('gateway' => $gateway_used), array('id' => $purchase_log_id));
            $current_gateway_data['function']($separator, $sessionid);
        } elseif ($current_gateway_data['internalname'] == 'google' && $current_gateway_data['internalname'] == $submitted_gateway) {
            $gateway_used = $current_gateway_data['internalname'];
            $wpdb->update(WPMLM_TABLE_PURCHASE_LOGS, array('gateway' => $gateway_used), array('id' => $purchase_log_id));
            $_SESSION['gateway'] = 'google';
            wp_redirect(get_option('shopping_cart_url'));
            exit;
        }
    }
}