<?php 
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2008 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка модификаций товара.
 * 
 * Файл: /admin/shop/action/load_item_catalog_modifications.php
 * 
 * @author Hostmake LLC
 * @version 5.2
 */
function LoadAjaxData(&$admin_forms)
{
	$on_page = $admin_forms->GetOnPageCount();

	$page = to_int($_REQUEST['limit']);
	$begin = ($page == 0) ? 0 : ($page - 1) * $on_page;

	$param = array();

	$param['limit'][0] = array('begin' => $begin, 'count' => $on_page);

	$DataBase = & singleton('DataBase');

	$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

	$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

	$shop_items_catalog_modification_id = to_int($_REQUEST['shop_items_catalog_modification_id']);

	// Получаем имя товара, для которого следует вывести список модификаций
	$shop = & singleton('shop');

	$arr = $shop->GetItem($shop_items_catalog_modification_id);

	$shop_name = $arr['shop_items_catalog_name'];

	$row = $shop->GetShop($shop_shops_id);

	// Строим хлебные крошки.
	$path_array = $shop->GetShopPathArray($shop_groups_parent_id, false);

	// Преобразуем идентификаторы групп в ссылки на группы.
	$new_path_array = array();
	$new_path_array[0]['name'] = $GLOBALS['MSG_shops']['header_admin__list_forms'];
	$new_path_array[0]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');
	$new_path_array[0]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');

	$new_path_array[1]['name'] = $row['shop_shops_name'];
	$new_path_array[1]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=0&shop_shops_id=$shop_shops_id", 65, 'load_data');
	$new_path_array[1]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=0&shop_shops_id=$shop_shops_id", 65, 'load_data');

	if ($path_array)
	{
		foreach ($path_array as $key => $value)
		{
			$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$key&shop_shops_id=$shop_shops_id", 65, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$key&shop_shops_id=$shop_shops_id", 65, 'load_data'),
			'name' => $value);
		}
	}

	$new_path_array[] = array('name' => sprintf($GLOBALS['MSG_shops']['item_modification_title'], $shop_name),
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_modification_id=$shop_items_catalog_modification_id", 81, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_modification_id=$shop_items_catalog_modification_id", 81, 'load_data')
	);
	$param['path_array'] = $new_path_array;

	// Запрос для выборки элементов магазина
	$param['data'][] = "SELECT * FROM `shop_items_catalog_table`
	LEFT JOIN `shop_currency_table` 
	USING(`shop_currency_id`) 
	WHERE `shop_items_catalog_modification_id`=$shop_items_catalog_modification_id
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";


	$count = "SELECT count(*) AS count
	FROM `shop_items_catalog_table` 
	LEFT JOIN `shop_currency_table` 
	USING(`shop_currency_id`) 
	WHERE `shop_items_catalog_item_id`=$shop_items_catalog_modification_id 
	{FILTER_STRING}";


	// Формируем верхнее меню.
	$k = 0;
	$menu = array();
	$menu[$k]['name'] = $GLOBALS['MSG_shops']['show_groups_modification'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$p = 0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['item_modification_add_item'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_mod', 'check_0_0', 81, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_mod', 'check_0_0', 81, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/modifications_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// Формируем массив меню.
	$menu_array = array();
	$menu_array[] = $menu;

	// Для первого набора данных общее количство не указываем, т.к. передаем все элементы,
	// для второго набора данных указываем в виде запроса.
	$param['total_count'][] = $count;

	// Перекрываем настойки для некоторых полей
	$param['field_params'][0]['shop_items_catalog_is_active']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('active', 'check_0_{shop_items_catalog_item_id}', 81, 0, 0);
	$param['field_params'][0]['shop_items_catalog_is_active']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('active', 'check_0_{shop_items_catalog_item_id}', 81, 0, 0);
	$param['field_params'][0]['shop_items_catalog_is_active']['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_shops']['catalog_is_active']
	. "\n1=".$GLOBALS['MSG_shops']['catalog_is_active'];
	$param['field_params'][0]['shop_items_catalog_is_active']['admin_forms_field_title'] = "0=".$GLOBALS['MSG_shops']['catalog_is_active']
	. "\n1=".$GLOBALS['MSG_shops']['catalog_is_active'];

	/*$param['field_params'][0]['shop_items_catalog_indexation']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('index', 'check_0_{shop_items_catalog_item_id}', 81, 0, 0);
	$param['field_params'][0]['shop_items_catalog_indexation']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('index', 'check_0_{shop_items_catalog_item_id}', 81, 0, 0);*/

	/*$param['field_params'][0]['shop_items_catalog_indexation']['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_shops']['show_tying_products_menu'];
	$param['field_params'][0]['shop_items_catalog_indexation']['admin_forms_field_title'] = "0=".$GLOBALS['MSG_shops']['show_tying_products_menu'];*/

	$param['field_params'][0]['addonses']['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id={shop_items_catalog_item_id}", 79, 'load_data');
	$param['field_params'][0]['addonses']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_items_catalog_item_id={shop_items_catalog_item_id}", 79, 'load_data');

	$param['field_params'][0]['addonses']['admin_forms_field_alt'] = "=".$GLOBALS['MSG_shops']['show_tying_products_menu'];
	$param['field_params'][0]['addonses']['admin_forms_field_title'] = "=".$GLOBALS['MSG_shops']['show_tying_products_menu'];

	$param['field_params'][0]['easy']['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&item_id=$shop_items_catalog_modification_id&shop_items_catalog_item_id={shop_items_catalog_item_id}", 72, 'load_data');
	$param['field_params'][0]['easy']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&item_id=$shop_items_catalog_modification_id&shop_items_catalog_item_id={shop_items_catalog_item_id}", 72, 'load_data');
	$param['field_params'][0]['easy']['admin_forms_field_alt'] = "=".$GLOBALS['MSG_shops']['show_groups_discount'];
	$param['field_params'][0]['easy']['admin_forms_field_title'] = "=".$GLOBALS['MSG_shops']['show_groups_discount'];

	$param['field_params'][0]['voices']['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&sort_catalog_item_id={shop_items_catalog_item_id}", 66, 'load_data');
	$param['field_params'][0]['voices']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&sort_catalog_item_id={shop_items_catalog_item_id}", 66, 'load_data');
	$param['field_params'][0]['voices']['admin_forms_field_alt'] = "=".$GLOBALS['MSG_shops']['show_groups_comment'];
	$param['field_params'][0]['voices']['admin_forms_field_title'] = "=".$GLOBALS['MSG_shops']['show_groups_comment'];

	$param['field_params'][0]['shop_items_catalog_type']['callback_function'] = 'callback_function_shop_items_catalog_type';


	function callback_function_shop_items_catalog_type($field_value, $value, $row)
	{
		// Получаем данные для передачи в новую форму
		$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

		// Идентификатор товара
		$item_id = to_int($row['shop_items_catalog_item_id']);

		$shop_items_catalog_modification_id = to_int($row['shop_items_catalog_modification_id']);

		$item_name = to_str($row['shop_items_catalog_name']);

		// Текущий каталог товаров
		$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

		$admin_forms = new admin_forms();

		if ($value == 1)
		{
		?>
		<a 
		href="<?php echo $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&modification=$shop_items_catalog_modification_id&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&item_id=$item_id", 132, 'load_data')?>"
		onclick="<?php echo $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&modification=$shop_items_catalog_modification_id&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&item_id=$item_id", 132, 'load_data')?>"
		><img alt="Электронный товар '<?php echo $item_name?>'" title="Электронный товар '<?php echo $item_name?>'" src="/admin/images/table.gif" /></a>
		<?php 
		}
		else
		{
			?>&mdash;<?php
		}
	}

	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;
	$param['title'] = sprintf($GLOBALS['MSG_shops']['item_modification_title'], $shop_name);
	return $param;
}

/**
 * функция для удаления элемента
 *
 * @param array $param
 */
function delete_mod(&$param)
{
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		ob_start();

		$shop = & singleton('shop');

		$count = 0;

		// Удаление элемента
		if (isset($param['data'][0]))
		{
			foreach ($param['data'] as $dataset)
			{
				foreach ($dataset as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					$shop = & singleton('shop');

					// Определяем информацию об объекте
					$object_row = $shop->GetItem($key);

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$shop->DeleteItem($key))
						{
							$flag_success = false;
						}
						else
						{
							$count++;

							$flag_success = true;
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success = false;
					}
				}
			}

			if ($flag_success)
			{
				if ($count == 1)
				{
					show_message($GLOBALS['MSG_shops']['items_catalog_success_delete']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['items_catalogs_success_delete']);
				}
			}
		}
	}
	$error = ob_get_clean();
	$param['error'] = $error;

}
/**
 * Редактирование модификации
 *
 * @param array $param
 * @return boolean
 */
function edit_mod(&$param)
{
	ob_start();

	$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

	$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

	if (isset($param['data']))
	{
		if (isset($param['data'][0]))
		{
			foreach ($param['data'][0] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetItem($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$id = $key;

					include(CMS_FOLDER.'admin/shop/action/form_edit_add_items_catalog.php');
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

	$param['result'] = ob_get_clean();
	return true;
}

/**
 * Применить изменения
 *
 * @param array $param
 */
function apply_mod(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

		$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

		$params = array();

		$shop = & singleton('shop');

		if (isset($param['data']))
		{
			// редактирование директории
			foreach ($param['data'] AS $key => $val)
			{
				foreach ($val AS $keys => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					$shop = & singleton('shop');

					// Определяем информацию об объекте
					$object_row = $shop->GetItem($keys);

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// редактирвание порядка сортировки у товара
						if (isset($param['data'][0]))
						{
							// Получаем данные о модификации (товаре)
							$item_row = $shop->GetItem($keys, array('cache_off' => true));

							$params['order'] = $value['shop_items_catalog_order'];

							$params['weight'] = $item_row['shop_items_catalog_weight'];

							$params['price'] = $item_row['shop_items_catalog_price'];

							$params['item_id'] = $keys;

							$params['shops_id'] = $shop_shops_id;

							$shop->InsertItem($params);
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}

	$error = ob_get_clean();

	$param['error'] = $error;
}

/**
 * Изменение статуса активности
 *
 * @param array $param
 */

function active(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$DataBase = & singleton('DataBase');

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					$shop = & singleton('shop');

					// Определяем информацию об объекте
					$object_row = $shop->GetItem($key);

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$key = to_int($key);

						$query = "UPDATE `shop_items_catalog_table` SET `shop_items_catalog_is_active` = 1 - `shop_items_catalog_is_active` WHERE `shop_items_catalog_item_id` = '$key'";

						$ret = $DataBase->query($query);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

/**
 * Изменение статуса индексации
 *
 * @param array $param
 */
function index(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$DataBase = & singleton('DataBase');

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					$shop = & singleton('shop');

					// Определяем информацию об объекте
					$object_row = $shop->GetItem($key);

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$key = to_int($key);

						$query = "UPDATE `shop_items_catalog_table` SET `shop_items_catalog_indexation` = 1 - `shop_items_catalog_indexation` WHERE `shop_items_catalog_item_id` = '$key'";

						$ret = $DataBase->query($query);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

/**
 * Копирование товара
 *
 * @param array $param
 */
function copy_item(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$shop = & singleton('shop');

		$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

		$kernel = & singleton('kernel');

		$DataBase = & singleton('DataBase');

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					$shop = & singleton('shop');

					// Определяем информацию об объекте
					$object_row = $shop->GetItem($key);

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$param = array();

						$data = $shop->GetItem(to_int($key));

						$param['users_id'] = to_int($data['users_id']);

						$param['shops_id'] = to_int($data['shop_shops_id']);

						// Дописать изменение имени в копируемом файле относительно оригинала
						$param['name'] = to_str($data['shop_items_catalog_name'])." [Копия ".date('d.m.Y H:i:s')."]";

						$param['marking'] = to_str($data['shop_items_catalog_marking']);

						$param['shop_items_catalog_date_time'] = $data['shop_items_catalog_date_time'];

						$param['description'] = to_str($data['shop_items_catalog_description']);

						$param['tax_id'] = to_int($data['shop_tax_id']);

						$param['groups_id'] = to_int($data['shop_groups_id']);

						$param['currency_id'] = to_int($data['shop_currency_id']);

						$param['producers_list_id'] = to_int($data['shop_producers_list_id']);

						$param['mesures_id'] = to_int($data['shop_mesures_id']);

						$param['text'] = to_str($data['shop_items_catalog_text']);

						$param['shop_items_catalog_yandex_market_allow'] = to_int($data['shop_items_catalog_yandex_market_allow']);

						$param['shop_items_catalog_yandex_market_bid'] = to_int($data['shop_items_catalog_yandex_market_bid']);

						$param['shop_items_catalog_yandex_market_cid'] = to_int($data['shop_items_catalog_yandex_market_cid']);

						$param['weight'] = to_float($data['shop_items_catalog_weight']);

						$param['rest'] = to_int($data['shop_items_catalog_rest']);

						$param['price'] = to_float($data['shop_items_catalog_price']);

						$param['seo_title'] = to_str($data['shop_items_catalog_seo_title']);

						$param['seo_description'] = to_str($data['shop_items_catalog_seo_description']);

						$param['seo_keywords'] = to_str($data['shop_items_catalog_seo_keywords']);

						$param['shop_items_catalog_type'] = to_int($data['shop_items_catalog_type']);

						$param['shop_sallers_id'] = to_int($data['shop_sallers_id']);

						$param['shop_items_catalog_modification_id'] = to_int($data['shop_items_catalog_modification_id']);

						$param['order'] = to_int($data['shop_items_catalog_order']);

						$param['is_active'] = to_int($data['shop_items_catalog_is_active']);

						$param['indexation'] = to_int($data['shop_items_catalog_indexation']);

						$id_copy = $shop->InsertItem($param);

						$id = to_int($key);

						///// Вызвать
						CopyExternalPropertiesForItem($id, $id_copy, $shop_shops_id);

						$shop = new shop();

						// Нужно скопировать основные картинки товара
						// Получаем информацио о товаре
						$main_images_item_row = $shop->GetItem($id);

						// Если большое изображение не пустое
						if ($main_images_item_row['shop_items_catalog_image'] != '')
						{
							// Генерируем путь к большому изображению копируемого товара
							$main_big_image = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/' . $main_images_item_row['shop_items_catalog_image'];

							// Получаем расширение файла большого изображения
							$extension = $kernel->GetExtension($main_images_item_row['shop_items_catalog_image']);

							// Если расширение не пустое
							if ($extension != '')
							{
								// Генерируем путь к файлу большого изображения
								$main_big_image_copy = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id . '/shop_items_catalog_image' . $id . '.' . $extension;
								// Имя файла пойдет в базу
								$param_update_images['image'] = 'shop_items_catalog_image' . $id_copy . '.' . $extension;

								if (!is_dir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy))
								{
									@mkdir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy);
								}

								// Генерируем имя конечного файла
								$main_big_image_copy_to = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy . '/shop_items_catalog_image' . $id_copy . '.' . $extension;

								if (is_file($main_big_image_copy))
								{
									// Копируем
									copy($main_big_image_copy, $main_big_image_copy_to);
								}
							}
						}

						// Если малое изображение не пустое
						if ($main_images_item_row['shop_items_catalog_small_image'] != '')
						{
							$main_small_image = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/' . $main_images_item_row['shop_items_catalog_small_image'];

							// Получаем расширение файла большого изображения
							$extension = $kernel->GetExtension($main_images_item_row['shop_items_catalog_small_image']);

							// Если расширение не пустое
							if ($extension != '')
							{
								// Генерируем путь к файлу большого изображения
								$main_small_image_copy = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id . '/small_shop_items_catalog_image' . $id . '.' . $extension;
								// Имя файла пойдет в базу
								$param_update_images['image_small'] = 'small_shop_items_catalog_image' . $id_copy . '.' . $extension;

								if (!is_dir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id  . '/item_catalog_' . $id_copy ))
								{
									@mkdir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id  . '/item_catalog_' . $id_copy );
								}

								// Генерирем имя целевого файла
								$main_small_image_copy_to = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id  . '/item_catalog_' . $id_copy . '/small_shop_items_catalog_image' . $id_copy . '.' . $extension;

								if (is_file($main_small_image_copy))
								{
									// Копируем
									copy($main_small_image_copy, $main_small_image_copy_to);
								}
							}
						}

						$param_update_images['item_id'] = $id_copy;

						$shop->InsertItem($param_update_images);

						// Товар скопирован, проверям были ли у товара модификации
						$id_mod = $id;

						$DataBase = & singleton('DataBase');

						$query = "SELECT * FROM `shop_items_catalog_table` WHERE `shop_items_catalog_modification_id`=$id_mod";

						$res = $DataBase->query($query);

						$count = mysql_num_rows($res);

						if ($count > 0)
						{
							while ($data = mysql_fetch_assoc($res))

							{
								$param['users_id'] = to_int($data['users_id']);

								$param['shops_id'] = to_int($data['shop_shops_id']);

								// Дописать изменение имени в копируемом файле относительно оригинала
								$param['name'] = to_str($data['shop_items_catalog_name']);

								$param['marking'] = to_str($data['shop_items_catalog_marking']);

								$param['shop_items_catalog_date_time'] = $data['shop_items_catalog_date_time'];

								$param['description'] = to_str($data['shop_items_catalog_description']);

								$param['tax_id'] = to_int($data['shop_tax_id']);

								$param['groups_id'] = to_int($data['shop_groups_id']);

								$param['currency_id'] = to_int($data['shop_currency_id']);

								$param['producers_list_id'] = to_int($data['shop_producers_list_id']);

								$param['mesures_id'] = to_int($data['shop_mesures_id']);

								$param['text'] = to_str($data['shop_items_catalog_text']);

								$param['shop_items_catalog_yandex_market_allow'] = to_int($data['shop_items_catalog_yandex_market_allow']);

								$param['shop_items_catalog_yandex_market_bid'] = to_int($data['shop_items_catalog_yandex_market_bid']);

								$param['shop_items_catalog_yandex_market_cid'] = to_int($data['shop_items_catalog_yandex_market_cid']);

								$kernel = & singleton('kernel');

								// Получаем путь изображения копируемого товара
								$file_path_big_image_from = CMS_FOLDER . UPLOADDIR . '/shop_' . $shop_shops_id . '/item_catalog_' . $data['shop_items_catalog_item_id'] . '/' . $data['shop_items_catalog_image'];

								$file_path_small_image_from = CMS_FOLDER . UPLOADDIR . '/shop_' . $shop_shops_id . '/item_catalog_' . $data['shop_items_catalog_item_id'] . '/' . $data['shop_items_catalog_small_image'];

								// Получаем расширения исходных файлов
								$ext_big = $kernel->GetExtension($file_path_big_image_from);

								$ext_small = $kernel->GetExtension($file_path_small_image_from);

								// Ставим новое изображение
								$param['image'] = '';

								// Ставим новое малое изображение
								$param['image_small'] = '';

								$param['weight'] = to_float($data['shop_items_catalog_weight']);

								$param['rest'] = to_int($data['shop_items_catalog_rest']);

								$param['price'] = to_float($data['shop_items_catalog_price']);

								$param['seo_title'] = to_str($data['shop_items_catalog_seo_title']);

								$param['seo_description'] = to_str($data['shop_items_catalog_seo_description']);

								$param['seo_keywords'] = to_str($data['shop_items_catalog_seo_keywords']);

								$param['shop_sallers_id'] = to_int($data['shop_sallers_id']);

								$param['shop_items_catalog_modification_id'] = $id_copy;

								$param['order'] = to_int($data['shop_items_catalog_order']);

								$param['is_active'] = to_int($data['shop_items_catalog_is_active']);

								$param['indexation'] = to_int($data['shop_items_catalog_indexation']);

								$target_id = $shop->InsertItem($param);

								$ext_string_big = '';

								if ($ext_big != '')
								{
									$ext_string_big = '.' . $ext_big;
								}

								$ext_string_small = '';

								if ($ext_small != '')
								{
									$ext_string_small = '.' . $ext_small;
								}

								// Получаем путь изображения для целевого товара
								$file_path_big_image_to = CMS_FOLDER . UPLOADDIR . '/shop_' . $shop_shops_id . '/item_catalog_' . $target_id . '/shop_items_catalog_image' . $target_id . $ext_string_big;

								$file_path_small_image_to = CMS_FOLDER . UPLOADDIR . '/shop_' . $shop_shops_id . '/item_catalog_' . $target_id . '/small_shop_items_catalog_image' . $target_id . $ext_string_small;

								// Проверяем, существует ли целевая папка
								if (is_dir(CMS_FOLDER . UPLOADDIR . '/shop_' . $shop_shops_id . '/item_catalog_' . $data['shop_items_catalog_item_id']))
								{
									@mkdir(CMS_FOLDER . UPLOADDIR . '/shop_' . $shop_shops_id . '/item_catalog_' . $data['shop_items_catalog_item_id']);
								}

								// Обновляем данные об изображении в базе данных
								$shop->InsertItem(array('item_id' => $target_id, 'image' => 'shop_items_catalog_image'. $target_id . $ext_string_big, 'image_small' => 'small_shop_items_catalog_image' . $target_id . $ext_string_small));

								// Копируем файл большого изображения
								copy($file_path_big_image_from, $file_path_big_image_to);

								// Копируем файл малого изображения
								copy($file_path_small_image_from, $file_path_small_image_to);

								CopyExternalPropertiesForItem($data['shop_items_catalog_item_id'], $target_id, $shop_shops_id);
							}
						}

						// Получаем список сопутствующих товаров копируемому товару
						$query = "SELECT * FROM `shop_intermediate_table` WHERE `shop_items_catalog_item_id` = '$key'";

						$res = $DataBase->query($query);

						$count = mysql_num_rows($res);

						$param = array();

						if ($count > 0)
						{
							while ($data = mysql_fetch_assoc($res))
							{
								$param['shop_items_catalog_item_id'] = $id_copy;

								$param['sho_shop_items_catalog_item_id'] = to_int($data['sho_shop_items_catalog_item_id']);

								$shop->InsertTyingProducts($param);
							}
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

function CopyExternalPropertiesForItem($id, $id_copy, $shop_shops_id)
{
	$shop = & singleton('shop');

	$DataBase = & singleton('DataBase');

	$kernel = & singleton('kernel');

	// Нужно скопировать все дополнительные свойства товара
	$ext_prop_row = $shop->GetAllPropertiesItem($id, array('cache_off' => true));

	if ($ext_prop_row)
	{
		foreach ($ext_prop_row as $row)
		{
			// Получаем данные о дополнительном свойстве товара
			$shop_list_of_properties_id = $row['shop_list_of_properties_id'];

			$shop_properties_items_value = $row['shop_properties_items_value'];

			$shop_properties_items_value_small = $row['shop_properties_items_value_small'];

			$shop_properties_items_file = $row['shop_properties_items_file'];

			$shop_properties_items_file_small = $row['shop_properties_items_file_small'];

			$old_big_file = $shop_properties_items_file;

			$old_small_file = $shop_properties_items_file_small;

			if ($shop_properties_items_file != '')
			{
				// расширение большого файла
				$big_extension = $kernel->GetExtension($shop_properties_items_file);
			}

			if ($shop_properties_items_file_small != '')
			{
				// расширение малого файла
				$small_extension = $kernel->GetExtension($shop_properties_items_file_small);
			}

			if (isset($big_extension) && $big_extension != '')
			{
				// Генерируем имена файлов большого и малого изображений
				$shop_properties_items_file = 'shop_property_file_' . $id_copy . '_' . $shop_list_of_properties_id . '.' . $big_extension;
			}

			if (isset($small_extension) && $small_extension != '')
			{
				// Генерируем имена файлов большого и малого изображений
				$shop_properties_items_file_small = 'small_shop_property_file_' . $id_copy . '_' . $shop_list_of_properties_id . '.' . $small_extension;
			}

			// Генерирем запрос на вставку
			$query = "INSERT INTO `shop_properties_items_table` (
					`shop_items_catalog_item_id`,
					`shop_list_of_properties_id`,
					`shop_properties_items_value`,
					`shop_properties_items_value_small`,
					`shop_properties_items_file`,
					`shop_properties_items_file_small`)
					 VALUES (
					 '$id_copy',
					 '$shop_list_of_properties_id',
					 '$shop_properties_items_value',
					 '$shop_properties_items_value_small',
					 '$shop_properties_items_file',
					 '$shop_properties_items_file_small')";

			// Вставляем копию дополнительных параметров
			$DataBase->query($query);

			// Если файл большого изображения не пустой, то нужно скопировать и его
			if ($shop_properties_items_file != '')
			{
				// Генерируем файл большого изображения копируемого товара
				$f_name_from_file_big_image = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id . '/' . $old_big_file;

				// Получаем расширение копируемого файла
				$extension = $kernel->GetExtension($shop_properties_items_file);

				// Генерируем имя большого изображения для скопированного товара
				$f_name_to_file_big_image = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy . '/shop_property_file_' . $id_copy . '_' . $shop_list_of_properties_id . '.' . $extension;
				// Если директории не существует, создаем ее
				if (!is_dir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy))
				{
					@mkdir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy);
				}


				if (is_file($f_name_from_file_big_image))
				{
					@copy($f_name_from_file_big_image, $f_name_to_file_big_image);
				}
			}

			// Также с малым файлом
			if ($shop_properties_items_file_small != '')
			{
				// Генерируем файл малого изображения копируемого товара
				$f_name_from_file_small_image = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id . '/' . $old_small_file;

				// Получаем расширение копируемого файла
				$extension = $kernel->GetExtension($shop_properties_items_file_small);

				// Генерируем имя малого изображения для скопированного товара
				$f_name_to_file_small_image = CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy . '/small_shop_property_file_' . $id_copy . '_' . $shop_list_of_properties_id . '.' . $extension;


				// Если директории не существует, создаем ее
				if (!is_dir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy))
				{
					@mkdir(CMS_FOLDER . UPLOADDIR . 'shop_' . $shop_shops_id . '/item_catalog_' . $id_copy);
				}

				if (is_file($f_name_from_file_small_image))
				{
					@copy($f_name_from_file_small_image, $f_name_to_file_small_image);
				}
			}
		}
	}
}
?>