<?php 
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка дополнительных свойств групп товаров.
 * 
 * Файл: /admin/shop/action/load_group_property.php
 * 
 * @author Hostmake LLC
 * @version 5.x
 */
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']['all'] = array('begin' => $begin, 'count' => $on_page);

	$shop = & singleton('shop');

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

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

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

	$DataBase = & singleton('DataBase');

	$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" => $GLOBALS['MSG_shops']['list_of_property_for_group'],
	"link" => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 135, 'load_data'),
	"onclick" => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 135, 'load_data')
	);

	// Генерируем дополнительные хлебные крошки
	$path_array = $shop->GetAdditionalPropertyDirPathArray($ext_shop_groups_parent_id);
	//print_r($path_array);
	if (count($path_array) > 0)
	{
		foreach ($path_array as $key => $value)
		{
			$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&ext_shop_groups_parent_id=$key", 135, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&ext_shop_groups_parent_id=$key", 135, 'load_data'),
			'name' => $value);
		}
	}

	$param['path_array'] = $new_path_array;

	// Запрос для выборки групп
	$param['data'][] = "SELECT shop_properties_groups_dir_id AS code,
	shop_properties_groups_dir_name AS name,
	shop_properties_groups_dir_order AS order_field
	FROM `shop_properties_groups_dir_table`
	WHERE `shop_shops_id` = '$shop_shops_id' 
	AND `shop_properties_groups_dir_parent_id` = '$ext_shop_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество групп
	$count_groups = "SELECT count(*) AS count
	FROM `shop_properties_groups_dir_table`
	WHERE `shop_shops_id` = '$shop_shops_id' 
	AND `shop_properties_groups_dir_parent_id` = '$ext_shop_groups_parent_id'
	{FILTER_STRING}";	


	// Запрос для выборки элементов
	$param['data'][] = "SELECT
	shop_properties_group_id AS code,
	shop_properties_group_name AS name,
	shop_properties_group_xml_name AS xml,
	shop_properties_group_order AS order_field
	FROM `shop_properties_group_table`
	WHERE `shop_shops_id` = '$shop_shops_id'
	AND `shop_properties_groups_dir_id`='$ext_shop_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество элементов
	$count = "SELECT count(*) AS count
	FROM `shop_properties_group_table` 
	WHERE `shop_shops_id` = '$shop_shops_id'
	AND `shop_properties_groups_dir_id`='$ext_shop_groups_parent_id'
	{FILTER_STRING}";

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

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


	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['menu2_caption'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

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

	$param['field_params'][0]['name']['admin_forms_field_type'] = 4;
	$param['field_params'][0]['name']['admin_forms_field_link'] =  $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&ext_shop_groups_parent_id={code}&shop_groups_parent_id=$shop_groups_parent_id", 135, 'load_data');
	$param['field_params'][0]['name']['admin_forms_field_onclick'] =  $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&ext_shop_groups_parent_id={code}&shop_groups_parent_id=$shop_groups_parent_id", 135, 'load_data');

	$param['field_params'][0]['type']['admin_forms_field_image'] = "=/admin/images/folder.gif";
	$param['field_params'][1]['type']['admin_forms_field_image'] = "=/admin/images/page.gif";

	// Формируем массив меню.
	$menu_array = array();
	$menu_array[] = $menu;
	$param['total_count'][] = $count_groups;
	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;

	$param['title'] = $GLOBALS['MSG_shops']['list_of_property_for_group'];

	return $param;
}


function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0: // Список каталогов элементов.
		{
			switch ($field_name)
			{
				case 'code':
					{
						$field_name = 'shop_properties_groups_dir_id';
						break;
					}
				case 'name':
					{
						$field_name = 'shop_properties_groups_dir_name';
						break;
					}
				case 'xml':
					{
						$field_name = '';
						break;
					}
				case 'order_field':
					{
						$field_name = 'shop_properties_groups_dir_order';
						break;
					}
			}
			break;
		}
		case 1: // Список элементов.
		{
			switch ($field_name)
			{
				case 'code':
					{
						$field_name = 'shop_properties_group_id';
						break;
					}
				case 'name':
					{
						$field_name = 'shop_properties_group_name';
						break;
					}
				case 'xml':
					{
						$field_name = 'shop_properties_group_xml_name';
						break;
					}
				case 'order_field':
					{
						$field_name = 'shop_properties_group_order';
						break;
					}
			}
			break;
		}
	}
	return true;
}




/**
 * Функция для удаления свойства товара
 *
 * @param array $param
 */
function delete_external_prop(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

		$count = 0;

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

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetPropretyOfGroup($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->DeletePropretyOfGroup($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']['group_properties_success_delete']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['groups_properties_success_delete']);
				}
			}
		}
		// Удаление элемента
		if (isset($param['data'][0]))
		{
			$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

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

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetPropertiesGroupsDir($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->DeletePropertiesGroupsDir($key, $shop_shops_id))
					{
						$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']['success_delete_dir_dirs']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['success_delete_dirs_dirs']);
				}
			}
		}
	}
	$error = ob_get_clean();
	$param['error'] = $error;
}

// Обработчик события "Копировать" дополнительного свойства узлов структуры
function copy_shop_groups_property(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

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

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$shop->CopyGroupsItemsProperty($key);
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
			
		}
	}
	
	$param['error'] = ob_get_clean();
}

/**
 * Редактирование дополнительного свойства
 *
 * @param array $param
 * @return boolean
 */
//
function edit_external_prop(&$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'][1]))
		{
			foreach ($param['data'][1] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetPropretyOfGroup($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_property_for_group.php');

					// Устанавливаем <title> для страницы
					$param['title'] = ($id == 0) ? $GLOBALS['MSG_shops']['form_add_property_dir_for_group']:$GLOBALS['MSG_shops']['form_edit_property_dir_for_group'];

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

				$shop = & singleton('shop');

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

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

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

					include(CMS_FOLDER.'admin/shop/action/form_edit_add_property_for_group_dir.php');

					// Устанавливаем <title> для страницы
					$param['title'] = ($shop_properties_groups_dir_id == 0) ? $GLOBALS['MSG_shops']['add_group_dir']:$GLOBALS['MSG_shops']['edit_group_dir'];

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

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

/**
 * Применить изменения
 *
 * @param array $param
 */
function apply_change(&$param)
{
	ob_start();
	$params = array();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

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

							$shop = & singleton('shop');

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

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

							if ($user_access->IssetUserAccessForObject($object_user_id))
							{
								$shop->InsertPropretyOfGroup(array('shop_properties_group_id' => $key, 'shop_properties_group_order' => $value['order_field']));
							}
							else
							{
								$user_access->MessageOnlyOwn();
								$param['error'] = ob_get_clean();
								return ;
							}
						}
					}
					// редактирвание порядка сортировки у товара
					if (isset($param['data'][0]))
					{
						foreach ($param['data'][0] AS $key => $value)
						{
							// Определяем режим доступа пользователя и принадлежит ли объект пользователю
							$user_access = new user_access();

							$shop = & singleton('shop');

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

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

							if ($user_access->IssetUserAccessForObject($object_user_id))
							{
								$shop->InsertPropertiesGroupsDir(array('shop_properties_groups_dir_id' => $key, 'shop_properties_groups_dir_order' => $value['order_field']));
							}
							else
							{
								$user_access->MessageOnlyOwn();
								$param['error'] = ob_get_clean();
								return ;
							}
						}
					}
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}
?>