<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Обработчик добавления/редактирования заказа.
 *
 * Файл: /admin/shop/action/add_order.php
 *
 * @author Hostmake LLC
 * @version 5.x
 */
$param = array();
$shop = & singleton('shop');

if (isset($_REQUEST['edit_order']))
{
	$param['id'] = to_str($_REQUEST['edit_order']);
}

$date = & singleton('DateClass');
$param['order_date_time'] = $date->datetime_format_sql(to_str($_REQUEST['order_date_time']));
$param['sum'] = to_float($_REQUEST['order_sum']);

$param['status_of_pay'] = isset($_REQUEST['order_status_of_pay']);

if ($param['status_of_pay'] && isset($_REQUEST['order_date_of_pay']))
{
	// Дата не равна нулям
	if ($_REQUEST['order_date_of_pay'] != '00.00.0000 00:00:00')
	{
		$param['date_of_pay'] = $date->datetime_format_sql(to_str($_REQUEST['order_date_of_pay']));
	}
	// Иначе текущая дата
	else
	{
		$param['date_of_pay'] = date("Y-m-d H:i:s");
	}
}

$param['address'] = to_str($_REQUEST['order_address']);
$param['index'] = to_str($_REQUEST['order_index']);
$param['currency_id'] = to_str($_REQUEST['currency_id']);
$param['country_id'] = to_str($_REQUEST['country_id']);
$param['shop_city_id'] = to_str($_REQUEST['city_id']);
$param['city_area_id'] = to_str($_REQUEST['city_area_id']);
$param['phone'] = to_str($_REQUEST['order_phone']);
$param['shop_shops_id'] = to_int($_REQUEST['shop_shops_id']);
$param['location_id'] = to_int($_REQUEST['location_id']);
$param['site_user_id'] = to_int($_REQUEST['site_users_id']);
$param['shop_currency_id'] = to_int($_REQUEST['order_currency']);
$param['shop_system_of_pay_id'] = to_int($_REQUEST['system_of_pay']);
$param['shop_cond_of_delivery_id'] = to_int($_REQUEST['shop_cond_of_delivery_id']);
$param['shop_type_of_delivery_id'] = to_int($_REQUEST['shop_type_of_delivery_id']);
$param['shop_order_status_id'] = to_int($_REQUEST['shop_order_status_id']);
$param['shop_order_sending_info'] = to_str($_REQUEST['shop_order_sending_info']);
$param['shop_order_ip'] = to_str($_REQUEST['shop_order_ip']);

$order_change_status_date_time = quote_smart(to_str($_REQUEST['order_change_status_date_time']));

if ($order_change_status_date_time == '00.00.0000 00:00:00'
|| empty($order_change_status_date_time))
{
	$param['change_status_date'] = '0000-00-00 00:00:00';
}
else
{
	$param['change_status_date'] = $date->datetime_format_sql($order_change_status_date_time);
}

if (isset($_REQUEST['order_cancel_status']))
{
	$param['shop_order_cancel'] = 1;
}
else
{
	$param['shop_order_cancel'] = 0;
}

$param['description'] = to_str($_REQUEST['shop_order_description']);
$param['system_information'] = to_str($_REQUEST['shop_order_system_information']);

// Данные о заказчике.
$param['shop_order_users_name'] = to_str($_REQUEST['shop_order_users_name']);
$param['shop_order_users_surname'] = to_str($_REQUEST['shop_order_users_surname']);
$param['shop_order_users_patronymic'] = to_str($_REQUEST['shop_order_users_patronymic']);
$param['shop_order_users_email'] = to_str($_REQUEST['shop_order_users_email']);
$param['shop_order_users_company'] = to_str($_REQUEST['shop_order_users_company']);
$param['shop_order_users_fax'] = to_str($_REQUEST['shop_order_users_fax']);

$param['shop_order_account_number'] = to_str($_REQUEST['shop_order_account_number']);

// Информация о заказе до обновления
if (isset($_REQUEST['edit_order']))
{
	$prev_order_row = $shop->GetOrder($_REQUEST['edit_order']);
	$current_status = to_int($prev_order_row['shop_order_status_of_pay']);
}
else
{
	// Текущего статуса нет, установим -1
	$current_status = -1;
}

if ($shop_order_id = $shop->InsertOrder($param))
{
	// Информация о заказе получаем после обновления
	$order_row = $shop->GetOrder($shop_order_id);

	// Текущий статус НЕ соответствует установленному статусу в базе данных
	if ($param['status_of_pay'] != $current_status)
	{
		if ($param['status_of_pay'])
		{
			$affiliate = & singleton('affiliate');
			$affiliate->AcceptAffiliatePlanForSiteUsers($order_row['site_users_id'], $shop_order_id);
		}
		else
		{
			// Снимаем активность с проводок по этому заказу т.к. он отменен
			$query = "UPDATE `shop_site_users_account_table`
        	SET `shop_site_users_account_active` = '0'
        	WHERE `shop_order_id` = '$shop_order_id'";
				
			$DataBase->query($query);
		}
	}

	$aExecParam = array('shop_order_id' => $shop_order_id, 'action' => 'edit');
	
	// Предыдущие даные о заказе до редактирования
	if (isset($_REQUEST['edit_order']))
	{
		$aExecParam['prev_order_row'] = $prev_order_row;
	}
	
	// Вызываем обработчик платежной системы для события "редактирование"
	$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], $aExecParam);
	
	$admin_forms = new admin_forms();
	$window_id = $admin_forms->GetWindowId();
	?><script type="text/javascript">
	$.appendInput('<?php echo $window_id?>', 'EditAddOrder', 'edit_order', '<?php echo $shop_order_id?>');
	</script><?php
	
	if (isset($_REQUEST['edit_order']))
	{
		show_message($GLOBALS['MSG_shops']['success_edit_order']);
	}
	else
	{
		show_message($GLOBALS['MSG_shops']['success_add_order']);
	}
	
	// Если заказ добавляем нет смысла менять ему статус, он и так равен 0
	if(to_int($_REQUEST['edit_order']) > 0)
	{
		// Меняем статус выгрузки заказа
		$shop->SetUnload($shop_order_id, 0);	
	}
}
else
{
	show_error_message($GLOBALS['MSG_shops']['error_add_order']);
}

?>