<?php 
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2008 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка коментариев.
 * 
 * Файл: /admin/shop/action/load_comment.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;

	$shop = & singleton('shop');

	$param = array();

	$param['limit'][0] = 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']);

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

	// Если был передан идентификатор товара
	if ($sort_catalog_item_id)
	{
		$res = $shop->GetItem($sort_catalog_item_id);

		$param['title'] = sprintf($GLOBALS['MSG_shops']['show_item_comment_title'], $res['shop_items_catalog_name']);
	}
	else
	{
		$param['title'] = $GLOBALS['MSG_shops']['items_catalog_add_form_comment_link'];
	}

	// Строим "хлебные крошки".

	$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');

	if (!isset($_REQUEST['all_comments_all_shops']))
	{
		$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);
			}
		}
		// Если мы пришли сюда из формы списка модификаций
		if (isset($_REQUEST['shop_items_catalog_modification_id']))
		{
			$shop_items_catalog_modification_id = to_int($_REQUEST['shop_items_catalog_modification_id']);

			// Получаем имя модификации товара, от которой пришли
			$query = "SELECT * FROM `shop_items_catalog_table` WHERE `shop_items_catalog_item_id` = '$shop_items_catalog_modification_id'";

			$row = mysql_fetch_assoc($DataBase->query($query));

			$new_path_array[] = array(
			"name" => sprintf($GLOBALS['MSG_shops']['item_modification_title'], $row['shop_items_catalog_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'));

			$new_path_array[] = array('name' => $param['title'],
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_groups_parent_id=$shop_groups_parent_id&sort_catalog_item_id=$sort_catalog_item_id", 66, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_items_catalog_modification_id=$shop_items_catalog_modification_id&shop_groups_parent_id=$shop_groups_parent_id&sort_catalog_item_id=$sort_catalog_item_id", 66, 'load_data'));
		}
		else
		{
			if (isset($_REQUEST['all_comments_this_shop']))
			{
				$additional_param = "&all_comments_this_shop=1";
			}
			else
			{
				$additional_param = "";
			}

			$new_path_array[] = array('name' => $param['title'],
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&sort_catalog_item_id=$sort_catalog_item_id".$additional_param, 66, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&sort_catalog_item_id=$sort_catalog_item_id".$additional_param, 66, 'load_data'));
		}
	}

	$param['path_array'] = $new_path_array;

	if (isset($_REQUEST['all_comments_all_shops']))
	{
		$string = 'WHERE (1) ';
	}
	elseif (isset($_REQUEST['all_comments_this_shop']))
	{
		$string = "WHERE shop_items_catalog_table.shop_shops_id='$shop_shops_id'";
	}
	else
	{
		// Если идентификатор товара равен 0, отображаем отзывы обо всех товарах сразу
		if (isset($sort_catalog_item_id) && $sort_catalog_item_id == 0)
		{
			$string = "WHERE shop_items_catalog_table.shop_shops_id='$shop_shops_id'
			";
		}
		else
		{
			$string = "WHERE shop_items_catalog_table.shop_items_catalog_item_id='$sort_catalog_item_id' AND shop_items_catalog_table.shop_shops_id='$shop_shops_id'
			";
		}
	}


	// Выборка нужных записей.
	$param['data'][] = "SELECT * FROM `shop_comment_table`
	LEFT JOIN `shop_items_catalog_table` USING(shop_items_catalog_item_id) $string 	{FILTER_STRING} 
	{ORDER_STRING} 
	{LIMIT}";

	$count = "SELECT count(*) as count FROM `shop_comment_table`
	LEFT JOIN `shop_items_catalog_table` USING(shop_items_catalog_item_id) $string
	{FILTER_STRING} ";

	if (!isset($_REQUEST['all_comments_all_shops']))
	{
		// Формируем верхнее меню.
		$k = 0;
		$menu = array();
		$menu[$k]['name'] = $GLOBALS['MSG_shops']['show_groups_comment'];
		$menu[$k]['link'] = '';
		$menu[$k]['icon'] = '';

		$p = 0;

		$sub_menu = array();
		$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['comment_show_add_link'];
		$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_comment', 'check_0_0', 66, 0, 0);
		$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_comment', 'check_0_0', 66, 0, 0);
		$sub_menu[$p]['icon'] = '/admin/images/comment_add.gif';

		// Добавляем подэлементы.
		$menu[$k]['sub_items'] = $sub_menu;
	}

	// Перекрываем некторые настройки выводимой таблицы
	$param['field_params'][0]['shop_comment_active']['admin_forms_field_type'] = 7;// картинка-ссылка
	$param['field_params'][0]['shop_comment_active']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('show', 'check_0_{shop_comment_id}', 66, 0, 0);
	$param['field_params'][0]['shop_comment_active']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('show', 'check_0_{shop_comment_id}', 66, 0, 0);

	$param['field_params'][0]['view']['callback_function'] = 'callback_function_show_item';

	function callback_function_show_item($field_value, $value, $row)
	{
		$shop_shops_id = to_int($row['shop_shops_id']);

		$shop = & singleton('shop');

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

		$path = '';

		if ($shop_row)
		{
			$structure = & singleton('Structure');
			$path = $structure->GetStructurePath($shop_row['structure_id'], 0);

			$path = $path . $shop->GetPathGroup($row['shop_groups_id']);

			$row_item = $shop->GetItem($row['shop_items_catalog_item_id']);

			if ($row_item)
			{
				$path = $path . $row_item['shop_items_catalog_path'];
			}
		}

		// Выбираем основной алиас текущего сайта, для ссылки со страницы
		$site = & singleton ('site');

		$alias_name = $site->GetCurrentAlias(CURRENT_SITE);

		if (!$alias_name)
		{
			$alias_name = '';
		}

		?>
		<a href="<?php echo htmlspecialchars('/' . $path)?>" target="_blank"><img src="/admin/images/comment_view.gif"<?php echo  '/' . $path;?>/>
		<?php
	}

	$param['field_params'][0]['shop_comment_user_name']['callback_function'] = 'callback_function_shop_comment_user_name';
	
	// Вычисляемое поле
	$param['field_params'][0]['shop_comment_user_name']['admin_forms_field_type'] = 10; 
	$param['field_params'][0]['shop_comment_user_name']['callback_function'] = 'callback_function_shop_comment_user_name';

	function callback_function_shop_comment_user_name($field_value, $value, $row)
	{
		// Если указан ID пользователя и есть модуль "Пользователи сайта"
		if (!empty($row['site_users_id']) && class_exists('SiteUsers'))
		{
			$SiteUsers = & singleton('SiteUsers');
			$site_user_row = $SiteUsers->GetSiteUser($row['site_users_id']);

			if ($site_user_row)
			{
				?><img src="/admin/images/new_window.gif" /> <a href="<?php echo "/admin/Site_users/Site_users.php?admin_forms_id=30&operation=edit_user&check_0_{$row['site_users_id']}=1"?>" target="_blank"><?php echo $site_user_row['site_users_login']?></a><?php
			}
		}
		else
		{
			// Просто имя автора
			echo $value;
		}
	}

	// Формируем массив меню.
	if (!isset($_REQUEST['all_comments_all_shops']))
	{
		$menu_array = array();
		$menu_array[] = $menu;
		$param['menus'] = $menu_array;
	}

	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;

	return $param;
}

/**
 * Функция изменяет статус комментария
 *
 * @param array $param
 */
function show(&$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->GetComment($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_comment_table`
				SET `shop_comment_active` = 1 - `shop_comment_active`
				WHERE `shop_comment_id` = '$key'";

						$ret = $DataBase->query($query);
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success = false;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

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

// Удаление отзыва о товаре
function delete_comment(&$param)
{
	ob_start();

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

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

		$count = 0;

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

					$shop = & singleton('shop');

					// Определяем информацию об объекте
					$object_row = $shop->GetComment($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->DeleteComment($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']['comment_delete_success']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['comments_delete_success']);
				}
			}
		}
	}
	$error = ob_get_clean();

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

// редактирование отзыва о товаре
function edit_comment(&$param)
{

	ob_start();

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

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

			$shop = & singleton('shop');

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

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

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

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

				// Устанавливаем <title> для страницы
				$param['title'] = ($shop_comment_id == 0) ? $GLOBALS['MSG_shops']['comment_form_title_add']:$GLOBALS['MSG_shops']['comment_form_title_edit'];
			}
			else
			{
				$user_access->MessageOnlyOwn();
				$param['error'] = ob_get_clean();
				return ;
			}
		}
	}

	$param['result'] = ob_get_clean();


	return true;

}

?>