/**
 * category meta functions are as follows:
*/
function wpmlm_get_categorymeta($cart_id, $meta_key)
{
    return wpmlm_get_meta($cart_id, $meta_key, 'wpmlm_category');
}
/**
 * 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;
        }
    }
}
function wpmlm_admin_category_forms_edit()
{
    global $wpdb;
    $category_value_count = 0;
    $category_name = '';
    $category = array();
    $category_id = absint($_REQUEST["tag_ID"]);
    $category = get_term($category_id, 'wpmlm_product_category', ARRAY_A);
    $category['nice-name'] = wpmlm_get_categorymeta($category['term_id'], 'nice-name');
    $category['description'] = wpmlm_get_categorymeta($category['term_id'], 'description');
    $category['image'] = wpmlm_get_categorymeta($category['term_id'], 'image');
    $category['fee'] = wpmlm_get_categorymeta($category['term_id'], 'fee');
    $category['active'] = wpmlm_get_categorymeta($category['term_id'], 'active');
    $category['order'] = wpmlm_get_categorymeta($category['term_id'], 'order');
    $category['display_type'] = wpmlm_get_categorymeta($category['term_id'], 'display_type');
    $category['image_height'] = wpmlm_get_categorymeta($category['term_id'], 'image_height');
    $category['image_width'] = wpmlm_get_categorymeta($category['term_id'], 'image_width');
    $category['use_additional_form_set'] = wpmlm_get_categorymeta($category['term_id'], 'use_additional_form_set');
    ?>

        <tr>
            <td colspan="2">
                <h3><?php 
    _e('Advanced Settings', 'wpmlm');
    ?>
</h3>
              
            </td>
        </tr>

	<tr class="form-field">
            <th scope="row" valign="top">
		<label for="display_type"><?php 
    _e('Catalog View', 'wpmlm');
    ?>
</label>
            </th>
            <td>
		<?php 
    //Could probably be *heavily* refactored later just to use do_action here and in GoldCart.  Baby steps.
    if (!isset($category['display_type'])) {
        $category['display_type'] = '';
    }
    if ($category['display_type'] == 'grid') {
        $display_type1 = "selected='selected'";
    } else {
        if ($category['display_type'] == 'default') {
            $display_type2 = "selected='selected'";
        }
    }
    switch ($category['display_type']) {
        case "default":
            $category_view1 = "selected ='selected'";
            break;
        case "grid":
            if (function_exists('product_display_grid')) {
                $category_view3 = "selected ='selected'";
                break;
            }
        case "list":
            if (function_exists('product_display_list')) {
                $category_view2 = "selected ='selected'";
                break;
            }
        default:
            $category_view0 = "selected ='selected'";
            break;
    }
    ?>
                        <select name='display_type'>
                                <option value=''<?php 
    echo $category_view0;
    ?>
 ><?php 
    _e('Please select', 'wpmlm');
    ?>
</option>
                                <option value='default' <?php 
    if (isset($category_view1)) {
        echo $category_view1;
    }
    ?>
 ><?php 
    _e('Default View', 'wpmlm');
    ?>
</option>

                                <?php 
    if (function_exists('product_display_list')) {
        ?>
                                                        <option value='list' <?php 
        echo $category_view2;
        ?>
><?php 
        _e('List View', 'wpmlm');
        ?>
</option>
                                <?php 
    } else {
        ?>
                                                        <option value='list' disabled='disabled' <?php 
        if (isset($category_view2)) {
            echo $category_view2;
        }
        ?>
><?php 
        _e('List View', 'wpmlm');
        ?>
</option>
                                <?php 
    }
    ?>
                                <?php 
    if (function_exists('product_display_grid')) {
        ?>
                                                        <option value='grid' <?php 
        if (isset($category_view3)) {
            echo $category_view3;
        }
        ?>
><?php 
        _e('Grid View', 'wpmlm');
        ?>
</option>
                                <?php 
    } else {
        ?>
                                                        <option value='grid' disabled='disabled' <?php 
        if (isset($category_view3)) {
            echo $category_view3;
        }
        ?>
><?php 
        _e('Grid View', 'wpmlm');
        ?>
</option>
                                <?php 
    }
    ?>
                        </select><br />
		<span class="description"><?php 
    _e('To over-ride the presentation settings for this group you can enter in your prefered settings here', 'wpmlm');
    ?>
</span>
            </td>
	</tr>
        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
    _e('Category Image', 'wpmlm');
    ?>
</label>
            </th>
            <td>
		<input type='file' name='image' value='' /><br />
                <label><input type='checkbox' name='deleteimage' class="wpmlm_cat_box" value='1' /><?php 
    _e('Delete Image', 'wpmlm');
    ?>
</label><br/>
		<span class="description"><?php 
    _e('You can set an image for the category here.  If one exists, check the box to delete.', 'wpmlm');
    ?>
</span>
            </td>
	</tr>
        <?php 
    if (function_exists("getimagesize")) {
        ?>
        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
        _e('Thumbnail Size', 'wpmlm');
        ?>
</label>
            </th>
            <td>
                <?php 
        _e('Width', 'wpmlm');
        ?>
 <input type='text' class="wpmlm_cat_image_size" value='<?php 
        if (isset($category['image_width'])) {
            echo $category['image_width'];
        }
        ?>
' name='image_width' size='6' />
                <?php 
        _e('Height', 'wpmlm');
        ?>
 <input type='text' class="wpmlm_cat_image_size" value='<?php 
        if (isset($category['image_height'])) {
            echo $category['image_height'];
        }
        ?>
' name='image_height' size='6' /><br/>
           </td>
	</tr>
        <?php 
    }
    // 'getimagesize' condition
    ?>
	<tr>
            <td colspan="2"><h3><?php 
    _e('Shortcodes and Template Tags', 'wpmlm');
    ?>
</h3></td>
        </tr>

        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
    _e('Display Category Shortcode', 'wpmlm');
    ?>
:</label>
            </th>
            <td>
                <span>[wpmlm_products category_url_name='<?php 
    echo $category["slug"];
    ?>
']</span><br />
		<span class="description"><?php 
    _e('Shortcodes are used to display a particular category or group within any WordPress page or post.', 'wpmlm');
    ?>
</span>
            </td>
	</tr>
        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
    _e('Display Category Template Tag', 'wpmlm');
    ?>
:</label>
            </th>
            <td>
                <span>&lt;?php echo wpmlm_display_products_page( array( 'category_url_name'=>'<?php 
    echo $category["slug"];
    ?>
' ) ); ?&gt;</span><br />
		<span class="description"><?php 
    _e('Template tags are used to display a particular category or group within your theme / template.', 'wpmlm');
    ?>
</span>
            </td>
	</tr>

<!-- START OF TARGET MARKET SELECTION -->

        <tr>
            <td colspan="2">
                <h3><?php 
    _e('Target Market Restrictions', 'wpmlm');
    ?>
</h3>
            </td>
        </tr>
        <?php 
    $countrylist = $wpdb->get_results("SELECT id,country,visible FROM `" . WPMLM_TABLE_CURRENCY_LIST . "` ORDER BY country ASC ", ARRAY_A);
    $selectedCountries = wpmlm_get_meta($category_id, 'target_market', 'wpmlm_category');
    ?>
        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
    _e('Target Markets', 'wpmlm');
    ?>
:</label>
            </th>
            <td>
                <?php 
    if (@extension_loaded('suhosin')) {
        ?>
                <em><?php 
        _e('The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature, then disable the suhosin extension. If you can not do this, you will need to contact your hosting provider.', 'wpmlm');
        ?>
</em>

                <?php 
    } else {
        ?>
		<span><?php 
        _e('Select', 'wpmlm');
        ?>
: <a href='' class='wpmlm_select_all'><?php 
        _e('All', 'wpmlm');
        ?>
</a>&nbsp; <a href='' class='wpmlm_select_none'><?php 
        _e('None', 'wpmlm');
        ?>
</a></span><br />
		<div id='resizeable' class='ui-widget-content multiple-select'>
                    <?php 
        foreach ($countrylist as $country) {
            if (in_array($country['id'], (array) $selectedCountries)) {
                echo " <input type='checkbox' class='wpmlm_cat_box' name='countrylist2[]' value='" . $country['id'] . "'  checked='" . $country['visible'] . "' />" . $country['country'] . "<br />";
            } else {
                echo " <input type='checkbox' class='wpmlm_cat_box' name='countrylist2[]' value='" . $country['id'] . "'  />" . $country['country'] . "<br />";
            }
        }
        ?>
		</div>
                <?php 
    }
    ?>
<br />
		<span class="description"><?php 
    _e('Select the markets you are selling this category to.', 'wpmlm');
    ?>
</span>
            </td>
	</tr>
<!-- Checkout settings -->

        <tr>
            <td colspan="2">
                <h3><?php 
    _e('Checkout Settings', 'wpmlm');
    ?>
</h3>
            </td>
        </tr>
        <?php 
    if (!isset($category['term_id'])) {
        $category['term_id'] = '';
    }
    $used_additonal_form_set = wpmlm_get_categorymeta($category['term_id'], 'use_additional_form_set');
    $checkout_sets = get_option('wpmlm_checkout_form_sets');
    unset($checkout_sets[0]);
    $uses_billing_address = (bool) wpmlm_get_categorymeta($category['term_id'], 'uses_billing_address');
    ?>
        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
    _e('Category requires additional checkout form fields', 'wpmlm');
    ?>
</label>
            </th>
            <td>
                <select name='use_additional_form_set'>
                    <option value=''><?php 
    _e('None', 'wpmlm');
    ?>
</option>
                    <?php 
    foreach ((array) $checkout_sets as $key => $value) {
        $selected_state = "";
        if ($used_additonal_form_set == $key) {
            $selected_state = "selected='selected'";
        }
        ?>
                    <option <?php 
        echo $selected_state;
        ?>
 value='<?php 
        echo $key;
        ?>
'><?php 
        echo stripslashes($value);
        ?>
</option>
                    <?php 
    }
    ?>
                </select><br />
              </td>
	</tr>

        <tr class="form-field">
            <th scope="row" valign="top">
		<label for="image"><?php 
    _e('Products in this category use the billing address to calculate shipping', 'wpmlm');
    ?>
</label>
            </th>
            <td>
                <input type='radio' class="wpmlm_cat_box" value='1' name='uses_billing_address' <?php 
    echo $uses_billing_address == true ? "checked='checked'" : "";
    ?>
 /><?php 
    _e('Yes', 'wpmlm');
    ?>
                <input type='radio' class="wpmlm_cat_box" value='0' name='uses_billing_address' <?php 
    echo $uses_billing_address != true ? "checked='checked'" : "";
    ?>
 /><?php 
    _e('No', 'wpmlm');
    ?>
                <br />
	  </td>
	</tr>

  <?php 
}