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

if (isset($_POST['edit_prices']))
{
	$param['id'] = to_int($_POST['edit_prices']);
}

$param['name'] = to_str($_POST['prices_name']);
$param['percent_to_basic'] = to_float($_POST['prices_percent_to_basic']);
$param['user_group_id'] = to_int($_POST['prices_users_group']);
$param['shop_shops_id'] = to_int($_POST['shop_shops_id']);
$param['shop_list_of_prices_cml_id'] = to_str($_POST['shop_list_of_prices_cml_id']);
//$param['shop_shops_id'] = to_int($_REQUEST['shop_shops_id']);


$insert_result = $shop->InsertPrice($param);

switch ($insert_result)
{
	case 0:
		{
			if (isset($_POST['edit_prices']))
			{
				show_error_message($GLOBALS['MSG_shops']['error_edit_prices']);
			}
			else
			{
				show_error_message($GLOBALS['MSG_shops']['error_add_prices']);
			}

			break;

		}
	case -1:
		{
			show_error_message($GLOBALS['MSG_shops']['error_add_edit_prices_for_group']);

			$can_show_main_form = false;
			break;
		}
		/*case -2:
		 {
			show_error_message($GLOBALS['MSG_shops']['error_add_edit_prices_for_group_100']);

			$can_show_main_form = false;
			break;
			}*/
	default:
	{
		// Пересчитываем цены
		if (isset($_REQUEST['recalculate_price']))
		{
			$query = "UPDATE shop_prices_to_item_table, shop_items_catalog_table
			SET shop_prices_to_item_value = (shop_items_catalog_price/100*{$param['percent_to_basic']})
			WHERE shop_prices_to_item_table.shop_items_catalog_item_id = shop_items_catalog_table.shop_items_catalog_item_id
			AND shop_list_of_prices_id = '{$insert_result}'";

			$DataBase->query($query);
		}

		// Устанавливаем новую цену для всех товаров магазина
		if (isset($_REQUEST['apply_for_all']))
		{
			$query = "INSERT INTO shop_prices_to_item_table
			(shop_prices_to_item_table.shop_items_catalog_item_id, shop_list_of_prices_id, shop_prices_to_item_value)
			SELECT shop_items_catalog_item_id, {$insert_result}, shop_items_catalog_price/100*{$param['percent_to_basic']}
			FROM shop_items_catalog_table 
			WHERE shop_shops_id = {$param['shop_shops_id']}";

			$DataBase->query($query);
		}

		if (isset($_POST['edit_prices']))
		{
			show_message($GLOBALS['MSG_shops']['success_edit_prices']);
		}
		else
		{
			show_message($GLOBALS['MSG_shops']['success_add_prices']);
		}

		$admin_forms = new admin_forms();
		$window_id = $admin_forms->GetWindowId();
		?><script type="text/javascript">
		$.appendInput('<?php echo $window_id?>', 'EditAddPrice', 'edit_prices', '<?php echo $insert_result?>');
		</script><?php
	}
}
?>