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

if (isset($_REQUEST['shops_id']))
{
	$param['id'] = to_int($_REQUEST['shops_id']);

	$id = $param['id'];

	$param_shop['cache_off'] = true;

	$res = $shop->GetShop($id, $param_shop);

	$oldfile = $res['shop_watermark_file'];
}
else
{
	$oldfile = '';
}

/* Получаем переданные параметры */
$param['shop_dir_id'] = to_int($_REQUEST['current_shop_dir_id']);
$param['shop_format_date'] = to_str($_REQUEST['shop_format_date']);
$param['shop_format_datetime'] = to_str($_REQUEST['shop_format_datetime']);
$param['shop_company_id'] = to_int($_REQUEST['shop_company_id']);
$param['site_id'] = CURRENT_SITE;
$param['name'] = to_str($_REQUEST['shop_name']);
$param['description'] = to_str($_REQUEST['shop_description']);
$param['max_size_small_image'] = to_int($_REQUEST['max_size_small_image']);
$param['max_size_big_image'] = to_int($_REQUEST['max_size_big_image']);
$param['shop_country_id'] = to_int($_REQUEST['shop_country_id']);
$param['shop_currency_id'] = to_int($_REQUEST['shop_currency_id']);
$param['shop_order_status_id'] = to_int($_REQUEST['shop_order_status_id']);
$param['shop_items_on_page'] = to_int($_REQUEST['shop_items_on_page']);
$param['shop_shops_yandex_market_name'] = to_str($_REQUEST['shop_shops_yandex_market_name']);
$param['shop_yandex_market_sales_notes_default'] = to_str($_REQUEST['shop_yandex_market_sales_notes_default']);

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

/* Изображение */
$param['shop_image_small_max_width'] = to_int($_REQUEST['shop_image_small_max_width']);
$param['shop_image_big_max_width'] = to_int($_REQUEST['shop_image_big_max_width']);
$param['shop_image_small_max_height'] = to_int($_REQUEST['shop_image_small_max_height']);
$param['shop_image_big_max_height'] = to_int($_REQUEST['shop_image_big_max_height']);
$param['shop_image_small_max_width_group'] = to_int($_REQUEST['shop_image_small_max_width_group']);
$param['shop_image_big_max_width_group'] = to_int($_REQUEST['shop_image_big_max_width_group']);
$param['shop_image_small_max_height_group'] = to_int($_REQUEST['shop_image_small_max_height_group']);
$param['shop_image_big_max_height_group'] = to_int($_REQUEST['shop_image_big_max_height_group']);

$param['shop_typograph_item_by_default'] = (isset($_REQUEST['shop_typograph_item_by_default']))?1:0;

$param['shop_typograph_group_by_default'] = (isset($_REQUEST['shop_typograph_group_by_default']))?1:0;

$param['shop_shops_apply_keywords_automatic'] = (isset($_REQUEST['shop_shops_apply_keywords_automatic']))?1:0;

$param['shop_shops_url_type'] = to_int($_REQUEST['shop_shops_url_type']);

/* Единица измерения */
$param['shop_mesures_id'] = to_int($_REQUEST['shop_mesures_id']);

/* Флаги отправки писем */
$param['shop_shops_send_order_mail_admin'] = 0;
if (isset($_REQUEST['shop_shops_send_order_mail_admin']))
{
	$param['shop_shops_send_order_mail_admin'] = 1;
}
$param['shop_shops_send_order_mail_user'] = 0;
if (isset($_REQUEST['shop_shops_send_order_mail_user']))
{
	$param['shop_shops_send_order_mail_user'] = 1;
}
/* Флаг премодерции комментариев к продавцу */
$param['shop_comment_active'] = 0;
if (isset($_REQUEST['shop_comment_active']))
{
	$param['shop_comment_active'] = 1;
}

$param['shop_shops_attach_eitem'] = isset($_REQUEST['shop_shops_attach_eitem']) ? 1 : 0;

/* Электронный адрес куратора магазина */
$param['shop_shops_admin_mail'] = to_str($_REQUEST['shop_shops_admin_mail']);

/* Узел структуры */
$param['structure_id'] = to_str($_REQUEST['structure_id']);

/* Группа доступа */
$param['shop_access'] = to_int($_REQUEST['shop_shops_access']);

/* Атрибуты сортировки товара */
$param['shop_sort_order_field'] = to_int($_REQUEST['shop_sort_order_field']);
$param['shop_sort_order_type'] = to_int($_REQUEST['shop_sort_order_type']);

/* Атрибуты сортировки групп товара */
$param['shop_group_sort_order_field'] = to_int($_REQUEST['shop_group_sort_order_field']);
$param['shop_group_sort_order_type'] = to_int($_REQUEST['shop_group_sort_order_type']);

/* Watermark */
$param['shop_watermark_file'] = to_str($_REQUEST['old_watermark_file']);

if ($param['shop_watermark_file'] == '')
{
	$param['shop_watermark_file'] = $oldfile;
}

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

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


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

$param['shop_watermark_default_position_x'] = to_str($_REQUEST['shop_watermark_default_position_x']);
$param['shop_watermark_default_position_y'] = to_str($_REQUEST['shop_watermark_default_position_y']);

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

$param['shop_shops_writeoff_payed_items'] = isset($_REQUEST['shop_shops_writeoff_payed_items']) ? 1 : 0;

$param['shop_shops_file_name_conversion'] = isset($_REQUEST['shop_shops_file_name_conversion']) ? 1 : 0;

/* Осуществляем метод вставки информации о магазние */
if($shop_id = $shop->InsertShop($param))
{
	if ($shop_id != -1)
	{
		$admin_forms = new admin_forms();
		$window_id = $admin_forms->GetWindowId();
		?><script type="text/javascript">
		$.appendInput('<?php echo $window_id?>', 'EditAddShop', 'shops_id', '<?php echo $shop_id?>');
		</script><?php
	}
}

// Ошибка! Файл ватермарка должен иметь формат PNG
if (isset($_FILES['shop_watermark_file']['tmp_name'])
	&& $_FILES['shop_watermark_file']['tmp_name'] != ''
	&& exif_imagetype($_FILES['shop_watermark_file']['tmp_name']) != 3)
{
	$can_show_form = false;

	show_error_message($GLOBALS['MSG_shops']['error_watermark_extention_add_edit_shop']);
}
/* Сохранение watermark'а */
elseif ($shop_id && $shop_id != -1)
{
	if (isset($_REQUEST['shops_id']))
	{
		show_message($GLOBALS['MSG_shops']['success_edit_shop']);
	}
	else
	{
		show_message($GLOBALS['MSG_shops']['success_add_shop']);
	}
	/* Проверяем задан ли файл watermark'a */
	if (!empty($_FILES['shop_watermark_file']['name']))
	{
		/* Определяем расширение файла */
		$ext = mb_strtolower($kernel->GetExtension($_FILES['shop_watermark_file']['name']));
		if (!empty($ext))
		{
			/* Проверяем/создаем директорию для хранения файла watermark'a */
			$uploaddir = $shop->CreateDirectory($shop_id, 'watermarks', false);
			if (!$uploaddir)
			{
				/* Ставим путь по умолчанию */
				$uploaddir = CMS_FOLDER.UPLOADDIR;
			}

			/* Обновляем информацию о watermark'e */
			$full_watermark_name = $shop->AssignShopWatermark($shop_id, $ext);
			if ($full_watermark_name)
			{
				/* Формируем полный путь к файлу */
				$full_watermark_name = $uploaddir.$full_watermark_name;

				/* Пробуем переместить файл */
				if (!move_uploaded_file($_FILES['shop_watermark_file']['tmp_name'], $full_watermark_name))
				{
					/* Попытка переместить файл закончилась неудачей, удаляем информацию из БД */
					$shop->AssignShopWatermark($shop_id, '');
				}
				else
				{
					/* Устанавливаем права */
					@chmod($full_watermark_name, CHMOD_FILE);
				}
			}
		}
	}
}
elseif ($shop_id == -1)
{
	show_error_message($GLOBALS['MSG_shops']['error_isset_shop_with_structure']);

	$id = 0;

	$can_show_main_form = false;
}
else
{
	if (isset($_REQUEST['shops_id']))
	{
		show_error_message($GLOBALS['MSG_shops']['error_edit_shop']);
	}
	else
	{
		show_error_message($GLOBALS['MSG_shops']['error_add_shop']);
	}
}
?>