$email = $user_data['email'];
 if ($usertype == 'R') {
     $usertype = 'C';
     $product_list_template =& cw_session_register("product_list_template");
     $product_list_template = 2;
 }
 $identifiers[$current_area == 'R' ? 'C' : $current_area] = array('customer_id' => $user_data['customer_id']);
 $customer_id = $user_data['customer_id'];
 if (in_array($current_area, array("C", "R"))) {
     cw_session_register("login_redirect");
     $login_redirect = 1;
 }
 // Update addresses in session from database
 $user_address =& cw_session_register('user_address', array());
 $user_address['current_address'] = cw_user_get_address($customer_id, 'current');
 $user_address['main_address'] = cw_user_get_address($customer_id, 'main');
 db_query("update {$tables['customers_system_info']} set last_login='******' where customer_id='{$customer_id}'");
 $current_language = $user_data['language'];
 $items_per_page_targets = cw_core_restore_navigation($customer_id);
 cw_include('init/lng.php');
 $cart =& cw_session_register('cart', array());
 if ($current_area == "C" && cw_is_cart_empty($cart)) {
     $cart = cw_user_get_stored_cart($customer_id);
 }
 $userinfo = cw_user_get_info($customer_id);
 $products = cw_call('cw_products_in_cart', array($cart, $userinfo));
 $cart = cw_func_call('cw_cart_calc', array('cart' => $cart, 'products' => $products, 'userinfo' => $userinfo));
 cw_event('on_login', array($customer_id, $current_area, 0));
 if (!empty($instagram_login_info['return_url'])) {
     cw_header_location($instagram_login_info['return_url']);
 } else {
function cw_user_get_info($customer_id, $info_type = 0)
{
    global $tables, $current_language, $default_user_profile_fields, $config;
    global $addons;
    $userinfo = \Customer\get($customer_id);
    if (empty($userinfo)) {
        return null;
    }
    $userinfo = array_merge($userinfo, (array) cw_query_first("SELECT membership, flag FROM {$tables['memberships']} WHERE membership_id = '{$userinfo['membership_id']}'"));
    # kornev, TOFIX
    if ($userinfo['usertype'] == 'B') {
        $userinfo['plan_id'] = cw_query_first_cell("SELECT plan_id FROM {$tables['salesman_commissions']} WHERE salesman_customer_id='{$userinfo['customer_id']}'");
    }
    if ($info_type & 1) {
        $userinfo['addresses'] = cw_user_get_addresses($customer_id);
        $userinfo['main_address'] = cw_user_get_address($customer_id, 'main');
        $userinfo['current_address'] = cw_user_get_address($customer_id, 'current');
        $address = empty($userinfo['main_address']) ? $userinfo['current_address'] : $userinfo['main_address'];
        $userinfo['firstname'] = $address['firstname'];
        $userinfo['lastname'] = $address['lastname'];
        $userinfo['fullname'] = trim($address['firstname'] . ' ' . $address['lastname']);
        unset($address);
    }
    if ($info_type & 2) {
        cw_load('crypt');
        // For security reason password must be left encrypted in userinfo data
        /*
        	$userinfo['password'] = text_decrypt($userinfo['password']);
        	if (is_null($userinfo['password']))
        	    cw_log_flag("log_decrypt_errors", "DECRYPT", "Could not decrypt password for the user ".$userinfo['customer_id'], true);
        	elseif ($userinfo['password'] !== false)
        	    $userinfo['password'] = stripslashes($userinfo['password']);
        */
    }
    if ($info_type & 4) {
        $userinfo['cc_info'] = cw_user_get_current_ccinfo($customer_id);
    }
    if ($info_type & 8) {
        cw_load('profile_fields');
        $userinfo['additional_fields'] = cw_profile_fields_get_additional($customer_id);
    }
    if ($info_type & 16) {
        if ($userinfo['usertype'] == 'B') {
            $userinfo['salesman_info'] = cw_get_salesman_info($customer_id);
        }
    }
    if ($info_type & 32) {
        $userinfo['system_info'] = cw_user_get_system_info($customer_id);
    }
    if ($info_type & 64) {
        $userinfo['additional_info'] = cw_user_get_addition_info($customer_id, $userinfo['usertype']);
        $userinfo['relations'] = cw_user_get_relations($customer_id);
    }
    if ($info_type & 256) {
        $userinfo['addresses'] = cw_user_get_addresses($customer_id);
    }
    if ($info_type & 1024) {
        $userinfo['custom_fields'] = cw_user_get_custom_fields($customer_id);
    }
    return $userinfo;
}
function cw_doc_get($doc_id, $info_type = 0)
{
    global $tables;
    global $config, $addons;
    global $app_main_dir;
    global $smarty;
    cw_load('warehouse', 'profile_fields');
    $doc = cw_query_first("select * from {$tables['docs']} where doc_id='{$doc_id}'");
    $doc['info'] = cw_query_first("select * from {$tables['docs_info']} where doc_info_id='{$doc['doc_info_id']}'");
    $doc['info']['carrier'] = cw_call('cw_shipping_get_carrier', array($doc['info']['shipping_id']));
    $doc['info']['applied_taxes'] = unserialize($doc['info']['applied_taxes']);
    $doc['info']['extra'] = unserialize($doc['info']['extra']);
    $doc['info']['extras'] = cw_call('cw_doc_get_extras_data', array($doc_id));
    $doc['userinfo'] = cw_query_first("select * from {$tables['docs_user_info']} where doc_info_id='{$doc['doc_info_id']}'");
    $doc['userinfo']['main_address'] = cw_user_get_address(null, $doc['userinfo']['main_address_id']);
    $doc['userinfo']['current_address'] = cw_user_get_address(null, $doc['userinfo']['current_address_id']);
    $fields_area = cw_profile_fields_get_area($doc['userinfo']['customer_id'], $doc['userinfo']['membership_id']);
    list($profile_sections, $profile_fields, $additional_fields) = cw_profile_fields_get_sections('U', true, $fields_area);
    $doc['userinfo']['profile_sections'] = $profile_sections;
    $doc['userinfo']['profile_fields'] = $profile_fields;
    $doc['related_docs'] = cw_doc_get_related($doc_id);
    $doc['settings'] = cw_doc_get_settings($doc['doc_info_id']);
    if ($addons['egoods']) {
        $join .= " left join {$tables['download_keys']} ON {$tables['docs_items']}.item_id={$tables['download_keys']}.item_id AND {$tables['download_keys']}.product_id={$tables['docs_items']}.product_id";
        $fields .= ", {$tables['download_keys']}.download_key, {$tables['download_keys']}.expires";
    }
    $join .= " left join {$tables['products_system_info']} on {$tables['products_system_info']}.product_id={$tables['docs_items']}.product_id";
    $fields .= ", {$tables['products_system_info']}.supplier_customer_id";
    $products = cw_query("select {$tables['products']}.*, {$tables['products']}.productcode as sku, {$tables['docs_items']}.*, IF({$tables['products']}.product_id IS NULL, 'Y', '') as is_deleted, IF({$tables['docs_items']}.product = '', {$tables['products']}.product, {$tables['docs_items']}.product) as product {$fields} FROM {$tables['docs_items']} LEFT JOIN {$tables['products']} ON {$tables['docs_items']}.product_id = {$tables['products']}.product_id {$join} WHERE {$tables['docs_items']}.doc_id='{$doc_id}'");
    $products = cw_doc_translate_products($products, $doc['info']['language']);
    $is_returns = false;
    cw_load('warehouse');
    $gift_doc_ids = cw_doc_get_related_docs($doc_id);
    $gift_doc_ids = array_unique(array_merge($gift_doc_ids, array($doc_id)));
    $giftcerts = cw_query("SELECT * {$gc_add_date} FROM {$tables['giftcerts']} WHERE doc_id in ('" . implode(',', $gift_doc_ids) . "')");
    if (!empty($giftcerts) && $config['General']['use_counties'] == "Y") {
        foreach ($giftcerts as $k => $v) {
            if (!empty($v['recipient_county'])) {
                $giftcerts[$k]['recipient_countyname'] = cw_get_county($v['recipient_county']);
            }
        }
    }
    $doc['giftcerts'] = $giftcerts;
    if ($doc['info']['giftcert_ids']) {
        $doc['info']['applied_giftcerts'] = explode('*', $doc['info']['giftcert_ids']);
        if ($doc['info']['applied_giftcerts']) {
            $tmp = array();
            foreach ($doc['info']['applied_giftcerts'] as $k => $v) {
                if (empty($v)) {
                    continue;
                }
                list($arr['giftcert_id'], $arr['giftcert_cost']) = explode(':', $v);
                $tmp[] = $arr;
            }
            $doc['info']['applied_giftcerts'] = $tmp;
        }
    }
    $doc['is_returns'] = $is_returns;
    if (cw_query_first_cell("select count(*) from {$tables['docs_items']}, {$tables['download_keys']} WHERE {$tables['docs_items']}.doc_id = '{$doc_id}' and {$tables['download_keys']}.item_id = {$tables['docs_items']}.item_id ")) {
        $doc['is_egood'] = 'Y';
    } elseif (cw_query_first_cell("select count(*) from {$tables['docs_items']}, {$tables['products']} WHERE {$tables['docs_items']}.doc_id = '{$doc_id}' and {$tables['docs_items']}.product_id={$tables['products']}.product_id AND {$tables['products']}.distribution != ''")) {
        $doc['is_egood'] = 'E';
    }
    if (preg_match("/(free_ship|percent|absolute)(?:``)(.+)/S", $doc['coupon'], $found)) {
        $doc['coupon'] = $found[2];
        $doc['coupon_type'] = $found[1];
    }
    $order['info']['extra']['tax_info']['product_tax_name'] = '';
    $_products_taxes = array();
    if ($products) {
        foreach ($products as $k => $v) {
            if ($addons['sn']) {
                $v['serial_numbers'] = cw_query("select * from {$tables['docs_items_serials']} where item_id='{$v['item_id']}'");
            }
            $v['product_options_txt'] = $v['product_options'];
            if ($v['extra_data']) {
                $v['extra_data'] = unserialize($v['extra_data']);
                if (is_array(@$v['extra_data']['display'])) {
                    foreach ($v['extra_data']['display'] as $i => $j) {
                        $v["display_" . $i] = $j;
                    }
                }
                if (is_array($v['extra_data']['taxes'])) {
                    foreach ($v['extra_data']['taxes'] as $i => $j) {
                        if ($j['tax_value'] > 0) {
                            $_products_taxes[$i] = $j['tax_display_name'];
                        }
                    }
                }
            }
            $v['original_price'] = $v['ordered_price'] = $v['price'];
            $v['price_deducted_tax'] = "Y";
            if ($v['is_deleted'] != 'Y') {
                $v['original_price'] = cw_query_first_cell("SELECT {$tables['products_prices']}.price FROM {$tables['products_prices']} WHERE {$tables['products_prices']}.product_id = '{$v['product_id']}' AND {$tables['products_prices']}.membership_id IN (0, '{$userinfo['membership_id']}') AND {$tables['products_prices']}.quantity <= '{$v['amount']}' AND {$tables['products_prices']}.variant_id = 0");
                # kornev, TOFIX
                if ($addons['product_options'] && $v['extra_data']['product_options']) {
                    list($variant, $product_options) = cw_get_product_options_data($v['product_id'], $v['extra_data']['product_options'], $userinfo['membership_id']);
                    if ($product_options === false) {
                        unset($product_options);
                    } else {
                        if (empty($variant['price'])) {
                            $variant['price'] = $v['original_price'];
                        }
                        $v['original_price'] = $variant['price'];
                        unset($variant['price']);
                        if ($product_options) {
                            foreach ($product_options as $o) {
                                if ($o['modifier_type'] == '%') {
                                    $v['original_price'] += $v['original_price'] * $o['price_modifier'] / 100;
                                } else {
                                    $v['original_price'] += $o['price_modifier'];
                                }
                            }
                        }
                        $v['product_options'] = $product_options;
                        # Check current and saved product options set
                        if (!empty($v['product_options_txt'])) {
                            $flag_txt = true;
                            # Check saved product options
                            $count = 0;
                            foreach ($v['product_options'] as $opt) {
                                if (preg_match("/" . preg_quote($opt['class'], "/") . ": " . preg_quote($opt['option_name'], "/") . "/Sm", $v['product_options_txt'])) {
                                    $count++;
                                }
                            }
                            if ($count != count($v['product_options'])) {
                                $flag_txt = false;
                            }
                            # Check current product options set
                            if ($flag_txt) {
                                $count = 0;
                                $tmp = explode("\n", $v['product_options_txt']);
                                foreach ($tmp as $txt_row) {
                                    if (!preg_match("/^([^:]+): (.*)\$/S", trim($txt_row), $match)) {
                                        continue;
                                    }
                                    foreach ($v['product_options'] as $opt) {
                                        if ($match[1] == $opt['option_name'] && $match[2] == trim($opt['name'])) {
                                            $count++;
                                            break;
                                        }
                                    }
                                }
                                if ($count != count($tmp)) {
                                    $flag_txt = false;
                                }
                            }
                            # Force display saved product options set
                            # if saved and current product options sets wasn't equal
                            if (!$flag_txt) {
                                $v['force_product_options_txt'] = true;
                            }
                        }
                        if (!empty($variant)) {
                            $v = cw_array_merge($v, $variant);
                        }
                    }
                }
            }
            $products[$k] = $v;
        }
    }
    $doc['products'] = $products;
    if (count($_products_taxes) == 1) {
        $order['info']['extra']['tax_info']['product_tax_name'] = array_pop($_products_taxes);
    }
    if ($order['coupon_type'] == "free_ship") {
        $order['shipping_cost'] = $order['coupon_discount'];
        $order['discounted_subtotal'] += $order['coupon_discount'];
    }
    $order['discounted_subtotal'] = price_format($order['discounted_subtotal']);
    # kornev, 512 is free for now (something was removed)
    if ($info_type & 1024 && $addons['pos']) {
        cw_load('pos');
        $doc['pos'] = cw_pos_get_doc_info($doc['doc_info_id']);
    }
    if ($info_type & 2048) {
        $doc['warehouse'] = cw_warehouse_get_like_user($doc['info']['warehouse_customer_id'], $doc['info']['warehouse_customer_id']);
    }
    if ($info_type & 4096) {
        $doc['quotes'] = cw_doc_get_quotes($doc_id);
    }
    if ($info_type & 8192) {
        $doc['info']['details'] = text_decrypt($doc['info']['details']);
    }
    if ($info_type & 1) {
        $doc['attributes'] = cw_func_call('cw_attributes_get', array('item_id' => $doc_id, 'item_type' => 'O'));
    }
    return $doc;
}
        if ($customer_info['main_address']['address_id']) {
            $customer_info['main_address'] = cw_user_get_address($customer_info['customer_id'], $customer_info['main_address']['address_id']);
        }
        if ($customer_info['current_address']['address_id']) {
            $customer_info['current_address'] = cw_user_get_address($customer_info['customer_id'], $customer_info['current_address']['address_id']);
        }
        $aom_orders[$doc_id]['userinfo'] = cw_doc_prepare_user_information($customer_info, $aom_orders[$doc_id]['userinfo']);
    }
    cw_header_location("index.php?target={$target}&doc_id={$doc_id}&mode=edit&js_tab=customer");
}
if ($action == 'update_customer' && $aom_orders[$doc_id]['type'] == 'O' && in_array(AREA_TYPE, array('C'))) {
    if ($customer_info['main_address']['address_id']) {
        $customer_info['main_address'] = cw_user_get_address($customer_info['customer_id'], $customer_info['main_address']['address_id']);
    }
    if ($customer_info['current_address']['address_id']) {
        $customer_info['current_address'] = cw_user_get_address($customer_info['customer_id'], $customer_info['current_address']['address_id']);
    }
    $customer_info['membership_id'] = $user_account['membership_id'];
    $customer_info['usertype'] = $user_account['usertype'];
    $aom_orders[$doc_id]['userinfo'] = cw_doc_prepare_user_information($customer_info, $aom_orders[$doc_id]['userinfo']);
    cw_header_location("index.php?target={$target}&doc_id={$doc_id}&mode=edit&js_tab=customer");
}
if ($action == 'update_totals' && in_array(AREA_TYPE, array('P', 'A', 'G'))) {
    $aom_orders[$doc_id]['info']['cause_id'] = $total_details['cause_id'];
    if ($cause_details) {
        $cause_details['invoice_date'] = cw_core_strtotime($cause_details['invoice_date']);
        $aom_orders[$doc_id]['cause_info']['doc'] = $cause_details;
    }
    if ($settings) {
        $aom_orders[$doc_id]['settings'] = $settings;
    }
    $address_id = $address_type = 0;
    $address = null;
    $action = 'load';
}
if ($action == 'load_checkout') {
    cw_load('checkout');
    $userinfo = cw_call('cw_checkout_userinfo', array($user_account));
    $smarty->assign('userinfo', $userinfo);
    $smarty->assign('is_same', $userinfo['main_address']['address_id'] == $userinfo['current_address']['address_id']);
    cw_add_ajax_block(array('id' => 'address', 'action' => 'update', 'template' => 'customer/checkout/address.tpl'), 'address');
}
if ($action == 'load') {
    if ($fill_error) {
        $address = $prefilled_address;
    } elseif (empty($address)) {
        $address = cw_user_get_address($user, $address_id);
    }
    $smarty->assign('address', $address);
    $smarty->assign('address_id', $address_id);
    //    $smarty->assign('is_main', $is_main);
    $smarty->assign('name_prefix', 'update_fields[address][' . (in_array($address_type, array('main', 'current'), true) ? $address_type : $address_id) . ']');
    cw_add_ajax_block(array('id' => in_array($address_type, array('main', 'current'), true) ? $address_type . '_address' : 'address', 'action' => 'update', 'template' => 'main/users/sections/address_modify.tpl'), $address_type . '_address');
}
if ($action == 'set_main' || $action == 'set_current') {
    $field = $action == 'set_main' ? 'main' : 'current';
    Customer\Address\setAddressType($user, $field, $address_id);
    cw_user_check_addresses($user);
    // For correct shipping cost calculate after address changing
    cw_load('user');
    $user_address =& cw_session_register('user_address');
    $user_address = array();