}
    cw_header_location("index.php?target={$target}&mode=edit&cat={$cat}&ge_id={$ge_id}");
}
if ($action == 'move' && !empty($cat) && $cat_location != $cat) {
    $cat_ids = array();
    array_push($cat_ids, $cat);
    if ($fields['category_location']) {
        while ($id = cw_group_edit_each($ge_id, 1, $cat)) {
            array_push($cat_ids, $id);
        }
    }
    if (!in_array($cat_location, $cat_ids)) {
        foreach ($cat_ids as $id) {
            // Get all affected categories - parent and children
            $parent_id = cw_query_first_cell("select parent_id from {$tables['categories']} where category_id='{$id}'");
            $subcats = cw_category_get_subcategory_ids($id);
            db_query("update {$tables['categories']} set parent_id='{$cat_location}' where category_id='{$id}'");
            cw_category_update_path($id);
            if (count($subcats)) {
                foreach ($subcats as $scat_id) {
                    cw_category_update_path($scat_id);
                }
            }
            $path = array($parent_id, $cat_location);
            cw_recalc_subcat_count($path);
        }
        $top_message = array('content' => cw_get_langvar_by_name('msg_adm_category_move'), 'type' => 'I');
        cw_header_location("index.php?target={$target}&mode=edit&cat={$cat}&ge_id={$ge_id}");
    }
}
if ($action == "delete_icon" && !empty($cat)) {
function cw_discount_coupons_cart_calc_discounts($params, $return)
{
    global $tables, $config, $addons, $global_store;
    extract($params);
    $coupon = $cart['info']['coupon'];
    foreach ($products as $k => $product) {
        if ($product['hidden']) {
            continue;
        }
        $products[$k]['coupon_discount'] = 0;
    }
    $return['coupon_discount'] = 0;
    $return['coupon'] = 0;
    if (!empty($coupon)) {
        $coupon_total = 0;
        $coupon_amount = 0;
        cw_load('salesman');
        $is_salesman_coupon = cw_is_salesman_coupon($discount_coupon);
        if ($is_salesman_coupon) {
            $discount_coupon_data = cw_query_first("select * from {$tables['discount_coupons']} where coupon='{$discount_coupon}'");
            if ($discount_coupon_data['from_account']) {
                $discount_coupon_data['discount'] = cw_get_salesman_discount($products, $discount_coupon, $membership_id, $warehouse);
                $discount_coupon_data['coupon_type'] = 'absolute';
            }
        } else {
            if (!empty($global_store['discount_coupons'])) {
                $discount_coupon_data = array();
                foreach ($global_store['discount_coupons'] as $v) {
                    if ($v['__override'] || $v['coupon'] == $coupon && $v['warehouse_customer_id'] == $warehouse) {
                        $discount_coupon_data = $v;
                        break;
                    }
                }
            } else {
                $discount_coupon_data = cw_query_first("select * from {$tables['discount_coupons']} where coupon='{$coupon}'");
            }
        }
        $return['discount_coupon_data'] = $discount_coupon_data;
        $return['coupon_type'] = $discount_coupon_data['coupon_type'];
        if (!empty($discount_coupon_data) && ($discount_coupon_data['coupon_type'] == 'absolute' || $discount_coupon_data['coupon_type'] == 'percent')) {
            $coupon_discount = 0;
            if ($discount_coupon_data['product_id'] > 0) {
                foreach ($products as $k => $product) {
                    if ($product['product_id'] != $discount_coupon_data['product_id']) {
                        continue;
                    }
                    $price = $product['discounted_price'];
                    if ($discount_coupon_data['coupon_type'] == 'absolute' && $discount_coupon_data['discount'] > $price) {
                        $discount_coupon_data['discount'] = 100;
                        $discount_coupon_data['coupon_type'] = 'percent';
                    }
                    if ($discount_coupon_data['coupon_type'] == 'absolute' && $discount_coupon_data['apply_product_once'] == 0) {
                        $multiplier = $product['amount'];
                    } else {
                        $multiplier = 1;
                    }
                    $_coupon_discount = $_taxed_coupon_discount = $discount_coupon_data['discount'] * $multiplier;
                    if ($config['Taxes']['apply_discount_on_taxed_amount'] == "Y" && !empty($product['taxes']) && is_array($product['taxes'])) {
                        $_taxes = cw_tax_price($_coupon_discount, 0, false, NULL, '', $product['taxes'], $discount_coupon_data['coupon_type'] == 'percent');
                        $_taxed_coupon_discount = $_taxes['taxed_price'];
                        $_coupon_discount = $_taxes['net_price'];
                    }
                    if ($discount_coupon_data['coupon_type'] == 'absolute') {
                        $taxed_coupon_discount = $_taxed_coupon_discount;
                        $taxed_coupon_discount = $coupon_discount = $_coupon_discount;
                    } else {
                        $taxed_coupon_discount = $price * $_taxed_coupon_discount / 100;
                        $coupon_discount = $price * $_coupon_discount / 100;
                    }
                    $products[$k]['coupon_discount'] = $taxed_coupon_discount;
                    $products[$k]['discounted_price'] = max($price - $coupon_discount, 0.0);
                    $return['coupon_discount'] += $taxed_coupon_discount;
                }
            } elseif ($discount_coupon_data['category_id'] > 0) {
                $category_ids[] = $discount_coupon_data['category_id'];
                if ($discount_coupon_data['recursive']) {
                    $category_ids = cw_category_get_subcategory_ids($discount_coupon_data['category_id']);
                }
                if ($discount_coupon_data['coupon_type'] == 'absolute') {
                    foreach ($products as $k => $product) {
                        if ($config['Appearance']['categories_in_products'] == '1') {
                            $product_categories = cw_query("SELECT category_id FROM {$tables['products_categories']} WHERE product_id='{$product['product_id']}'");
                            $is_valid_product = false;
                            foreach ($product_categories as $pc) {
                                if (in_array($pc['category_id'], $category_ids)) {
                                    $is_valid_product = true;
                                    break;
                                }
                            }
                        }
                        if ($is_valid_product) {
                            if ($discount_coupon_data['coupon_type'] == "absolute" && ~$discount_coupon_data['apply_product_once']) {
                                $multiplier = $product['amount'];
                            } else {
                                $multiplier = 1;
                            }
                            $sum_discount += $discount_coupon_data['discount'] * $multiplier;
                        }
                    }
                    if ($sum_discount > $return['total']) {
                        $discount_coupon_data['discount'] = 100;
                        $discount_coupon_data['coupon_type'] = 'percent';
                    }
                }
                foreach ($products as $k => $product) {
                    if ($config['Appearance']['categories_in_products'] == '1') {
                        $product_categories = cw_query("SELECT category_id FROM {$tables['products_categories']} WHERE product_id='{$product['product_id']}'");
                        $is_valid_product = false;
                        foreach ($product_categories as $pc) {
                            if (in_array($pc['category_id'], $category_ids)) {
                                $is_valid_product = true;
                                break;
                            }
                        }
                    }
                    if ($is_valid_product) {
                        if ($discount_coupon_data['coupon_type'] == "absolute" && $discount_coupon_data['apply_product_once'] == "N") {
                            $multiplier = $product['amount'];
                        } else {
                            $multiplier = 1;
                        }
                        $_coupon_discount = $_taxed_coupon_discount = $discount_coupon_data['discount'] * $multiplier;
                        if ($config['Taxes']['apply_discount_on_taxed_amount'] == "Y" && !empty($product['taxes']) && is_array($product['taxes'])) {
                            $_taxes = cw_tax_price($_coupon_discount, 0, false, NULL, "", $product['taxes'], $discount_coupon_data['coupon_type'] == "percent");
                            $_taxed_coupon_discount = $_taxes['taxed_price'];
                            $_coupon_discount = $_taxes['net_price'];
                        }
                        $price = $product['discounted_price'];
                        if ($discount_coupon_data['coupon_type'] == "absolute") {
                            $taxed_coupon_discount = $_taxed_coupon_discount;
                            $coupon_discount = $_coupon_discount;
                        } else {
                            $taxed_coupon_discount = $price * $_taxed_coupon_discount / 100;
                            $coupon_discount = $price * $_coupon_discount / 100;
                        }
                        $taxed_coupon_discount = $taxed_coupon_discount;
                        $products[$k]['coupon_discount'] = $taxed_coupon_discount;
                        $products[$k]['discounted_price'] = max($price - $coupon_discount, 0.0);
                        $return['coupon_discount'] += $taxed_coupon_discount;
                        if ($discount_coupon_data['coupon_type'] == "absolute" && $discount_coupon_data['apply_category_once'] == "Y") {
                            break;
                        }
                    }
                }
            } else {
                if ($discount_coupon_data['coupon_type'] == 'absolute' && $discount_coupon_data['discount'] > $return['total']) {
                    $discount_coupon_data['discount'] = 100;
                    $discount_coupon_data['coupon_type'] = 'percent';
                }
                if ($discount_coupon_data['coupon_type'] == 'absolute') {
                    $return['coupon_discount'] = $discount_coupon_data['discount'];
                } elseif ($discount_coupon_data['coupon_type'] == 'percent') {
                    $return['coupon_discount'] = $return['total'] * $discount_coupon_data['discount'] / 100;
                }
                $updated = cw_distribute_discount("coupon_discount", $products, $discount_coupon_data['discount'], $discount_coupon_data['coupon_type'], $return['total'], $_taxes);
                extract($updated);
                unset($updated);
                $return['coupon_discount'] = $coupon_discount;
            }
        }
        if (isset($coupon_discount_orig)) {
            $return['coupon_discount_orig'] = $coupon_discount_orig;
        } else {
            $return['coupon_discount_orig'] = $return['coupon_discount'];
        }
        $return['products'] = $products;
    }
    return $return;
}
function cw_get_offer_conditions($offer_id)
{
    static $offer_conditions;
    $cond_categories = $cond_manufacturers = $cond_products = array();
    $result = array($cond_categories, $cond_manufacturers, $cond_products);
    if (empty($offer_id)) {
        return $result;
    }
    if (!isset($offer_conditions)) {
        $offer_conditions = array();
    }
    if (isset($offer_conditions[$offer_id])) {
        return $offer_conditions[$offer_id];
    }
    //product categories
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array('object_id', 'quantity');
    $from_tbls[] = 'ps_cond_details';
    $where[] = "object_type = '" . PS_OBJ_TYPE_CATS . "'";
    $where[] = "offer_id = '{$offer_id}'";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $cond_categories = cw_query_hash($search_query, 'object_id', false, true);
    $result_cond_categories = array();
    if (!empty($cond_categories) && is_array($cond_categories)) {
        foreach ($cond_categories as $category => $quantity) {
            $cond_categories[$category] = array('subcats' => array(), 'quantity' => $quantity);
            $sub_cond_categories = cw_category_get_subcategory_ids($category);
            if (!empty($sub_cond_categories) && is_array($sub_cond_categories)) {
                $sub_cond_categories = array_fill_keys($sub_cond_categories, $quantity);
                $cond_categories[$category] = array('subcats' => $sub_cond_categories, 'quantity' => $quantity);
                $result_cond_categories += $sub_cond_categories;
            }
        }
        unset($sub_cond_categories);
    }
    // manufacturers
    $where = array();
    $where[] = "object_type = '" . PS_OBJ_TYPE_MANS . "'";
    $where[] = "offer_id = '{$offer_id}'";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $cond_manufacturers = cw_query_hash($search_query, 'object_id', false, true);
    if (!is_array($cond_manufacturers)) {
        $cond_manufacturers = array();
    }
    // attributes
    $where = array();
    $where[] = "object_type = '" . PS_OBJ_TYPE_ATTR . "'";
    $where[] = "offer_id = '{$offer_id}'";
    $search_query = cw_db_generate_query(array_merge($fields, array('cd_id', 'param1', 'param2')), $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $cond_attributes = cw_query_hash($search_query, 'object_id', false, true);
    if (!is_array($cond_attributes)) {
        $cond_attributes = array();
    }
    // products
    $where = array();
    $where[] = "object_type = '" . PS_OBJ_TYPE_PRODS . "'";
    $where[] = "offer_id = '{$offer_id}'";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $cond_products = cw_query_hash($search_query, 'object_id', false, true);
    $offer_conditions[$offer_id] = array($cond_categories, $cond_manufacturers, $cond_products, $cond_attributes);
    unset($cond_categories, $cond_manufacturers, $cond_products);
    return $offer_conditions[$offer_id];
}
        $top_message = array('content' => cw_get_langvar_by_name('lbl_please_select_categories_for_editing'), 'type' => 'I');
        cw_header_location('index.php?target=' . $target);
    }
    $cat_ids = array_keys($delete_arr);
    $ge_id = cw_group_edit_add($cat_ids);
    $cat_id = $cat_ids[0];
    cw_header_location('index.php?target=' . $target . '&mode=edit&cat=' . $cat_id . '&ge_id=' . $ge_id);
}
if ($action == 'apply' && is_array($posted_data)) {
    foreach ($posted_data as $k => $v) {
        $query_data = array('order_by' => intval($v['order_by']));
        cw_array2update('categories', $query_data, "category_id='" . $k . "'");
        cw_category_update_status($k, $v['status']);
    }
    if ($cat) {
        $path = cw_category_get_subcategory_ids($cat);
        if (!empty($path)) {
            cw_recalc_subcat_count($path);
        }
    } else {
        cw_recalc_subcat_count();
    }
    $top_message = array('content' => cw_get_langvar_by_name('msg_adm_categories_upd'), 'type' => 'I');
    cw_header_location("index.php?target={$target}" . ($mode ? '&mode=' . $mode : '') . "&cat={$cat}&js_tab={$js_tab}");
}
if ($action == 'delete') {
    if ($confirmed == "Y") {
        # kronev, for the big amount of products - the
        cw_display_service_header('lbl_delete_categories') . '<br/>';
        if (is_array($categories_to_delete)) {
            foreach ($categories_to_delete as $cat) {
function cw_product_search($params, $return = null)
{
    extract($params);
    global $tables, $addons, $current_language, $config, $app_config_file;
    global $cart;
    global $smarty;
    global $target;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $from_tbls[] = 'products';
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    if ($data['where']) {
        $where[] = $data['where'];
    }
    $query_joins['products_stats'] = array('on' => "{$tables['products_stats']}.product_id = {$tables['products']}.product_id", 'only_select' => 1);
    # kornev, all of the inner joins are replaced by left join && not null
    # it works fastly because mylsq do not optimize the tables order is query and we are able to play with it.
    $memberships = array(0);
    if ($user_account['membership_id'] > 0) {
        $memberships[] = intval($user_account['membership_id']);
    }
    $query_joins['products_flat'] = array('on' => "{$tables['products_flat']}.product_id = {$tables['products']}.product_id", 'only_select' => 1);
    $fields[] = "{$tables['products_flat']}.*";
    $fields[] = "{$tables['products']}.*";
    if (!is_array($data['warehouse_customer_id'])) {
        $data['warehouse_customer_id'] = array($data['warehouse_customer_id'] => 1);
    }
    $query_joins['products_warehouses_amount'] = array('parent' => 'products', 'on' => "{$tables['products_warehouses_amount']}.product_id = {$tables['products']}.product_id and {$tables['products_warehouses_amount']}.warehouse_customer_id = 0 and {$tables['products_warehouses_amount']}.variant_id=0");
    $fields[] = "{$tables['products_warehouses_amount']}.avail";
    if ($current_area == 'A') {
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "{$tables['products_prices']}.price";
        # kornev, TOFIX
        if ($addons['product_options']) {
            $fields[] = "if({$tables['product_variants']}.product_id IS NULL, '', 'Y') as is_variants";
        }
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
    } else {
        $fields[] = "min({$tables['products_prices']}.price) as price";
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "{$tables['products_prices']}.list_price";
        //        $fields[] = "min($tables[products_prices].list_price) as list_price";
        $query_joins['products_prices'] = array('parent' => 'products', 'on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id and {$tables['products_prices']}.quantity=1 and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")", 'is_inner' => 1);
        if ($config['Appearance']['show_views_on_product_page'] == 'Y') {
            $fields[] = "{$tables['products_stats']}.views_stats";
        }
    }
    if ($config['Appearance']['categories_in_products'] == '1') {
        $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id", 'pos' => '0', 'is_inner' => 1);
    }
    # kornev, we should add filter by attributes names
    if ($data['attribute_names']) {
        $att_ids = cw_call('cw_attributes_get_attribute_by_field', array('field' => array_keys($data['attribute_names'])));
        if ($att_ids) {
            foreach ($att_ids as $k => $v) {
                $data['attributes'][$v] = $data['attribute_names'][$k];
            }
        }
    }
    # kornev, filter by attributes
    if ($data['attributes']) {
        if ($data['attributes'][PRICE_ATTRIBUTE_ID]) {
            $data['price_min'] = $data['attributes'][PRICE_ATTRIBUTE_ID]['min'];
            $data['price_max'] = $data['attributes'][PRICE_ATTRIBUTE_ID]['max'];
        }
        if ($data['attributes']['substring']) {
            $data['substring'] = $data['attributes']['substring'];
        }
        foreach ($data['attributes'] as $k => $v) {
            $a = cw_call('cw_attributes_filter', array(array('attribute_id' => $k), true));
            // If attr is number and presented in filter as predefined ranges,
            // then range attribute_value_id is passed as criteria, not real value or real range
            if (in_array($a['type'], array('decimal', 'integer'), true) && in_array($a['pf_display_type'], array('P', 'W', 'E', 'G')) && !isset($v['min'])) {
                $result = cw_product_filter_get_price_range_values($v[0]);
                if ($result) {
                    $v['min'] = $result[0];
                    $v['max'] = $result[1];
                }
                if ($k == PRICE_ATTRIBUTE_ID) {
                    $data['price_min'] = $v['min'];
                    $data['price_max'] = $v['max'];
                    $data['attributes']['price'] = $v;
                    continue;
                }
            }
            if (in_array($k, array('price', 'substring', PRICE_ATTRIBUTE_ID))) {
                continue;
            }
            if (!is_numeric($k)) {
                continue;
            }
            // Only real attributes must e converted into JOIN sql statement
            if (!is_array($v)) {
                $data['attributes'][$k] = $v = array($v);
            }
            $query_joins['atv_' . $k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_{$k}.item_id and atv_{$k}.attribute_id = '{$k}' and atv_{$k}.code in ('{$current_language}', '') and " . (isset($v['min']) ? "atv_{$k}.value >= " . floatval($v['min']) . " and atv_{$k}.value <= " . floatval($v['max']) : "atv_{$k}.value in ('" . implode("', '", $v) . "')"), 'is_inner' => 1);
        }
    }
    if (!empty($data['by_pf_s_attr']) && !empty($data['substring'])) {
        $attr_pf_s_where = array();
        foreach ($data['by_pf_s_attr'] as $attr_id => $digit_flag) {
            $is_def_values = cw_query_first_cell("select count(*) from {$tables['attributes_default']} where attribute_id='{$attr_id}'");
            $attr_type = cw_query_first_cell("select type from {$tables['attributes']} where attribute_id='{$attr_id}'");
            if ($is_def_values && !in_array($attr_type, array('textarea', 'text'))) {
                if ($data['including'] == 'all' || $data['including'] == 'any') {
                    $search_words = array_filter(explode(" ", $data['substring']));
                    $search_words_arr = array();
                    foreach ($search_words as $word) {
                        $word = addslashes($word);
                        $search_words_arr[] = "atd_pf_s_{$attr_id}.value like '%{$word}%'";
                    }
                }
                if ($data['including'] == 'all') {
                    $value_eq_sql = " (" . implode(" and ", $search_words_arr) . ") ";
                } elseif ($data['including'] == 'any') {
                    $value_eq_sql = " (" . implode(" or ", $search_words_arr) . ") ";
                } else {
                    $value_eq_sql = "atd_pf_s_{$attr_id}.value like '%" . addslashes($data['substring']) . "%'";
                }
                $attr_value_ids = cw_query_column("select attribute_value_id from {$tables['attributes_default']} atd_pf_s_{$attr_id} where atd_pf_s_{$attr_id}.attribute_id='{$attr_id}' and {$value_eq_sql}");
                if (!empty($attr_value_ids)) {
                    $query_joins['atv_pf_s_' . $attr_id] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_pf_s_{$attr_id}.item_id and atv_pf_s_{$attr_id}.item_type='P' and atv_pf_s_{$attr_id}.attribute_id = '{$attr_id}' and atv_pf_s_{$attr_id}.code in ('{$current_language}', '') and cast(atv_pf_s_{$attr_id}.value as SIGNED) in ('" . implode("','", $attr_value_ids) . "')");
                    $attr_pf_s_where[] = "atv_pf_s_{$attr_id}.item_id is not null";
                }
            } else {
                if ($data['including'] == 'all' || $data['including'] == 'any') {
                    $search_words = array_filter(explode(" ", $data['substring']));
                    $search_words_arr = array();
                    foreach ($search_words as $word) {
                        $word = addslashes($word);
                        $search_words_arr[] = "atv_pf_s_{$attr_id}.value like '%{$word}%'";
                    }
                }
                if ($data['including'] == 'all') {
                    $value_eq_sql = " (" . implode(" and ", $search_words_arr) . ") ";
                } elseif ($data['including'] == 'any') {
                    $value_eq_sql = " (" . implode(" or ", $search_words_arr) . ") ";
                } else {
                    $value_eq_sql = "atv_pf_s_{$attr_id}.value like '%" . addslashes($data['substring']) . "%'";
                }
                $query_joins['atv_pf_s_' . $attr_id] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_pf_s_{$attr_id}.item_id and atv_pf_s_{$attr_id}.item_type='P' and atv_pf_s_{$attr_id}.attribute_id = '{$attr_id}' and atv_pf_s_{$attr_id}.code in ('{$current_language}', '') and {$value_eq_sql}");
                $attr_pf_s_where[] = "atv_pf_s_{$attr_id}.item_id is not null";
            }
            $return['substring_search_alternative'] = true;
        }
        if (!empty($attr_pf_s_where)) {
            $where[] = "(" . implode(" or ", $attr_pf_s_where) . ")";
        }
    }
    if (!empty($data['by_pf_attr_numeric'])) {
        $cast_types = array('decimal' => 'DECIMAL', 'integer' => 'SIGNED', 'yes_no' => 'SIGNED');
        foreach ($data['by_pf_attr_numeric'] as $attr_id => $attr_limits) {
            if (empty($attr_limits['min']) && empty($attr_limits['max'])) {
                continue;
            }
            $attr_type = cw_query_first_cell("select type from {$tables['attributes']} where attribute_id='{$attr_id}'");
            $_cast_type = $cast_types[$attr_type];
            if (empty($_cast_type)) {
                continue;
            }
            $ps_numeric_val_limits = array();
            $_min_limit = min($attr_limits['min'], $attr_limits['max']);
            $_max_limit = max($attr_limits['min'], $attr_limits['max']);
            $ps_num_table_alias = "ps_num_" . $attr_id;
            if (!empty($_min_limit)) {
                $ps_numeric_val_limits[] = "cast(" . $ps_num_table_alias . ".value as {$_cast_type}) >= '{$_min_limit}'";
            }
            if (!empty($_max_limit)) {
                $ps_numeric_val_limits[] = "cast(" . $ps_num_table_alias . ".value as {$_cast_type}) <= '{$_max_limit}'";
            }
            if (!empty($ps_numeric_val_limits)) {
                $query_joins[$ps_num_table_alias] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id={$ps_num_table_alias}.item_id and {$ps_num_table_alias}.item_type='P' and {$ps_num_table_alias}.attribute_id='{$attr_id}' and " . implode(" and ", $ps_numeric_val_limits), 'is_inner' => 1);
            }
        }
    }
    if (isset($data['by_pf_attr_multi'])) {
        foreach ($data['by_pf_attr_multi'] as $attr_id => $attr_value_ids) {
            if (empty($attr_value_ids)) {
                continue;
            }
            $ps_multi_table_alias = 'atv_pf_multi_' . $attr_id;
            $query_joins[$ps_multi_table_alias] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id={$ps_multi_table_alias}.item_id and {$ps_multi_table_alias}.item_type='P' and {$ps_multi_table_alias}.attribute_id = '{$attr_id}' and {$ps_multi_table_alias}.code in ('{$current_language}', '') and (cast({$ps_multi_table_alias}.value as SIGNED) in ('" . implode("','", $attr_value_ids) . "'))", 'is_inner' => 1);
        }
    }
    if (!$data['substring_exact']) {
        $data['substring'] = trim($data['substring']);
        $data['substring_prepared'] = '%' . $data['substring'] . '%';
    } else {
        $data['substring_prepared'] = $data['substring'];
    }
    $search_by_variants = false;
    if (($data['search_sections']['tab_basic_search'] || $data['flat_search'] || $data['attributes']['substring']) && $data['substring']) {
        $condition = array();
        $search_string_fields = array();
        if (empty($data['by_title']) && empty($data['by_shortdescr']) && empty($data['by_fulldescr']) && empty($data['by_sku']) && empty($return['substring_search_alternative'])) {
            $search_data['products'][$use_search_conditions]['by_title'] = $data['by_title'] = 1;
            // TOFIX: both $search_data and $use_search_conditions is undefinde
            $flag_save = true;
        }
        if ($data['by_title']) {
            $search_string_fields[] = "product";
        }
        if ($data['by_manufacturer']) {
            $search_string_fields[] = 'manufacturer_code';
        }
        if ($data['by_productcode']) {
            $search_string_fields[] = 'productcode';
        }
        if ($data['by_ean']) {
            $search_string_fields[] = 'eancode';
        }
        if ($data['by_shortdescr']) {
            $search_string_fields[] = "descr";
        }
        if ($data['by_fulldescr']) {
            $search_string_fields[] = "fulldescr";
        }
        if ($data['by_ean'] && !empty($addons['product_options'])) {
            $search_by_variants = true;
            $condition[] = "search_variants.eancode LIKE '" . $data['substring_prepared'] . "'";
        }
        if ($data['by_manufacturer'] && !empty($addons['product_options'])) {
            $search_by_variants = true;
            $condition[] = "search_variants.mpn LIKE '" . $data['substring_prepared'] . "'";
        }
        $search_words = array();
        if ($config['General']['allow_search_by_words'] == 'Y' && in_array($data['including'], array("all", "any"))) {
            $tmp = stripslashes(trim($data['substring']));
            if (preg_match_all('/"([^"]+)"/', $tmp, $match)) {
                $search_words = $match[1];
                $tmp = str_replace($match[0], '', $tmp);
            }
            $tmp = explode(' ', $tmp);
            $tmp = cw_array_map("trim", $tmp);
            $search_words = array_merge($search_words, $tmp);
            unset($tmp);
            # Check word length limit
            if ($search_word_length_limit > 0) {
                $search_words = preg_grep("/^..+\$/", $search_words);
            }
            $stopwords = cw_get_stopwords();
            if (!empty($stopwords) && is_array($stopwords)) {
                $tmp = preg_grep("/^(" . implode("|", $stopwords) . ")\$/i", $search_words);
                if (!empty($tmp) && is_array($tmp)) {
                    $search_words = array_diff($search_words, $tmp);
                    $search_words = array_values($search_words);
                }
                unset($tmp);
            }
            # Check word count limit
            if ($search_word_limit > 0 && count($search_words) > $search_word_limit) {
                $search_words = array_splice($search_words, $search_word_limit - 1);
            }
        }
        $search_words = array_filter($search_words);
        $search_words = cw_addslashes($search_words);
        foreach ($search_string_fields as $ssf) {
            if ($config['General']['allow_search_by_words'] == 'Y' && !empty($search_words) && in_array($data['including'], array("all", "any"))) {
                if ($data['including'] == 'all') {
                    $tmp = array();
                    foreach ($search_words as $sw) {
                        if ($current_area == 'C' || $current_area == 'B') {
                            if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                                $tmp[] = "{$tables['products']}.{$ssf} LIKE '%" . $sw . "%'";
                            } else {
                                $tmp[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) LIKE '%" . $sw . "%'";
                            }
                        } else {
                            $tmp[] = "{$tables['products']}.{$ssf} LIKE '%" . $sw . "%'";
                        }
                    }
                    if (!empty($tmp)) {
                        $condition[] = "(" . implode(" AND ", $tmp) . ")";
                    }
                    unset($tmp);
                } else {
                    if ($current_area == 'C' || $current_area == 'B') {
                        if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                            $condition[] = "{$tables['products']}.{$ssf} REGEXP '" . implode("|", $search_words) . "'";
                        } else {
                            $condition[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) REGEXP '" . implode("|", $search_words) . "'";
                        }
                    } else {
                        $condition[] = "{$tables['products']}.{$ssf} REGEXP '" . implode("|", $search_words) . "'";
                    }
                }
            } elseif ($current_area == 'C' || $current_area == 'B') {
                if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                    $condition[] = "{$tables['products']}.{$ssf} LIKE '" . $data['substring_prepared'] . "'";
                } else {
                    $condition[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) LIKE '" . $data['substring_prepared'] . "'";
                }
            } else {
                $condition[] = "{$tables['products']}.{$ssf} LIKE '" . $data['substring_prepared'] . "'";
            }
        }
        if ($data['by_sku']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $condition[] = (empty($addons['product_options']) ? "({$tables['products']}.productcode)" : "(IFNULL(search_variants.productcode, {$tables['products']}.productcode)") . " LIKE '" . $data['substring_prepared'] . "' OR {$tables['products']}.eancode like '" . $data['substring_prepared'] . "')";
        }
        if ($data['by_tags'] || $data['by_shortdescr'] || $data['by_fulldescr']) {
            if (!empty($search_words) && in_array($data['including'], array("all", "any"))) {
                $tags_condition = "name REGEXP '" . implode("|", $search_words) . "'";
            } else {
                $tags_condition = "name LIKE '" . $data['substring_prepared'] . "'";
            }
            $tag_ids = cw_query_column("SELECT tag_id FROM {$tables['tags']} WHERE {$tags_condition}");
            $query_joins['tags_substr'] = array('tblname' => 'tags_products', 'on' => "tags_substr.product_id = {$tables['products']}.product_id", 'only_select' => 0);
            $condition[] = "tags_substr.tag_id IN ('" . join("','", $tag_ids) . "')";
            unset($tag_ids, $tags_condition);
        }
        if (!empty($condition)) {
            $where[] = "(" . implode(" OR ", $condition) . ")";
        }
        unset($condition);
    }
    if ($data['search_sections']['tab_add_search'] || $data['flat_search'] || $data['product_types']) {
        if (!$data['status']) {
            $data['status'] = cw_core_get_required_status($current_area);
        }
        if ($data['status']) {
            $where[] = "{$tables['products']}.status in (" . implode(", ", $data['status']) . ")";
        }
        if ($config['Appearance']['categories_in_products'] == '1') {
            if ($data['category_id']) {
                $data['categories'] = array($data['category_id'] => 1);
                $data['categories_orig'] = array($data['category_id']);
            }
            if ($data['category_ids']) {
                $_categories = array();
                $_categories_orig = array();
                foreach ($data['category_ids'] as $c_id) {
                    $_categories[$c_id] = 1;
                    $_categories_orig[] = $c_id;
                }
                $data['categories'] = $_categories;
                $data['categories_orig'] = $_categories_orig;
            }
            if ($data['categories'] && is_array($data['categories'])) {
                if ($data['search_in_subcategories']) {
                    $categories_to_search = cw_category_get_subcategory_ids($data['categories_orig']);
                    if (count($categories_to_search)) {
                        $where[] = "{$tables['products_categories']}.category_id IN (" . implode(",", $categories_to_search) . ")";
                    }
                } else {
                    $where[] = "{$tables['products_categories']}.category_id IN (" . implode(",", $data['categories_orig']) . ")";
                }
                $condition = array();
                if ($data['category_main']) {
                    $condition[] = "{$tables['products_categories']}.main = 1";
                }
                if ($data['category_extra']) {
                    $condition[] = "{$tables['products_categories']}.main = 0";
                }
                if (count($condition)) {
                    $where[] = "(" . implode(" OR ", $condition) . ")";
                }
            }
        }
        if ($data['productcode']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.productcode" : "IFNULL(search_variants.productcode, {$tables['products']}.productcode)";
            $where[] = "({$productcode_cond_string} LIKE '%" . $data['productcode'] . "%')";
        }
        if ($data['manufacturer_code']) {
            $where[] = "({$tables['products']}.manufacturer_code like '%" . $data['manufacturer_code'] . "%')";
        }
        if ($data['eancode']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.eancode" : "IFNULL(search_variants.eancode, {$tables['products']}.eancode)";
            $where[] = "({$productcode_cond_string} LIKE '%" . $data['eancode'] . "%')";
        }
        if ($data['product_id']) {
            $where[] = "{$tables['products']}.product_id " . (is_array($data['product_id']) ? " IN ('" . implode("','", $data['product_id']) . "')" : "= '" . $data['product_id'] . "'");
        }
        if (!empty($data['serial_number'])) {
            $warehouse_condition = AREA_TYPE == 'P' ? "and {$tables['serial_numbers']}.warehouse_customer_id='{$user_account['warehouse_customer_id']}'" : "";
            $where[] = "{$tables['serial_numbers']}.sn LIKE '%" . $data['serial_number'] . "%' {$warehouse_condition}";
            $query_joins['serial_numbers'] = array("on" => "{$tables['serial_numbers']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        }
        /* kornev, removed - the manufacturer is attribute now and search is going to be done in another way
                if ($addons['manufacturers']) {
        /*
        # kornev, attribute should be selected in another way
                    $fields[] = "$tables[manufacturers].manufacturer";
                    $query_joins['manufacturers'] = array(
                        'on' => "$tables[products].manufacturer_id = $tables[manufacturers].manufacturer_id",
                        'only_select' => 1,
                    );
        */
        /*
                    if ($data['manufacturers']) {
                        $where['manuf_condition'] = "$tables[products].manufacturer_id IN ('".implode("', '", array_keys($data['manufacturers']))."')";
                        $query_joins['manufacturers']['only_select'] = 0;
                        $query_joins['manufacturers']['is_inner'] = 1;
                    }
                    if ($data['manufacturers_substring']) {
                        $substring = $data['manufacturers_substring'];
                        if (!$data['manufacturers_substring_exact']) $substring = '%'.trim($substring).'%';
                        $where['manuf_condition'] .= "$tables[manufacturers].manufacturer like '$substring'";
                        $query_joins['manufacturers']['only_select'] = 0;
                        $query_joins['manufacturers']['is_inner'] = 1;
                    }
                }
        */
        if ($data['avail_types']) {
            if ($data['avail_types'][1]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail > 0";
            }
            if ($data['avail_types'][2]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_ordered > 0";
            }
            if ($data['avail_types'][3]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_sold > 0";
            }
            if ($data['avail_types'][4]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_reserved > 0";
            }
            if ($data['avail_types'][5]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail < 0";
            }
            if ($data['avail_types'][6]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail = 0";
            }
        }
        if ($data['product_types']) {
            $where[] = "{$tables['products']}.product_type in ('" . implode("', '", array_keys($data['product_types'])) . "')";
        }
    }
    if (($current_area == "C" || $current_area == "B") && $config['General']['disable_outofstock_products'] == "Y") {
        $where[] = "{$tables['products_warehouses_amount']}.avail > 0";
    }
    if ($data['search_sections']['tab_prices'] || $data['flat_search']) {
        $query_joins['products_prices'] = array('parent' => 'products', 'on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id and {$tables['products_prices']}.quantity=1 and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")", 'is_inner' => 1);
        if ($data['price_min']) {
            $where['price_min'] = "{$tables['products_prices']}.price >= '{$data['price_min']}'";
        }
        if ($data['price_max']) {
            $where['price_max'] = "{$tables['products_prices']}.price <= '{$data['price_max']}'";
        }
        if ($data['weight_min']) {
            $where['weight_min'] = "{$tables['products']}.weight >= '{$data['weight_min']}'";
        }
        if ($data['weight_max']) {
            $where['weight_max'] = "{$tables['products']}.weight <= '{$data['weight_max']}'";
        }
        /*
                if ($data['list_price_min'])
                    $where[] = "$tables[products_prices].list_price >= '$data[list_price_min]'";
                if ($data['list_price_min'])
                    $where[] = "$tables[products_prices].list_price <= '$data[list_price_max]'";
        */
        if ($data['list_price_min']) {
            $where[] = "{$tables['products']}.list_price >= '{$data['list_price_min']}'";
        }
        if ($data['list_price_min']) {
            $where[] = "{$tables['products']}.list_price <= '{$data['list_price_max']}'";
        }
    }
    if ($data['search_sections']['tab_additional_options'] || $data['flat_search']) {
        if ($data['flag_free_ship']) {
            $where[] = "{$tables['products']}.free_shipping = '" . $data['flag_free_ship'] . "'";
        }
        if ($data['flag_ship_freight']) {
            $where[] = "{$tables['products']}.shipping_freight " . ($data['flag_ship_freight'] == 'Y' ? '>0' : '=0');
        }
        if ($data['flag_global_disc']) {
            $where[] = "{$tables['products']}.discount_avail = '" . $data['flag_global_disc'] . "'";
        }
        if ($data['flag_free_tax']) {
            $where[] = "{$tables['products']}.free_tax = '" . $data['flag_free_tax'] . "'";
        }
        if ($data['flag_min_amount']) {
            if ($data['flag_min_amount'] == "Y") {
                $where[] = "{$tables['products']}.min_amount <= 1";
            } else {
                $where[] = "{$tables['products']}.min_amount = 1";
            }
        }
        if ($data['flag_low_avail_limit']) {
            if ($data['flag_low_avail_limit'] == 'Y') {
                $where[] = "{$tables['products']}.low_avail_limit <= 1";
            } else {
                $where[] = "{$tables['products']}.low_avail_limit > 1";
            }
        }
    }
    if ($data['search_sections']['tab_anagraphic'] || $data['flat_search']) {
        if ($data['blank_descr']) {
            $where[] = "{$tables['products']}.descr = ''";
        }
        if ($data['code']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.eancode" : "IFNULL(search_variants.eancode, {$tables['products']}.eancode)";
            $where[] = "({$productcode_cond_string} != '')";
        }
        if ($data['without_code']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $where[] = !$addons['product_options'] ? "({$tables['products']}.productcode = '' or {$tables['products']}.eancode = '')" : "(IFNULL(search_variants.productcode, {$tables['products']}.productcode) = '' OR IFNULL(search_variants.eancode, {$tables['products']}.eancode) = '')";
        }
        $query_joins['products_system_info'] = array('parent' => 'products', 'on' => "{$tables['products_system_info']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        if ($data['creation_date_start']) {
            $where[] = "{$tables['products_system_info']}.creation_date >= '{$data['creation_date_start']}'";
        }
        if ($data['creation_date_end']) {
            $where[] = "{$tables['products_system_info']}.creation_date <= '{$data['creation_date_end']}'";
        }
        if ($data['modify_date_start']) {
            $where[] = "{$tables['products_system_info']}.modification_date >= '{$data['modify_date_start']}'";
        }
        if ($data['modify_date_end']) {
            $where[] = "{$tables['products_system_info']}.modification_date <= '{$data['modify_date_end']}'";
        }
        if ($data['created_by']) {
            $where[] = "{$tables['products_system_info']}.creation_customer_id = '{$data['created_by']}'";
        }
        if ($data['supplier']) {
            $where[] = "{$tables['products_system_info']}.supplier_customer_id = '{$data['supplier']}'";
        }
        if ($data['sold_date_start'] || $data['sold_date_end']) {
            $query_joins['docs_items'] = array('on' => "{$tables['docs_items']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
            $query_joins['docs'] = array('on' => "{$tables['docs']}.doc_id = {$tables['docs_items']}.doc_id", 'is_inner' => 1);
            if ($data['sold_date_start']) {
                $where[] = "{$tables['docs']}.date >= '{$data['sold_date_start']}'";
            }
            if ($data['sold_date_end']) {
                $where[] = "{$tables['docs']}.date <= '{$data['sold_date_end']}'";
            }
        }
    }
    if ($data['tag']) {
        $query_joins['tags_products'] = array('on' => "{$tables['tags_products']}.product_id = {$tables['products']}.product_id", 'only_select' => 0);
        $query_joins['tags'] = array('on' => "{$tables['tags']}.tag_id = {$tables['tags_products']}.tag_id", 'only_select' => 0);
        $where[] = "{$tables['tags']}.name = '{$data['tag']}'";
    }
    //   if (in_array($current_area, array('B', 'G'))) {
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.product, {$tables['products']}.product) as product";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.descr, {$tables['products']}.descr) as descr";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.fulldescr, {$tables['products']}.fulldescr) as fulldescr";
    $query_joins['products_lng'] = array('on' => "{$tables['products_lng']}.product_id = {$tables['products']}.product_id AND {$tables['products_lng']}.code = '{$current_language}'", 'only_select' => 1);
    if ($data['by_title'] || $data['by_shortdescr'] || $data['by_fulldescr']) {
        $query_joins['products_lng']['only_select'] = 0;
    }
    //    }
    if (in_array($current_area, array('C', 'R', 'G'))) {
        if ($config['Appearance']['categories_in_products'] == '1') {
            $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['products_categories']}.category_id", 'parent' => 'products_categories', 'is_inner' => 1);
        }
        $query_joins['products_memberships'] = array('parent' => 'products', 'on' => "{$tables['products_memberships']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
    }
    if ($current_area == 'C') {
        if ($config['Appearance']['categories_in_products'] == '1') {
            $where[] = "{$tables['categories_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
            $where[] = "{$tables['categories']}.status = 1";
            $query_joins['categories_memberships']['only_select'] = 0;
            $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id", 'is_inner' => 1);
        }
        $where[] = "{$tables['products_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
        $query_joins['products_memberships']['only_select'] = 0;
    } elseif ($config['Appearance']['categories_in_products'] == '1' && $current_area == 'B') {
        $where[] = "{$tables['categories']}.status = 1";
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id", 'is_inner' => 1);
    }
    if ($config['Appearance']['categories_in_products'] == '1' && $data['get_category'] == 'Y') {
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id");
        $query_joins['categories_lng'] = array("on" => "{$tables['categories_lng']}.category_id = {$tables['categories']}.category_id and {$tables['categories_lng']}.code='{$current_language}'", "parent" => "categories");
        $fields[] = "IF({$tables['categories_lng']}.category_id IS NOT NULL AND {$tables['categories_lng']}.category != '', {$tables['categories_lng']}.category, {$tables['categories']}.category) as category";
    }
    if (isset($data['avail_min'])) {
        $where[] = "{$tables['products_warehouses_amount']}.avail >= '" . $data['avail_min'] . "'";
    }
    if (isset($data['avail_max'])) {
        $where[] = "{$tables['products_warehouses_amount']}.avail <= '" . $data['avail_max'] . "'";
    }
    # kornev, TOFIX
    if ($addons['product_options']) {
        if ($search_by_variants) {
            $query_joins['search_variants'] = array('tblname' => 'product_variants', 'on' => "search_variants.product_id = {$tables['products']}.product_id", 'only_select' => 0);
        }
        if ($current_area == 'A') {
            # kornev, TOFIX
            $query_joins['product_variants'] = array('on' => "{$tables['product_variants']}.product_id = {$tables['products']}.product_id AND {$tables['product_variants']}.variant_id = {$tables['products_prices']}.variant_id", 'parent' => 'products_prices', 'only_select' => 1);
        } else {
            $query_joins['product_variants'] = array('on' => "{$tables['product_variants']}.product_id = {$tables['products']}.product_id AND {$tables['product_variants']}.variant_id = {$tables['products_prices']}.variant_id", 'parent' => 'products_prices', 'only_select' => 1);
        }
        foreach (array('weight', 'productcode') as $property) {
            $fields[] = "ifnull({$tables['product_variants']}.{$property}, {$tables['products']}.{$property}) as " . $property;
        }
    }
    foreach (array('products_images_thumb', 'products_images_det') as $products_images_type) {
        if ($data['has_' . $products_images_type]) {
            global $available_images;
            $exclude_names_products_images = array($available_images[$products_images_type]['default_image'], '');
            if (is_array($data['exclude_filenames_' . $products_images_type])) {
                $exclude_names_products_images = array_merge($exclude_names_products_images, $data['exclude_filenames_' . $products_images_type]);
            }
            $query_joins[$products_images_type] = array('on' => $tables[$products_images_type] . ".id = {$tables['products']}.product_id AND (" . $tables[$products_images_type] . ".filename NOT IN ('" . implode("', '", $exclude_names_products_images) . "') OR " . $tables[$products_images_type] . ".image_path like 'http://%')", 'is_inner' => 1);
        }
    }
    global $allowed_products_sort_fields;
    if (!isset($allowed_products_sort_fields)) {
        $allowed_products_sort_fields = array();
    }
    if (!in_array($data['sort_field'], array('rand', 'productcode', 'title', 'orderby', 'quantity', 'price', 'product_id')) && !in_array($data['sort_field'], $allowed_products_sort_fields)) {
        $data['sort_field'] = $config['Appearance']['products_order'];
    }
    if (!empty($data['sort_field'])) {
        $direction = $data['sort_direction'] ? 'DESC' : 'ASC';
        if ($config['Appearance']['display_productcode_in_list'] != "Y" && ($current_area == 'C' || $current_area == 'B') && $data['sort_field'] == 'productcode') {
            $data['sort_field'] = 'orderby';
        }
        switch ($data['sort_field']) {
            case 'rand':
                $sort_string = 'RAND()';
                break;
            case "productcode":
                $sort_string = "{$tables['products']}.productcode {$direction}";
                break;
            case "title":
                $sort_string = "{$tables['products']}.product {$direction}";
                break;
            case "orderby":
                if ($config['Appearance']['categories_in_products'] == '1') {
                    $sort_string = "{$tables['products_categories']}.orderby {$direction}";
                } else {
                    $sort_string = "{$tables['products']}.productcode {$direction}";
                }
                break;
            case "quantity":
                $sort_string = "{$tables['products_warehouses_amount']}.avail {$direction}";
                break;
            case "price":
                $sort_string = "price {$direction}";
                break;
            case "product_id":
                $sort_string = "{$tables['products']}.product_id {$direction}";
                break;
            default:
                $sort_string = $data['sort_field'] . ' ' . $direction;
                // special case to order by rand(seed) field or custom field
        }
        global $custom_products_sort_string;
        if (!empty($custom_products_sort_string)) {
            $sort_string = $custom_products_sort_string;
        }
    } else {
        $sort_string = "{$tables['products']}.product";
    }
    if (!empty($data['sort_condition'])) {
        $sort_string = $data['sort_condition'];
    }
    /*
        if (($current_area == "C" || $current_area == "B") && $config['General']['disable_outofstock_products'] == "Y") {
            $query_joins['products_warehouses_amount'] = array(
                'tblname' => 'products_warehouses_amount',
                'on' => "$tables[products_warehouses_amount].product_id = $tables[products].product_id and $tables[products_warehouses_amount].variant_id=$tables[product_variants].variant_id and $tables[products_warehouses_amount.avail > 0",
                'only_select' => 0,
            );
        }
    */
    $groupbys[] = "{$tables['products']}.product_id";
    $orderbys[] = $sort_string;
    $orderbys[] = "{$tables['products']}.product ASC";
    if (isset($params['product_id_only']) && $params['product_id_only'] == true) {
        $fields = array($tables['products'] . '.product_id');
    }
    $search_query_count = cw_db_generate_query('count(*)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    //var_dump($search_query); die();
    if (!$data['limit'] && !$data['all']) {
        $_res = db_query($search_query_count);
        $total_items = db_num_rows($_res);
        db_free_result($_res);
    }
    # kornev, optimization, we don't need to pre-calculate the amount in some cases
    $page = $data['page'];
    if ($data['count']) {
        return $total_items;
    } elseif ($data['limit']) {
        $limit_str = " LIMIT {$data['limit']}";
    } elseif ($data['all']) {
        $limit_str = '';
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $page);
        $_objects2load = $navigation['objects_per_page'];
        $_first_object_on_page = $navigation['first_page'];
        if (isset($navigation['preload_objects'])) {
            $_objects2load += $navigation['preload_objects'];
            $_first_object_on_page = max($_first_object_on_page - $navigation['preload_objects'], 0);
        }
        $limit_str = " LIMIT {$_first_object_on_page}, {$_objects2load}";
    }
    $products = $pfr = array();
    if ($params['count_only']) {
        return array($products, $navigation, $pfr);
    }
    if ($total_items > 0 || $data['limit'] || $data['all'] || $data['attributes']) {
        $products = cw_query($search_query . $limit_str);
        if ($data['limit'] || $data['all']) {
            $items_per_page = 20;
            if (!empty($objects_per_page)) {
                $items_per_page = $objects_per_page;
            }
            $navigation = cw_core_get_navigation($target, count($products), $page, $items_per_page);
        }
        /* kornev, not used now
                if ($data['query_manufacturers'] == 'Y') {
                    $query_joins['manufacturers'] = array(
                        'on' => "$tables[products].manufacturer_id=$tables[manufacturers].manufacturer_id",
                        'is_inner' => 1,
                    );
        
                    unset($where['manuf_condition']);
                    $manuf_query = cw_db_generate_query(array("$tables[manufacturers].manufacturer", "$tables[manufacturers].manufacturer_id"), $from_tbls, $query_joins, $where, array("$tables[manufacturers].manufacturer"), $having, array("$tables[manufacturers].orderby"));
        
                    $p_manufacturers = cw_query($manuf_query);
                    if (is_array($p_manufacturers) && is_array($data['manufacturers']))
                    foreach($p_manufacturers as $k=>$v)
                        $p_manufacturers[$k]['selected'] = in_array($v['manufacturer_id'], array_keys($data['manufacturers']));
                    $smarty->assign('product_manufacturers', $p_manufacturers);
                }
        */
        # kornev, query features for the additional product filter
        if ($info_type & 1024 && !($pfr = cw_cache_get(array($search_query . $limit_str), 'PF_search'))) {
            $pfr = array();
            # kornev, we need that for the breadcrumbs
            if ($data['attributes']['substring']) {
                $pfr[] = array('attribute_id' => 'substring', 'name' => cw_get_langvar_by_name('lbl_substring'), 'type' => '', 'is_selected' => 1, 'selected' => array($data['attributes']['substring']), 'values' => array());
            }
            # kornev, firstly select all of the attributes to build the filter - without products count
            $attributes = cw_call('cw_attributes_filter', array(array('item_type' => 'P', 'pf_is_use' => 1, 'active' => 1)));
            uasort($attributes, '_sort_pf_by_pf_orderby');
            if ($attributes) {
                $att_ids = $ss_att = array();
                foreach ($attributes as $k => $v) {
                    $att_ids[] = $v['attribute_id'];
                    // Mark price attribute with special flag is_price
                    if ($v['field'] == 'price') {
                        //$attributes[$k]['attribute_id'] = $v['attribute_id'] = 'price';
                        $attributes[$k]['is_price'] = 1;
                    }
                    // If slider attr is passed in data, then prefill special array for sliders
                    if ($v['pf_display_type'] == 'S' && isset($data['attributes'][$v['attribute_id']])) {
                        $ss_att[] = $v;
                    }
                }
                $query_joins['atv'] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv.item_id and atv.attribute_id in ('" . implode("', '", $att_ids) . "') and atv.code in ('{$current_language}', '') and atv.value != ''");
                # kornev, we have to select all of the slider attributes separatelly
                // general selection of all attributes, values, prices for all products according to search query
                $attribute_query = cw_db_generate_query(array("atv.attribute_id", "atv.value", 'atv.item_id', $tables['products_prices'] . '.price'), $from_tbls, $query_joins, $where, null, null, null);
                //$atv = cw_query($attribute_query); // It takes a lot of memory and don't want return back even after unset()
                $tmp = $prices = array();
                if ($p_result = db_query($attribute_query, null)) {
                    while ($v = db_fetch_array($p_result)) {
                        if ($v['item_id']) {
                            $tmp[$v['attribute_id']][$v['value']][$v['item_id']] = $v['price'];
                            // Use price (to calculate min_price later) instead of dummy flag "1"
                        }
                        if ($v['price']) {
                            $tmp[PRICE_ATTRIBUTE_ID][$v['price']][$v['item_id']] = 1;
                        }
                    }
                    db_free_result($p_result);
                }
                # kornev, for the sliders we should select all of the values - so without the appropriate condition for the attribute;
                if ($ss_att && $config['product_filter']['is_slow_mode']) {
                    foreach ($ss_att as $id => $v) {
                        $__query_joins = $query_joins;
                        $__where = $where;
                        if ($id == 'price') {
                            unset($__where['price_min']);
                            unset($__where['price_max']);
                            $flds = array($tables['products_prices'] . '.price', $tables['products_prices'] . '.product_id');
                        } else {
                            unset($__query_joins['atv_' . $v['id']]);
                            $flds = array('atv.attribute_id', 'atv.value', 'atv.item_id');
                            //                        $__where[] = "atv_$v[id]. "
                        }
                        $attribute_query = cw_db_generate_query($flds, $from_tbls, $__query_joins, $__where, null, null, null);
                        if ($p_result = db_query($attribute_query, null)) {
                            while ($v = db_fetch_array($p_result)) {
                                if ($v['item_id']) {
                                    $tmp[$v['attribute_id']][$v['value']][$v['item_id']] = $v['price'];
                                    // Use price (to calculate min_price later) instead of dummy flag "1"
                                }
                                if ($v['price']) {
                                    $tmp[PRICE_ATTRIBUTE_ID][$v['price']][$v['item_id']] = 1;
                                }
                            }
                            db_free_result($p_result);
                        }
                    }
                }
                $atv = null;
                unset($atv, $ss_att);
                # kornev, for now the fake price attribute is used - we should move it to the attributes array
                # kornev, TOFIX - move price to attributes
                //                array_unshift($attributes, array('attribute_id' => 'price', 'name' => cw_get_langvar_by_name('lbl_price'), 'type' => 'decimal', 'field' => 'price', 'pf_display_type' => 'S', 'is_price' => 1));
                foreach ($attributes as $ka => $v) {
                    $images = array();
                    if (!$tmp[$v['attribute_id']]) {
                        continue;
                    }
                    # kornev, array_multisort problem with numbers
                    # kornev, name will be replaced for selectors
                    foreach ($tmp[$v['attribute_id']] as $k => $pids) {
                        $v['values'][$k] = array('name' => $k, 'id' => $k, 'counter' => count($pids));
                        if ($config['product_filter']['show_from_price'] == 'Y') {
                            $v['values'][$k]['min_price'] = cw_func_call('cw_product_filter_get_slider_value', array('value' => min($pids), 'is_price' => true, 'current_area' => $current_area, 'user_account' => $user_account));
                        }
                    }
                    if (isset($data['attributes'][$v['attribute_id']])) {
                        $v['is_selected'] = true;
                        $v['selected'] = $data['attributes'][$v['attribute_id']];
                    }
                    # kornev, we need to apply some order by to the fields
                    # kornev, also we have to add the images for the selectboxes and multi-selectboxes
                    $dfv = cw_call('cw_attributes_get_attribute_default_value', array('attribute_id' => $v['attribute_id']));
                    if (in_array($v['type'], array('multiple_selectbox', 'selectbox'))) {
                        $sort = $images = array();
                        if ($dfv) {
                            $prepared_dfv = array();
                            foreach ($dfv as $k => $d) {
                                $prepared_dfv[$d['attribute_value_id']] = $d;
                            }
                            foreach ($v['values'] as $k => $d) {
                                if (!$prepared_dfv[$k]) {
                                    unset($v['values'][$k]);
                                    continue;
                                }
                                $sort[$k] = $prepared_dfv[$k]['counter'];
                                $v['values'][$k]['name'] = $prepared_dfv[$k]['value'];
                                $v['values'][$k]['description'] = $prepared_dfv[$k]['description'];
                                $v['values'][$k]['facet'] = $prepared_dfv[$k]['facet'];
                                $v['values'][$k]['orderby'] = $prepared_dfv[$k]['orderby'];
                                // if the type includes swatch - find the images
                                if (in_array($v['pf_display_type'], array('W', 'E', 'G'))) {
                                    $images[$k] = $prepared_dfv[$k]['pf_image_id'];
                                }
                            }
                            # kornev, some problems with values - TOFIX - move to attributes
                            /* doesn't work
                                                        if (count($sort) != count($v['values']))
                                                        foreach($v['values'] as $k=>$d)
                                                            if (!isset($sort[$k]))
                                                                db_query("delete from $tables[attributes_values] where attribute_id='$v[attribute_id]' and value='".addslashes($k)."'");
                            */
                        }
                    } else {
                        if (isset($dfv[0]) && $dfv[0]) {
                            foreach ($v['values'] as $k => $d) {
                                $v['values'][$k]['description'] = $dfv[0]['description'];
                                $v['values'][$k]['facet'] = $dfv[0]['facet'];
                            }
                        }
                    }
                    uasort($v['values'], '_sort_pf_by_counter');
                    # kornev, if slider is used - limit the number of chunks to 50
                    if (in_array($v['pf_display_type'], array('S', 'R'))) {
                        # kornev, slider should be sorted in another way - as the deciaml/integer numbers (sql sorted it as a string)
                        ksort($v['values']);
                        $min = array_shift($v['values']);
                        $max = array_pop($v['values']);
                        if (!$max) {
                            $max = $min;
                        }
                        # kornev, slider with one value is not possible
                        if (!$max && !$v['selected']) {
                            continue;
                        }
                        $v['min_name'] = $v['min'] = $min['name'];
                        $v['max_name'] = $v['max'] = $max['name'];
                        if ($v['pf_display_type'] == 'S' && is_numeric($min['name']) && is_numeric($max['name'])) {
                            $approx_range = ($max['name'] - $min['name']) / 50;
                            $start = $min['name'];
                            $is_price = $v['is_price'] && in_array($current_area, array('G', 'C')) && $info_type & 8;
                            $values = array();
                            $values[$min['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $min['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $current = null;
                            while ($v['values'] || $current) {
                                if (!$current) {
                                    $current = array_shift($v['values']);
                                    $current['name'] = $v['type'] == 'integer' ? intval($current['name']) : floatval($current['name']);
                                    // Foolproof if numeric fields contain text
                                } else {
                                    $start_prev = $start;
                                    $start += $approx_range;
                                }
                                if ($start >= $current['name']) {
                                    if ($current['name'] > $start_prev) {
                                        # kornev, we need calculate the taxes for the price;
                                        $values[$current['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $current['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                                        $start_prev = $start;
                                        $start += $approx_range;
                                    }
                                    $current = null;
                                }
                            }
                            $values[$max['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $max['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $v['values'] = $values;
                            $v['values_counter'] = count($values);
                            //                            if ($is_price) {
                            $v['min_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $v['min'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $v['max_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $v['max'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            if ($v['selected']) {
                                foreach ($v['selected'] as $sk => $sv) {
                                    $v['selected'][$sk . '_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $sv, 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                                }
                            }
                            //                            }
                        }
                    } elseif (in_array($v['type'], array('integer', 'decimal')) && in_array($v['pf_display_type'], array('P', 'E', 'W', 'G'))) {
                        $v['values'] = cw_call('cw_product_filter_get_price_ranges', array('attribute_id' => $v['attribute_id'], $v['values']));
                        // Images collection
                        if (in_array($v['pf_display_type'], array('W', 'E', 'G'))) {
                            foreach ($v['values'] as $kk => $vv) {
                                $images[$kk] = $dfv[$kk]['pf_image_id'];
                            }
                        }
                        if (isset($data['attributes'][$v['attribute_id']])) {
                            $v['is_selected'] = true;
                            $v['selected'] = $data['attributes'][$v['attribute_id']];
                        }
                    }
                    # kornev, assign the images....
                    # kornev, TOFIX speed up is possible here
                    if ($images) {
                        foreach ($images as $kk => $dd) {
                            $v['values'][$kk]['image'] = cw_image_get('attributes_images', $dd);
                        }
                    }
                    $pfr[] = $v;
                }
                // foreach $attributes
            }
            unset($attributes, $tmp, $dfv, $prepared_dfv, $values, $images);
            cw_cache_save($pfr, array($search_query . $limit_str), 'PF_search');
        }
    }
    if ($products) {
        $cart =& cw_session_register('cart', array());
        cw_load('taxes', 'warehouse', 'cart');
        global $accl;
        cw_call('on_prepare_products_found', array(&$products, $data, $user_account, $info_type));
        $ids = array();
        $ids_options = array();
        foreach ($products as $k => $v) {
            $ids[] = $v['product_id'];
            $ids_options[$v['product_id']] = doubleval($v['price']);
        }
        # kornev, TOFIX
        if ($addons['product_options']) {
            $options_markups = array();
            if ($ids_options) {
                $options_markups = cw_get_default_options_markup_list($ids_options);
            }
            unset($ids_options);
        }
        //        $is_assigned = ($user_account['customer_id'] && cw_warehouse_is_warehouse_assigned($user_account['customer_id']));
        foreach ($products as $k => $v) {
            //            if($current_area == 'C' && $is_assigned)
            if ($current_area == 'C') {
                $products[$k]['avail'] = cw_warehouse_get_avail_for_customer($v['product_id'], $v['variant_id']);
            } elseif ($current_area == 'A') {
                $products[$k]['avails'] = cw_warehouse_get_avails($v['product_id']);
            }
            $products[$k]['display_price'] = $v['display_price'] = $v['price'];
            # kornev, TOFIX
            if ($addons['product-Options'] && !empty($v['is_product_options']) && !empty($options_markups[$v['product_id']])) {
                $products[$k]['price'] += $options_markups[$v['product_id']];
                $products[$k]['display_price'] = $products[$k]['price'];
                $v = $products[$k];
            }
            $in_cart = 0;
            if (in_array($current_area, array('C', 'G')) && !empty($cart['products']) && is_array($cart['products'])) {
                foreach ($cart['products'] as $cv) {
                    if ($cv['product_id'] == $v['product_id'] && intval($v['variant_id']) == intval($cv['variant_id'])) {
                        $in_cart += $cv['amount'];
                    }
                }
                $products[$k]['in_cart'] = $in_cart;
                $products[$k]['avail'] -= $in_cart;
                if ($products[$k]['avail'] < 0) {
                    $products[$k]['avail'] = 0;
                }
            }
            if ($info_type & 128) {
                $products[$k]['image_thumb'] = cw_image_get('products_images_thumb', $v['product_id']);
            }
            if (in_array($current_area, array('G', 'C')) && $info_type & 8) {
                $_tmp_price = $products[$k]['price'];
                $products[$k]['price'] = $products[$k]['list_price'];
                cw_get_products_taxes($products[$k], $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
                $products[$k]['list_price'] = $products[$k]['display_price'];
                $products[$k]['price'] = $_tmp_price;
                $products[$k]['taxes'] = cw_get_products_taxes($products[$k], $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
            }
            if ($products[$k]['descr'] == strip_tags($products[$k]['descr'])) {
                $products[$k]['descr'] = str_replace("\n", "<br />", $products[$k]['descr']);
            }
            if ($products[$k]['fulldescr'] == strip_tags($products[$k]['fulldescr'])) {
                $products[$k]['fulldescr'] = str_replace("\n", "<br />", $products[$k]['fulldescr']);
            }
        }
    }
    return array($products, $navigation, $pfr);
}
function cw_ps_category_delete($cat, $is_show_process = false)
{
    global $tables, $config;
    $return = cw_get_return();
    $subcats = cw_category_get_subcategory_ids($cat);
    $subcats[] = $cat;
    if (!empty($subcats) && is_array($subcats)) {
        db_exec("DELETE FROM {$tables['ps_bonus_details']} WHERE object_type = '" . PS_OBJ_TYPE_CATS . "' AND object_id IN (?)", array($subcats));
        db_exec("DELETE FROM {$tables['ps_cond_details']} WHERE object_type = '" . PS_OBJ_TYPE_CATS . "' AND object_id IN (?)", array($subcats));
    }
    return $return;
}
function cw_category_update_path($cat, $rec = false)
{
    global $tables;
    $path = array();
    $level = 0;
    cw_category_generate_path($cat, $path);
    $path[] = $cat;
    db_query("delete from {$tables['categories_parents']} where category_id='{$cat}'");
    foreach ($path as $val) {
        cw_array2insert('categories_parents', array('category_id' => $cat, 'parent_id' => $val, 'level' => $level++));
    }
    if ($rec) {
        $subcats = cw_category_get_subcategory_ids($cat);
        if (count($subcats)) {
            foreach ($subcats as $scat_id) {
                cw_category_update_path($scat_id);
            }
        }
    }
}
function cw_md_attributes_save($item_id, $item_type, $attributes, $language = null, $extra = array())
{
    # kornev, for the categories we need to distribute the params sometimes
    if ($item_type == 'C') {
        $cats[] = $item_id;
        # kornev, only domains should be updated
        $new_attributes = array('domains' => $attributes['domains']);
        // Disable this hook to avoid loop
        cw_unset_hook('cw_attributes_save', 'cw_md_attributes_save', EVENT_POST);
        if ($attributes['subcats_distribution']) {
            $subcats = cw_category_get_subcategory_ids($item_id);
            foreach ($subcats as $cat) {
                if ($cat != $item_id) {
                    cw_call('cw_attributes_save', array('item_id' => $cat, 'item_type' => 'C', 'attributes' => $new_attributes, 'language' => $language));
                    $cats[] = $cat;
                }
            }
        }
        if ($attributes['subproducts_distribution']) {
            global $user_account, $current_area;
            list($products, $tmp) = cw_func_call('cw_product_search', array('data' => array('categories' => $cats, 'categories_orig' => $cats, 'user_account' => $user_account, 'current_area' => $current_area, 'info_type' => 0, 'flat_search' => 1, 'all' => 1)));
            if (is_array($products)) {
                foreach ($products as $product) {
                    cw_call('cw_attributes_save', array('item_id' => $product['product_id'], 'item_type' => 'P', 'attributes' => $new_attributes, 'language' => $language));
                }
            }
        }
        // Return hook back
        cw_set_hook('cw_attributes_save', 'cw_md_attributes_save', EVENT_POST);
    }
    return null;
}