<?php

global $docs_type;
$docs_type = 'O';
cw_load('doc');
if ($action == 'add') {
    $doc_id = cw_doc_create_empty($docs_type . '_');
    // Create temporary doc_type until first POST request
    cw_header_location("index.php?target={$target}&doc_id={$doc_id}&mode=edit");
} elseif ($doc_id) {
    cw_include('include/orders/order.php');
} else {
    cw_include('include/orders/orders.php');
}
$smarty->assign('page_acl', '__18');
function cw_doc_place_order($params, $return = null)
{
    extract($params);
    global $cart, $discount_coupon, $smarty, $config, $addons, $salesman, $adv_campaign_id, $salesman_click_id;
    global $tables, $to_customer;
    global $wlid;
    global $app_main_dir, $REMOTE_ADDR, $PROXY_IP, $CLIENT_IP, $add_to_cart_time;
    $mintime = 10;
    cw_load('web');
    cw_lock('cw_doc_place_order');
    $doc_ids = array();
    foreach ($cart['orders'] as $cart_order_idx => $current_order) {
        # $extra - one serialized field in doc details
        # 	use $extra as storage of details which will not be used for orders search or aggregate
        # $extras - key=>value pairs in doc extras table
        # 	use $extras for scalar values which can be used in SQL queries
        $extra = cw_event('on_place_order_extra', array($current_order));
        $extra['additional_fields'] = $userinfo['additional_fields'];
        if (!empty($current_order['info']['shipping_no_offer'])) {
            $extra['shipping_no_offer'] = $current_order['info']['shipping_no_offer'];
        }
        $extras = cw_event('on_place_order_extras', array($current_order));
        //$extras['ip'] = $CLIENT_IP;
        //$extras['proxy_ip'] = $PROXY_IP;
        # kornev, each doc has got the same attributes as the other elements, like products
        # kornev, the attributes should be defined in the params by the pre function
        $doc_id = cw_doc_create_empty($order_type, array('warehouse_customer_id' => $current_order['warehouse_customer_id']), $params['prefix'], array(), $return['attributes']);
        $cart['orders'][$cart_order_idx]['created_doc_id'] = $doc_id;
        $extra['tax_info'] = array('display_taxed_order_totals' => $config['Taxes']['display_taxed_order_totals'], 'display_cart_products_tax_rates' => $config['Taxes']['display_cart_products_tax_rates'] == "Y", 'taxed_subtotal' => $current_order['display_subtotal'], 'taxed_discounted_subtotal' => $current_order['display_discounted_subtotal'], 'taxed_shipping' => $current_order['display_shipping_cost']);
        $giftcert_discount = $current_order['info']['giftcert_discount'];
        $applied_taxes = addslashes(serialize($current_order['info']['taxes']));
        $discount_coupon = $current_order['coupon'];
        if (!empty($current_order['coupon'])) {
            $current_order['coupon'] = cw_query_first_cell("SELECT coupon_type FROM {$tables['discount_coupons']} WHERE coupon='" . addslashes($current_order['coupon']) . "'") . "``" . $current_order['coupon'];
        }
        $current_order['userinfo'] = $userinfo;
        $current_order['new'] = true;
        // Flag can be used in cw_doc_update to differ just placed empty doc from update of existing doc
        $current_order['info']['shipping_id'] = $cart['info']['shipping_id'];
        $current_order['info']['payment_id'] = $cart['info']['payment_id'];
        $current_order['info']['payment_label'] = $cart['info']['payment_label'];
        $current_order['info']['quote_doc_id'] = isset($cart['info']['quote_doc_id']) ? $cart['info']['quote_doc_id'] : null;
        $current_order['info']['details'] = addslashes(cw_crypt_text($order_details));
        $current_order['info']['customer_notes'] = addslashes($customer_notes);
        if ($config['Appearance']['show_cart_summary'] == 'Y') {
            $current_order['info']['shipping_id'] = $cart['info']['shipping_arr'][$current_order['warehouse_customer_id']];
        }
        $current_order['info']['extra'] = $extra;
        $current_order['info']['extras'] = $_extras;
        $current_order['status'] = $order_status;
        $doc_info = cw_doc_get_basic_info($doc_id);
        $current_order['info']['doc_info_id'] = $doc_info['doc_info_id'];
        $current_order['info']['warehouse_customer_id'] = $current_order['warehouse_customer_id'];
        $current_order['userinfo']['main_address']['address_id'] = $doc_info['main_address_id'];
        $current_order['userinfo']['current_address']['address_id'] = $doc_info['current_address_id'];
        cw_log_add('doc_placed', array('doc_id' => $doc_id, 'current_order' => $current_order, 'cart' => $cart));
        cw_call('cw_doc_update', array($doc_id, $current_order));
        $doc_ids[] = $doc_id;
        $order = cw_call('cw_doc_get', array($doc_id));
        if ($discount_coupon) {
            // artem, TODO: no SQL
            $_per_user = cw_query_first_cell("SELECT per_user FROM {$tables['discount_coupons']} WHERE coupon='{$discount_coupon}' LIMIT 1");
            if ($_per_user == "Y") {
                $_need_to_update = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['discount_coupons_login']} WHERE coupon='{$discount_coupon}' AND customer_id='" . intval($userinfo['customer_id']) . "' LIMIT 1");
                if ($_need_to_update > 0) {
                    db_query("UPDATE {$tables['discount_coupons_login']} SET times_used=times_used+1 WHERE coupon='{$discount_coupon}' AND customer_id='" . intval($userinfo['customer_id']) . "'");
                } else {
                    db_query("INSERT INTO {$tables['discount_coupons_login']} (coupon, customer_id, times_used) VALUES ('{$discount_coupon}', '" . intval($userinfo['customer_id']) . "', '1')");
                }
            } else {
                db_query("UPDATE {$tables['discount_coupons']} SET times_used=times_used+1 WHERE coupon='{$discount_coupon}'");
                db_query("UPDATE {$tables['discount_coupons']} SET status='U' WHERE coupon='{$discount_coupon}' AND times_used=times");
            }
            $discount_coupon = "";
        }
        # Mail template processing
        $admin_notify = $order_status == "Q" && $config['Email']['enable_order_notif'] == "Y" || $order_status == "I" && $config['Email']['enable_init_order_notif'] == "Y";
        $customer_notify = $order_status == "Q" || $order_status == "I" && $config['Email']['enable_init_order_notif_customer'] == "Y";
        $doc_data = $doc_data_customer = cw_call('cw_doc_get', array($doc_id));
        if ($customer_notify) {
            $to_customer = $userinfo['language'] ? $userinfo['language'] : $config['default_customer_language'];
            $doc_data_customer['products'] = cw_doc_translate_products($doc_data['products'], $to_customer);
            $smarty->assign('doc_data', $doc_data_customer);
            if ($doc_data['info']['layout_id']) {
                $layout = cw_web_get_layout_by_id($doc_data['info']['layout_id']);
            } else {
                $layout = cw_call('cw_web_get_layout', array('docs_' . $doc_data['type']), true);
            }
            $smarty->assign('layout_data', $layout);
            $smarty->assign('info', $doc_data['info']);
            $smarty->assign('products', $doc_data_customer['products']);
            $smarty->assign('order', $doc_data);
            $smarty->assign('doc', $doc_data);
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $userinfo['email'], 'mail/docs/customer_subj.tpl', 'mail/docs/customer.tpl', null, false, true));
            $smarty->assign('is_email_invoice', 'N');
        }
        if ($admin_notify) {
            # Notify orders department by email
            $smarty->assign('doc_data', $doc_data);
            $smarty->assign('usertype_layout', 'A');
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($userinfo['email'], $config['Company']['orders_department'], 'mail/docs/admin_subj.tpl', 'mail/docs/admin.tpl', $config['default_admin_language'], true));
            $smarty->assign('is_email_invoice', 'N');
            $smarty->assign('usertype_layout', '');
            # Notify warehouse (or warehouses) by email
            if ($config['Email']['send_notifications_to_warehouse'] == "Y") {
                $pr_result = cw_query_first("SELECT email, language FROM {$tables['customers']} WHERE customer_id='{$current_order['warehouse_customer_id']}'");
                $prov_email = $pr_result['email'];
                if ($prov_email != $config['Company']['orders_department']) {
                    $to_customer = $pr_result['language'];
                    if (empty($to_customer)) {
                        $to_customer = $config['default_admin_language'];
                    }
                    $smarty->assign('is_email_invoice', 'Y');
                    cw_call('cw_send_mail', array($userinfo['email'], $prov_email, 'mail/docs/admin_subj.tpl', 'mail/docs/admin.tpl'));
                    $smarty->assign('is_email_invoice', 'N');
                }
            }
        }
        if ($addons['survey'] && AREA_TYPE == 'C') {
            cw_load('surveys');
            cw_check_surveys_events("OPL", $doc_data);
        }
        //cw_call('cw_doc_save_history_totals_by_customer', array(array(intval($userinfo['customer_id']))));
        cw_call('cw_doc_save_history_categories', array(array($doc_id)));
        cw_call('cw_doc_save_history_attributes', array(array($doc_id)));
    }
    # Send notifications to orders department and warehouses when product amount in stock is low
    foreach ($cart['products'] as $product) {
        if (!empty($product['distribution']) && $addons['egoods']) {
            continue;
        }
        # kornev, TOFIX
        if ($addons['product_options'] && $product['extra_data']['product_options']) {
            $avail_now = cw_get_options_amount($product['extra_data']['product_options'], $product['product_id']);
        } else {
            $avail_now = cw_query_first_cell("SELECT avail FROM {$tables['products_warehouses_amount']} WHERE product_id='" . $product['product_id'] . "' AND warehouse_customer_id ='" . $product['warehouse_customer_id'] . "'");
        }
        if ($product['low_avail_limit'] >= $avail_now && $config['Email']['eml_lowlimit_warning'] == 'Y') {
            # Mail template processing
            $product['avail'] = $avail_now;
            $smarty->assign('product', $product);
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $config['Company']['orders_department'], 'mail/lowlimit/subj.tpl', 'mail/lowlimit/body.tpl'));
            $pr_result = cw_query_first("SELECT email, language FROM {$tables['customers']} WHERE customer_id='" . $product['warehouse_customer_id'] . "'");
        }
    }
    cw_unlock('cw_doc_place_order');
    return $doc_ids;
}
<?php

if (!$addons['Salesman']) {
    cw_header_location('index.php');
}
$docs_type = 'B';
if ($action == 'add') {
    cw_load('doc');
    $doc_id = cw_doc_create_empty($docs_type, array('salesman_customer_id' => $customer_id));
    cw_header_location("index.php?target={$target}&doc_id={$doc_id}&mode=edit");
} elseif ($doc_id) {
    include $app_main_dir . '/include/orders/order.php';
} else {
    $search_data =& cw_session_register('search_data');
    $search_data['orders'][$docs_type]['basic']['salesman_customer_id'] = $customer_id;
    include $app_main_dir . '/include/orders/orders.php';
}
            $top_message = array('content' => cw_get_langvar_by_name('lbl_dest_source_equals'), 'type' => 'E');
        }
    } else {
        $aom_orders[$doc_id]['info']['company_id'] = $warehouse_info['company_id'];
        cw_aom_update_warehouse($aom_orders[$doc_id], $warehouse_info['customer_id']);
    }
}
if ($action && $aom_orders[$doc_id]['saved']) {
    $error_message = cw_get_langvar_by_name('txt_aom_already_printed');
}
if ($action == 'save_doc' && !$aom_orders[$doc_id]['saved']) {
    if ($aom_orders[$doc_id] && $aom_orders[$doc_id]['info']['total'] >= 0 && count($aom_orders[$doc_id]['products'])) {
        if ($aom_orders[$doc_id]['type'] == 'G' && $config['pos']['is_use_printer'] != 'Y' && AREA_TYPE == 'G') {
            $aom_orders[$doc_id]['type'] = 'I';
        }
        $aom_orders[$doc_id]['doc_id'] = cw_doc_create_empty($aom_orders[$doc_id]['type']);
        $doc_info = cw_doc_get_basic_info($aom_orders[$doc_id]['doc_id']);
        $aom_orders[$doc_id]['info']['doc_info_id'] = $doc_info['doc_info_id'];
        $aom_orders[$doc_id]['userinfo']['main_address']['address_id'] = $doc_info['main_address_id'];
        $aom_orders[$doc_id]['userinfo']['current_address']['address_id'] = $doc_info['current_address_id'];
        cw_aom_update_order($aom_orders[$doc_id], $is_invoice);
        $aom_orders[$doc_id]['saved'] = 1;
        # for pos, generate invoice if required
        if ($aom_orders[$doc_id]['type'] == 'G' && $is_invoice) {
            cw_doc_make_full_relation('I', $aom_orders[$doc_id]['doc_id']);
        }
    } else {
        $error_message = cw_get_langvar_by_name('txt_aom_total_is_incorrect');
    }
}
if (!$aom_orders[$doc_id]['saved']) {