function cw_shipping_get($shipping_id)
{
    global $tables;
    $shipping = cw_query_first("select s.*, sc.addon from {$tables['shipping']} as s, {$tables['shipping_carriers']} as sc where sc.carrier_id = s.carrier_id and shipping_id='{$shipping_id}'");
    $shipping['cod_type_ids'] = cw_query_key("select cod_type_id from {$tables['shipping_cods']} where shipping_id='{$shipping_id}'");
    return $shipping;
}
function cw_product_get($params, $return = null)
{
    extract($params);
    global $customer_id, $customer_id_type, $current_area, $cart, $current_location;
    global $current_language, $tables, $config, $addons;
    cw_load('files', 'taxes', 'tags');
    $lang = $lang ? $lang : $current_language;
    $variant_id = $variant_id ? $variant_id : 0;
    $amount = intval($amount > 0 ? $amount : 1);
    $fields = $from_tbls = $query_joins = $where = array();
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $from_tbls[] = 'products';
    $where[] = "{$tables['products']}.product_id='{$id}'";
    # kornev
    # customer area - all of the checkings
    # pos area - not check for membership, just available for sale property
    if (in_array($current_area, array('C'))) {
        $memberships = array(0);
        if ($user_account['membership_id'] > 0) {
            $memberships[] = intval($user_account['membership_id']);
        }
        $where[] = "{$tables['products_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
        $where[] = "{$tables['products_prices']}.quantity <= {$amount} and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")";
        if ($config['Appearance']['categories_in_products'] == '1') {
            $where[] = "{$tables['categories_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
            $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id", 'pos' => '0', 'is_straight' => 1);
            $query_joins['categories'] = array('on' => "{$tables['products_categories']}.category_id = {$tables['categories']}.category_id", 'parent' => 'products_categories');
            $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['categories']}.category_id", 'parent' => 'categories', 'is_straight' => 1);
        }
        $where[] = "{$tables['products']}.status in ('" . implode("', '", cw_core_get_required_status($current_area)) . "')";
    } elseif (in_array($current_area, array('G'))) {
        $where[] = "{$tables['products']}.product_id = {$tables['products_prices']}.product_id AND {$tables['products_prices']}.quantity <= {$amount} and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")";
    }
    $fields[] = "{$tables['products']}.*";
    $query_joins['products_warehouses_amount'] = array('on' => "{$tables['products']}.product_id = {$tables['products_warehouses_amount']}.product_id and {$tables['products_warehouses_amount']}.warehouse_customer_id=0 and {$tables['products_warehouses_amount']}.variant_id='{$variant_id}'");
    $in_cart = 0;
    if ($current_area == 'C' && !empty($cart) && !empty($cart['products'])) {
        foreach ($cart['products'] as $cart_item) {
            if ($cart_item['product_id'] == $id) {
                $in_cart += $cart_item['amount'];
            }
        }
    }
    $fields[] = "{$tables['products_warehouses_amount']}.avail-{$in_cart} AS avail";
    # kornev, TOFIX
    if ($addons['product_options'] && in_array($current_area, array('A', 'P'))) {
        $query_joins['product_variants'] = array('on' => "{$tables['products']}.product_id = {$tables['product_variants']}.product_id");
        $fields[] = "IF({$tables['product_variants']}.product_id IS NULL, '', 'Y') as is_variants";
    }
    /*
        if ($addons['manufacturers']) {
            $query_joins['manufacturers'] = array(
                'on' => "$tables[manufacturers].manufacturer_id = $tables[products].manufacturer_id",
            );
            $fields[] = "$tables[manufacturers].manufacturer";
        }
    */
    // statistic
    $fields[] = "{$tables['products_stats']}.views_stats";
    $fields[] = "{$tables['products_stats']}.sales_stats";
    $fields[] = "{$tables['products_stats']}.del_stats";
    $fields[] = "{$tables['products_stats']}.add_to_cart";
    $query_joins['products_stats'] = array('on' => "{$tables['products_stats']}.product_id = {$tables['products']}.product_id");
    if ($current_area == 'A' || $current_area == 'P') {
        $fields[] = "{$tables['products_prices']}.price";
        $fields[] = "{$tables['products_prices']}.list_price";
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id={$tables['products']}.product_id AND {$tables['products_prices']}.variant_id = '{$variant_id}' and {$tables['products_prices']}.quantity <= {$amount}");
    } else {
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id={$tables['products']}.product_id", 'is_inner' => 1);
        # kornev, find the min price and select only this record.
        $fields[] = "min({$tables['products_prices']}.price) as price";
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "min({$tables['products_prices']}.list_price) as list_price";
    }
    $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";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.features_text, {$tables['products']}.features_text) as features_text";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.specifications, {$tables['products']}.specifications) as specifications";
    $query_joins['products_lng'] = array('on' => "{$tables['products_lng']}.code='{$lang}' AND {$tables['products_lng']}.product_id = {$tables['products']}.product_id");
    if (in_array($current_area, array('C', 'G', 'S'))) {
        $fields[] = "{$tables['products_flat']}.*";
        $query_joins['products_flat'] = array('on' => "{$tables['products']}.product_id = {$tables['products_flat']}.product_id");
        if ($current_area == 'C') {
            $query_joins['products_memberships'] = array('on' => "{$tables['products_memberships']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        }
    }
    if ($config['Appearance']['categories_in_products'] == '1') {
        $fields[] = "{$tables['products_categories']}.category_id";
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id");
        $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id and {$tables['products_categories']}.main=1", 'pos' => '0', 'is_straight' => 1);
    }
    $fields[] = "{$tables['products']}.product_id";
    $query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, array("{$tables['products']}.product_id"), array(), array());
    $product = cw_query_first($query);
    # Error handling
    if (!$product || $current_area == 'C' && !$product['category_id'] && $config['Appearance']['categories_in_products'] == '1') {
        return false;
    }
    $product['system'] = cw_call('cw_product_get_system_info', array($product['product_id']));
    $product['attribute_class_ids'] = cw_func_call('cw_items_attribute_classes_get', array('item_id' => $product['product_id'], 'item_type' => 'P', 'for_product_modify' => $for_product_modify));
    if ($info_type & 1) {
        $product['membership_ids'] = cw_query_key("select membership_id from {$tables['products_memberships']} where product_id = '{$product['product_id']}'");
    }
    # kornev, TOFIX
    if ($info_type & 64 && $product['variant_id'] && $addons['product_options']) {
        $tmp = cw_query_first("SELECT * FROM {$tables['product_variants']} WHERE variant_id = '{$product['variant_id']}'");
        if (!empty($tmp)) {
            cw_unset($tmp, "def");
            $product = cw_array_merge($product, $tmp);
        } else {
            cw_unset($product, 'variant_id');
        }
    }
    if ($info_type & 128) {
        cw_load('image');
        $product['image_thumb'] = cw_image_get('products_images_thumb', $id);
    }
    if ($info_type & 512) {
        $product['image_det'] = cw_image_get('products_images_det', $id);
        # kornev, TOFIX
        if (in_array($current_area, array('C', 'B')) && $product['variant_id'] && $addons['product_options']) {
            $var_image = cw_image_get('products_images_var', $id);
            if (!$var_image['is_default']) {
                $product['image_det'] = $var_image;
            }
        }
    }
    # TOFIX
    if (in_array($current_area, array('C', 'B', 'G'))) {
        if (!$addons['egoods']) {
            $product['distribution'] = '';
        }
        $product['display_price'] = $product['price'];
        if ($current_area == 'C' && $info_type & 8) {
            $_tmp_price = $product['price'];
            $product['price'] = $product['list_price'];
            cw_get_products_taxes($product, $user_account);
            $product['list_price_net'] = $product['list_price'];
            $product['list_price'] = $product['taxed_price'];
            $product['price'] = $_tmp_price;
        }
        $product['taxes'] = cw_get_products_taxes($product, $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
    }
    if (in_array($current_area, array('C', 'B'))) {
        $product['descr'] = cw_eol2br($product['descr']);
        $product['fulldescr'] = cw_eol2br($product['fulldescr']);
    }
    $product['uns_shippings'] = unserialize($product['shippings']);
    $product['tags'] = cw_tags_get_product_tags($id);
    if ($info_type & 4096 && $product['warranty_id']) {
        $wr = cw_get_warranty($product['warranty_id'], $lang);
        $product['warranties'] = $wr['body'];
    }
    // TODO: move to addon as on_product_get handler
    if ($info_type & 8192) {
        cw_load('warehouse');
        if ($addons['warehouse']) {
            if (AREA_TYPE == 'A') {
                $product['avail_ordered'] = cw_warehouse_get_avail($id, 0, 'avail_ordered');
                $product['avail_sold'] = cw_warehouse_get_avail($id, 0, 'avail_sold');
                $product['avail_reserved'] = cw_warehouse_get_avail($id, 0, 'avail_reserved');
            } elseif (AREA_TYPE == 'P') {
                $product['avail'] = cw_warehouse_get_warehouse_avail($customer_id, $id);
                $product['avail_ordered'] = cw_warehouse_get_warehouse_avail($customer_id, $id, 'avail_ordered');
            } else {
                // TOFIX:  $product['avail'] becomes different meanings when info_type & 8192 flag is raised or not
                // without flag - avail of all variants without products already in cart
                // with flag - total avail as set in admin per variant
                //                $product['avail'] = cw_warehouse_get_avail_for_customer($id, $product['variant_id']);
                //                $product['avails']= cw_warehouse_get_avails_customer($id);
                $product['avail'] = cw_warehouse_get_avail_for_customer($id, $product['variant_id']);
            }
        } else {
            $product['avails'] = cw_warehouse_get_avails_customer($id, $product['avail'] + $product['avail_ordered']);
        }
    }
    return $product;
}
function cw_payment_get($payment_id, $language = '')
{
    global $tables;
    $language = $language ? $language : $current_language;
    $payment = cw_query_first("select pm.*, ifnull(pml.title, pm.title) as title from {$tables['payment_methods']} as pm left join {$tables['payment_methods_lng']} as pml on pm.payment_id=pml.payment_id and pml.code='{$language}' where pm.payment_id='{$payment_id}' order by pm.orderby, pm.title");
    $payment['web'] = cw_query_first("select ps.* from {$tables['payment_settings']} as ps where ps.payment_id='{$payment_id}'");
    $payment['quotes'] = cw_query("select * from {$tables['payment_quotes']} where payment_id='{$payment_id}'");
    $payment['memberships'] = cw_query_key("select membership_id from {$tables['payment_methods_memberships']} where payment_id = '{$payment_id}'");
    $payment['shippings'] = cw_query_key("select shipping_id from {$tables['payments_shippings']} where payment_id = '{$payment_id}'");
    return $payment;
}
                if (!empty($v)) {
                    $posted_data['default_value'][] = array('attribute_value_id' => $posted_data['default_values_multiselect_id'][$k], 'value' => $v, 'is_default' => $posted_data['default_values_multiselect_is_default'][$k], 'image_id' => $posted_data['default_multiselect_images'][$k], 'pf_image_id' => $posted_data['default_multiselect_pf_images'][$k], 'active' => $posted_data['default_values_multiselect_active'][$k], 'orderby' => $posted_data['default_values_multiselect_orderby'][$k], 'facet' => $posted_data['default_values_multiselect_facet'][$k], 'description' => addslashes(html_entity_decode($posted_data['default_values_multiselect_description'][$k], ENT_QUOTES)));
                }
            }
        }
    } else {
        if (is_array($posted_data['default_values_select'])) {
            foreach ($posted_data['default_values_select'] as $k => $v) {
                if (!empty($v)) {
                    $value_key = is_numeric($posted_data['default_values_select_from'][$k]) && is_numeric($posted_data['default_values_select_to'][$k]) ? $posted_data['default_values_select_from'][$k] . '-' . $posted_data['default_values_select_to'][$k] : '';
                    $posted_data['default_value'][] = array('attribute_value_id' => $posted_data['default_values_select_id'][$k], 'value' => $v, 'value_key' => $value_key, 'is_default' => $k == $posted_data['default_values_select_is_default'], 'image_id' => $posted_data['default_select_images'][$k], 'pf_image_id' => $posted_data['default_select_pf_images'][$k], 'active' => $posted_data['default_values_select_active'][$k], 'orderby' => $posted_data['default_values_select_orderby'][$k], 'facet' => $posted_data['default_values_select_facet'][$k], 'description' => addslashes(html_entity_decode($posted_data['default_values_select_description'][$k], ENT_QUOTES)));
                }
            }
        }
    }
    $existing = cw_query_key("select attribute_value_id from {$tables['attributes_default']} where attribute_id='{$attribute_id}'");
    if (is_array($posted_data['default_value'])) {
        foreach ($posted_data['default_value'] as $v) {
            cw_call('cw_attributes_update_default_value', array('attribute_id' => $attribute_id, 'data' => $v, 'language' => $edited_language));
            if ($v['attribute_value_id']) {
                unset($existing[$v['attribute_value_id']]);
            }
        }
    }
    if (count($existing)) {
        cw_call('cw_attributes_delete_values', array(array_keys($existing)));
    }
    cw_header_location('index.php?target=attribute_options&attribute_id=' . $attribute_id);
}
$images = cw_image_get_list('attributes_images', $attribute_id, 0);
$smarty->assign('images', $images);
function cw_category_get($params, $return = null)
{
    extract($params);
    global $current_area, $tables, $current_language, $user_account;
    global $app_main_dir, $current_location, $config;
    $cat = intval($cat);
    $fields = $from_tbls = $query_joins = $where = array();
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $from_tbls[] = 'categories';
    $fields[] = "{$tables['categories']}.*";
    $query_joins['categories_subcount'] = array('on' => "{$tables['categories_subcount']}.category_id = {$tables['categories']}.category_id" . ($current_area == "C" || $current_area == "B" ? " AND {$tables['categories_subcount']}.membership_id = '" . @$user_account['membership_id'] . "'" : ""));
    $query_joins['c_memb'] = array('tblname' => 'categories_memberships', 'on' => "c_memb.category_id = {$tables['categories']}.category_id");
    if ($current_area == "C" || $current_area == "B") {
        $fields[] = "{$tables['categories_subcount']}.subcategory_count";
    } else {
        $fields[] = "MAX({$tables['categories_subcount']}.subcategory_count) as subcategory_count";
    }
    $lang = $lang ? $lang : $current_language;
    $query_joins['c_lng'] = array('tblname' => 'categories_lng', 'on' => "c_lng.category_id = {$tables['categories']}.category_id and c_lng.code='{$lang}'");
    $fields[] = "IFNULL(c_lng.category, {$tables['categories']}.category) as category";
    $fields[] = "IFNULL(c_lng.description, {$tables['categories']}.description) as description";
    $fields[] = "{$tables['categories']}.category as category_name_orig";
    if (in_array($current_area, array('C', 'B'))) {
        $where[] = "{$tables['categories']}.status=1";
        $where[] = "(c_memb.membership_id IN (0, '" . $user_account['membership_id'] . "') OR c_memb.membership_id IS NULL)";
    }
    $where[] = "{$tables['categories']}.category_id='{$cat}'";
    $groupbys[] = "{$tables['categories']}.category_id";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $category = cw_query_first($search_query);
    if (!$category) {
        return false;
    }
    $category['attribute_class_ids'] = cw_func_call('cw_items_attribute_classes_get', array('item_id' => $category['category_id'], 'item_type' => 'C'));
    $category['membership_ids'] = cw_query_key("select membership_id from {$tables['categories_memberships']} where category_id = '{$cat}'");
    $category['image'] = cw_image_get('categories_images_thumb', $cat);
    return $category;
}
function cw_attributes_create_attribute($params, $return)
{
    global $current_language, $config, $tables;
    extract($params);
    $language = $language ? $language : $current_language;
    $lng_data = $data;
    if ($attribute_id && $language != $config['default_admin_language']) {
        cw_unset($data, 'name');
    }
    $data['field'] = cw_call('cw_attributes_cleanup_field', array($data['field']));
    if ($attribute_id) {
        $attribute_id = $data['attribute_id'];
        cw_array2update('attributes', $data, "attribute_id='{$attribute_id}'");
    } else {
        $attribute_id = cw_array2insert('attributes', $data, 1);
    }
    cw_func_call('cw_attributes_update_lng', array('attribute_id' => $attribute_id, 'data' => $lng_data, 'language' => $language));
    if (in_array($data['type'], array('selectbox', 'multiple_selectbox'))) {
        # kornev, we should remove not updated attributes;
        if ($config['edit_attribute_options_together'] == 'Y') {
            $existing = cw_query_key("select attribute_value_id from {$tables['attributes_default']} where attribute_id='{$attribute_id}'");
            if (is_array($data['default_value'])) {
                foreach ($data['default_value'] as $v) {
                    cw_call('cw_attributes_update_default_value', array('attribute_id' => $attribute_id, 'data' => $v, 'language' => $language));
                    if ($v['attribute_value_id']) {
                        unset($existing[$v['attribute_value_id']]);
                    }
                }
            }
            if (count($existing)) {
                cw_call('cw_attributes_delete_values', array(array_keys($existing)));
            }
        }
    } else {
        $counter = cw_query_first_cell("select count(*) from {$tables['attributes_default']} where attribute_id='{$attribute_id}'");
        if ($counter == 0) {
            cw_array2insert('attributes_default', array('attribute_id' => $attribute_id));
        }
        $data['attribute_value_id'] = cw_query_first_cell("select attribute_value_id from {$tables['attributes_default']} where attribute_id='{$attribute_id}' and is_default=1");
        $data['value'] = $data['default_value'] ? $data['default_value'] : $data['value'];
        $data['facet'] = $data['default_values']['facet'];
        $data['description'] = $data['default_values']['description'];
        $data['is_default'] = 1;
        unset($data['default_values']);
        # kornev, the text attribute might be multilng, for the other attributes - set the default lng
        if (in_array($data['type'], array('text', 'textarea'))) {
            cw_call('cw_attributes_update_default_value', array($attribute_id, $data, $language));
        } else {
            cw_call('cw_attributes_update_default_value', array($attribute_id, $data, $config['default_admin_language']));
        }
    }
    cw_call('cw_attributes_init');
    return $attribute_id;
}