<?php

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

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

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

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

	$shop_order_id = to_int($_REQUEST['view_order_id']);

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

	$shop = & singleton('shop');

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

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

	// Запрос для выборки элементов магазина
	$param['data'][] = "SELECT *,
		(shop_order_items_price * shop_order_items_quantity) AS summ 
		FROM shop_order_items_table 
		WHERE `shop_order_id` = '$shop_order_id'
		{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Запрос на количество элементов
	$count = "SELECT count(*) AS count
		FROM shop_order_items_table 
		WHERE `shop_order_id` = '$shop_order_id' 
		{FILTER_STRING}";

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

	$p = 0;
	$sub_menu = array ();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['order_items_add_form_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_item', 'check_0_0', 76, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_item', 'check_0_0', 76, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/page_add.gif';

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

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

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

	function callback_function_item_name($field_value, $value, $row)
	{
		$shop = & singleton('shop');
		$admin_forms = & singleton('admin_forms');

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

		if ($row_item)
		{
			// Ссылка на редактирование товара
?><img src="/admin/images/new_window.gif" /> <a href="<?php echo $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id={$row_item['shop_groups_id']}&shop_shops_id={$row_item['shop_shops_id']}&check_1_{$row_item['shop_items_catalog_item_id']}=1", 65, 'edit_item')?>" 
onclick="<?php echo $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id={$row_item['shop_groups_id']}&shop_shops_id={$row_item['shop_shops_id']}&check_1_{$row_item['shop_items_catalog_item_id']}=1", 65, 'edit_item')?>" target="_blank"><?php echo $row_item['shop_items_catalog_name']?></a><?php

		}
		else
		{
			// Просто имя автора
			echo $value;
		}

	}

	return $param;
}

/**
 * Необязательная функция для определения реального имени столбца по псевдониму.
 *
 * @param string $field_name
 * @param inbeger $dataset_id
 * @return boolean
 */
function ResolveFieldName(& $field_name, $dataset_id)
{
	if ($field_name == 'summ')
	{
		$field_name = 'shop_order_items_price * shop_order_items_quantity';
	}
	return true;
}

/**
 * функция для удаления товара в оформленном заказе
 *
 * @param array $param
 */
function delete_item(& $param)
{
	ob_start();

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

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

		$count = 0;

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

				$shop = & singleton('shop');

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

/**
 * Редактирование товара в оформленном заказе
 *
 * @param array $param
 * @return boolean
 */
function edit_item(& $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->GetOrderItem($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_order_items.php');

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

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