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

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

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

	$DataBase = & singleton('DataBase');

	$shop = & singleton('shop');

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

	$path_array = $shop->GetShopPathArray($shop_groups_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']['properties_item_for_groups_link'],
	"link" => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=0&shop_groups_id=$shop_groups_id", 71, 'load_data'),
	"onclick" => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=0&shop_groups_id=$shop_groups_id", 71, 'load_data'));
	
	// Генерируем дополнительные хлебные крошки
	$path_array = $shop->GetAdditionalPropertyPathArray($shop_groups_parent_id);

	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_id=$shop_groups_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$key", 71, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_id=$shop_groups_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$key", 71, 'load_data'),
			'name' => $value);
		}
	}
	
	$param['path_array'] = $new_path_array;

	// Получаем идентификатор группы дополнительных свойств товаров
	$shop_properties_items_dir_id = to_int($_REQUEST['shop_properties_items_dir_id']);
	
	// Выбираем группы дополнительных свойств
	$param['data'][] = "SELECT *, shop_properties_items_dir_order AS order_field, shop_properties_items_dir_id AS key_field, shop_properties_items_dir_name AS path_name FROM `shop_properties_items_dir_table` WHERE `shop_properties_items_dir_parent_id` = '$shop_groups_parent_id' AND `shop_shops_id` ='$shop_shops_id' 
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";
	
	$group_count = "SELECT count(*) AS count
	FROM `shop_properties_items_dir_table` WHERE `shop_properties_items_dir_parent_id` = '$shop_groups_parent_id' AND `shop_shops_id` = '$shop_shops_id'";

	// Выборка нужных записей.
	$param['data'][] = "SELECT *, shop_list_of_properties_order AS order_field, shop_list_of_properties_table.shop_list_of_properties_id AS key_field, shop_list_of_properties_name AS path_name, 
 	IF( shop_properties_item_for_groups_id, 1, 0) AS enable, 
 	shop_list_of_properties_table.shop_list_of_properties_id 
 	FROM shop_list_of_properties_table 
 	LEFT JOIN shop_properties_item_for_groups_table ON
	 (shop_properties_item_for_groups_table.shop_list_of_properties_id = 
	shop_list_of_properties_table.shop_list_of_properties_id 
	AND shop_properties_item_for_groups_table.shop_groups_id = '$shop_groups_id') 
	WHERE shop_list_of_properties_table.shop_shops_id = '$shop_shops_id'
	AND shop_list_of_properties_table.shop_properties_items_dir_id = '$shop_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(*) AS count
	FROM shop_list_of_properties_table 
	LEFT JOIN shop_properties_item_for_groups_table ON
	(shop_properties_item_for_groups_table.shop_list_of_properties_id = 
	shop_list_of_properties_table.shop_list_of_properties_id 
	AND shop_properties_item_for_groups_table.shop_groups_id = '$shop_groups_parent_id') 
	WHERE shop_list_of_properties_table.shop_shops_id = '$shop_shops_id'
	AND shop_list_of_properties_table.shop_properties_items_dir_id = '$shop_groups_parent_id'
	{FILTER_STRING}";

	// Переопределение некоторых параметров выводимой таблицы
	$param['field_params'][1]['enable']['admin_forms_field_link'] = "/admin/shop/shop.php?action=show_shop_properties_item_for_groups&set_enable&shop_shops_id=$shop_shops_id&shop_groups_id=$shop_groups_parent_id&property_id_{shop_list_of_properties_id}";
	$param['field_params'][1]['enable']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('enabled', 'check_1_{shop_list_of_properties_id}', 71, 0, 0);
	$param['field_params'][1]['enable']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('enabled', 'check_1_{shop_list_of_properties_id}', 71, 0, 0);
	
	// В поле с картинкой отображаем значек папки.
	$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";
	
	// Поле с названием делаем ссылкой.
	$param['field_params'][0]['path_name']['admin_forms_field_type'] = 4; // Ссылка.
	$param['field_params'][0]['path_name']['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_id=$shop_groups_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id={key_field}", 71, 'load_data');
	$param['field_params'][0]['path_name']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_id=$shop_groups_id&shop_shops_id=$shop_shops_id&shop_groups_parent_id={key_field}", 71, 'load_data');

	// Поле "Доступность" для групп убираем
	//$param['field_params'][1]['mods']['admin_forms_field_type'] = ;// 
	$param['field_params'][0]['enable']['admin_forms_field_type'] = 0;// 
	
	$param['total_count'][] = $group_count;
	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['title'] = $GLOBALS['MSG_shops']['properties_item_for_groups_root_title'];

	return $param;
}

/**
 * Необязательная функция для определения реального имени столбца по псевдониму.
 *
 * @param string $field_name
 * @param integer $dataset_id
 * @return boolean
 */
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0:
		{
			switch ($field_name)
			{
				case 'order_field':
					{
						$field_name = 'shop_properties_items_dir_order';
						break;
					}
				case 'key_field':
					{
						$field_name = 'shop_properties_items_dir_id';
						break;
					}
				case 'path_name':
					{
						$field_name = 'shop_properties_items_dir_name';
						break;
					}
				default:
					{
						$field_name = '';
						break;
					}
			}
			break;
		}
		case 1:
		{
			switch ($field_name)
			{
				case 'order_field':
					{
						$field_name = 'shop_list_of_properties_order';
						break;
					}
				case 'key_field':
					{
						$field_name = 'shop_list_of_properties_table.shop_list_of_properties_id';
						break;
					}
				case 'path_name':
					{
						$field_name = 'shop_list_of_properties_name';
						break;
					}
				default:
					{
						$field_name = '';
						break;
					}
			}
			break;
		}
	}
	return true;
}

/**
 * Включение доступа
 *
 * @param array $param
 */

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

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

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

		$DataBase = & singleton('DataBase');

		if (isset($param['data']))
		{
			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $value)
				{
					$shop_list_of_properties_id = $key;

					// Устанавливаем активность (ВКЛЮЧЕНО)

					// Если в таблице дополнительных свойств конкретной группы присутствует запись об этом свойстве, значит ее нужно удалить, иначе ее нужно добавить
					$query = "SELECT * FROM `shop_properties_item_for_groups_table` WHERE `shop_groups_id` = '$shop_groups_id' AND `shop_list_of_properties_id` = '$shop_list_of_properties_id' AND `shop_shops_id` = '$shop_shops_id'";

					$DataBase->select($query);

					if ($DataBase->get_count_row() == 0)
					{
						$kernel = new kernel();

						$users_id = $kernel->GetCurrentUser();

						// Запись не существует, добавим ее
						$query = "INSERT INTO `shop_properties_item_for_groups_table` (`shop_groups_id`, `shop_list_of_properties_id`, `shop_shops_id`, `users_id`) VALUES ($shop_groups_id,$shop_list_of_properties_id,$shop_shops_id, $users_id)";

						// Выполняем действие
						$DataBase->query($query);
					}
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}


/**
 * Выключение доступа
 *
 * @param array $param
 */

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

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

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

		$DataBase = & singleton('DataBase');

		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->GetPropretyOfItems($key);

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

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

						// Устанавливаем активность (ВЫКЛЮЧЕНО)

						// Если в таблице дополнительных свойств конкретной группы присутствует запись об этом свойстве, значит ее нужно удалить, иначе ее нужно добавить
						$query = "SELECT * FROM `shop_properties_item_for_groups_table` WHERE `shop_groups_id` = '$shop_groups_id' AND `shop_list_of_properties_id` = '$shop_list_of_properties_id' AND `shop_shops_id` = '$shop_shops_id'";

						$DataBase->select($query);

						if ($DataBase->get_count_row() != 0)
						{
							// Запись существует, удаляем ее
							$query = "DELETE FROM `shop_properties_item_for_groups_table` WHERE `shop_groups_id` = '$shop_groups_id' AND `shop_list_of_properties_id` = '$shop_list_of_properties_id' AND `shop_shops_id` = '$shop_shops_id'";

							// Выполняем действие
							$DataBase->query($query);
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}

	$param['error'] = ob_get_clean();
}

function select_subgrup($arr, $group_mas, $group_parent_id)
{
	$shop = & singleton('shop');

	if (isset($group_mas[$group_parent_id]))
	{
		foreach ($group_mas[$group_parent_id] as $key => $sub_group_id)
		{
			$arr[] = $sub_group_id;
			$arr = select_subgrup($arr, $group_mas, $sub_group_id);
		}
	}
	
	return $arr;
}



/**
 * Включение доступа всем подчиненным
 *
 * @param array $param
 */

function change_access_status_on_for_children(&$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']);

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

		// Получаем ID всех подгрупп
		$shop->FillMemCacheGoupsIdTree($shop_shops_id);
		$subgroups_array = $shop->CacheGoupsIdTree[$shop_shops_id];
		
		// Получаем ID всех подгрупп
		//$subgroups_array = $shop->GetGroupsTree($shop_groups_id, $shop_shops_id);

		if (isset($subgroups_array[$shop_groups_id]) && count($subgroups_array[$shop_groups_id]) > 0)
		{
			$in = array();
			$in[] = $shop_groups_id;
			$in = select_subgrup($in, $subgroups_array, $shop_groups_id);
			
			unset($subgroups_array);

			$DataBase = & singleton('DataBase');

			if (isset($param['data']))
			{
				if (isset($param['data'][1]))
				{
					foreach ($param['data'][1] as $key => $value)
					{
						$shop_list_of_properties_id = $key;

					
						// Устанавливаем активность (ВКЛЮЧЕНО)
						foreach ($in as $subgroup_id)
						{
							// Если в таблице дополнительных свойств конкретной группы присутствует запись об этом свойстве,
							// значит ее нужно удалить, иначе ее нужно добавить
							$query = "SELECT * FROM `shop_properties_item_for_groups_table`
							WHERE `shop_groups_id` = '{$subgroup_id}'
							AND `shop_list_of_properties_id` = '$shop_list_of_properties_id'
							AND `shop_shops_id` = '$shop_shops_id'";

							$DataBase->select($query);

							if ($DataBase->get_count_row() == 0)
							{

								$kernel = new kernel();

								$users_id = $kernel->GetCurrentUser();

								// Запись не существует, добавим ее
								$query = "INSERT INTO `shop_properties_item_for_groups_table`
								(`shop_groups_id`, `shop_list_of_properties_id`, `shop_shops_id`, `users_id`)
								VALUES ('{$subgroup_id}', $shop_list_of_properties_id, $shop_shops_id, $users_id)";

								// Выполняем действие
								$DataBase->query($query);
							}
						}
					}
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}


/**
 * Выключение доступа
 *
 * @param array $param
 */

function change_access_status_off_for_children(&$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']);

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

		// Получаем ID всех подгрупп
		$shop->FillMemCacheGoupsIdTree($shop_shops_id);
		$subgroups_array = $shop->CacheGoupsIdTree[$shop_shops_id];
		
		// Получаем ID всех подгрупп
		//$subgroups_array = $shop->GetGroupsTree($shop_groups_id, $shop_shops_id);

		if (isset($subgroups_array[$shop_groups_id]) && count($subgroups_array[$shop_groups_id]) > 0)
		{
			$in = array();
			$in[] = $shop_groups_id;
			$in = select_subgrup($in, $subgroups_array, $shop_groups_id);

			unset($subgroups_array);

			$DataBase = & singleton('DataBase');

			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->GetPropretyOfItems($key);

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

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

							// Устанавливаем активность (ВЫКЛЮЧЕНО)
							foreach ($in as $subgroup_id)
							{
								// Если в таблице дополнительных свойств конкретной группы присутствует запись об этом свойстве,
								// значит ее нужно удалить, иначе ее нужно добавить
								$query = "SELECT * FROM `shop_properties_item_for_groups_table`
							WHERE `shop_groups_id` = '{$subgroup_id}'
							AND `shop_list_of_properties_id` = '$shop_list_of_properties_id'
							AND `shop_shops_id` = '$shop_shops_id'";

								$DataBase->select($query);

								if ($DataBase->get_count_row() != 0)
								{
									// Запись существует, удаляем ее
									$query = "DELETE FROM `shop_properties_item_for_groups_table`
								WHERE `shop_groups_id` = '{$subgroup_id}'
								AND `shop_list_of_properties_id` = '$shop_list_of_properties_id'
								AND `shop_shops_id` = '$shop_shops_id'";

									// Выполняем действие
									$DataBase->query($query);
								}
							}
						}
						else
						{
							$user_access->MessageOnlyOwn();
							$param['error'] = ob_get_clean();
							return ;
						}
					}
				}
			}
		}
	}

	$param['error'] = ob_get_clean();
}

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

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

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

		$DataBase = & singleton('DataBase');

		if (isset($param['data']))
		{
			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $value)
				{
					$shop_list_of_properties_id = $key;

					// Если в таблице дополнительных свойств конкретной группы присутствует запись об этом свойстве, значит ее нужно удалить, иначе ее нужно добавить
					$query = "SELECT * FROM `shop_properties_item_for_groups_table`
					WHERE `shop_groups_id` = '$shop_groups_id'
					AND `shop_list_of_properties_id` = '$shop_list_of_properties_id'
					AND `shop_shops_id` = '$shop_shops_id'";

					$DataBase->select($query);
				
					if ($DataBase->get_count_row() == 1)
					{
						// Определяем режим доступа пользователя и принадлежит ли объект пользователю
						$user_access = new user_access();

						$shop = & singleton('shop');

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

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

						if ($user_access->IssetUserAccessForObject($object_user_id))
						{
							// Запись существует, удаляем ее
							$query = "DELETE FROM `shop_properties_item_for_groups_table`
							WHERE `shop_groups_id` = '$shop_groups_id'
							AND `shop_list_of_properties_id` = '$shop_list_of_properties_id'";

							// выполняем действие
							$DataBase->query($query);
						}
						else
						{
							$user_access->MessageOnlyOwn();
							$param['error'] = ob_get_clean();
							return ;
						}
					}
					else
					{
						$kernel = new kernel();

						$users_id = $kernel->GetCurrentUser();

						// Запись не существует, добавим ее
						$query = "INSERT INTO `shop_properties_item_for_groups_table` (`shop_groups_id`, `shop_list_of_properties_id`, `shop_shops_id`, `users_id`) VALUES ($shop_groups_id,$shop_list_of_properties_id,$shop_shops_id, $users_id)";

						// выполняем действие
						$DataBase->query($query);
					}
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}
?>