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

	$shop = & singleton('shop');

	// Если был передан идентификатор товара
	if (isset($_REQUEST['shop_items_catalog_item_id']))
	{
		$res = $shop->GetItem(to_int($_REQUEST['shop_items_catalog_item_id']));

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

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

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

	// Если пришли из формы списка модификаций товара
	if (isset($_REQUEST['shop_items_catalog_modification_id']) && isset($_REQUEST['item_id']))
	{
		// Получаем имя товара
		$shop_items_catalog_item_id = to_int($_REQUEST['item_id']);

		$row = $shop->GetItem($shop_items_catalog_item_id);

		$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_item_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_item_id", 81, 'load_data'));
	}

	if (isset($_REQUEST['shop_items_catalog_item_id']) && to_int($_REQUEST['shop_items_catalog_item_id']) != 0)
	{
		$shop_items_catalog_item_id = to_int($_REQUEST['shop_items_catalog_item_id']);
		if (isset($_REQUEST['item_id']))
		{

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

			$new_path_array[] = array("name" => sprintf($GLOBALS['MSG_shops']['show_item_discount_title'], $res['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_item_id=$shop_items_catalog_item_id&item_id=$item_id&shop_items_catalog_modification_id=$item_id", 72, '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_item_id=$shop_items_catalog_item_id&item_id=$item_id&shop_items_catalog_modification_id=$item_id", 72, 'load_data')
			);
		}
		else
		{
			$new_path_array[] = array("name" => sprintf($GLOBALS['MSG_shops']['show_item_discount_title'], $res['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_item_id=$shop_items_catalog_item_id", 72, '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_item_id=$shop_items_catalog_item_id", 72, 'load_data')
			);
		}
	}
	else
	{
		$new_path_array[] = array("name" => $GLOBALS['MSG_shops']['discount_add_form_link'],
		"link" => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 72, 'load_data'),
		"onclick" => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 72, 'load_data')
		);
	}

	$param['path_array'] = $new_path_array;

	// Если не установлен идентификатор товара, то показываем все скидки
	if (!isset($_REQUEST['shop_items_catalog_item_id']) || to_int($_REQUEST['shop_items_catalog_item_id']) == 0)
	{
		// Запрос для выборки элементов магазина
		$param['data'][] = "SELECT *, shop_discount_id AS keyfield FROM `shop_discount_table`
		WHERE `shop_shops_id` = '$shop_shops_id'
		{FILTER_STRING} {ORDER_STRING} {LIMIT}";

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

		// Переопределение некоторых параметров выводимой таблицы
		$param['field_params'][0]['shop_discount_is_active']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('active', 'check_0_{shop_discount_id}', 72, 0, 0);
		$param['field_params'][0]['shop_discount_is_active']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('active', 'check_0_{shop_discount_id}', 72, 0, 0);
	}
	// иначе показываем скидки только для данного товара
	else
	{
		$shop_items_catalog_item_id = to_int($_REQUEST['shop_items_catalog_item_id']);


		$param['data'][] = "SELECT *, shop_item_discount_id AS keyfield FROM `shop_item_discount_table`
		LEFT JOIN `shop_discount_table` USING (shop_discount_id) 
		WHERE shop_item_discount_table.shop_items_catalog_item_id='$shop_items_catalog_item_id'";

		$count = "SELECT count(*) AS count FROM `shop_item_discount_table`
		LEFT JOIN `shop_discount_table` USING (shop_discount_id) 
		WHERE shop_item_discount_table.shop_items_catalog_item_id='$shop_items_catalog_item_id'";

		// Убираем ссылку с активности скидки, т.к. она имеет двоякое значение и дублирует сама себя при показах форм "Справочник скидок" и "Скидки" конкретного товара
		$param['field_params'][0]['shop_discount_is_active']['admin_forms_field_type'] = 7;// картинка-ссылка
		$param['field_params'][0]['shop_discount_is_active']['admin_forms_field_link'] = '';
		$param['field_params'][0]['shop_discount_is_active']['admin_forms_field_onclick'] = '';
	}

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

	$p = 0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['add_item_discount_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_discount', 'check_0_0', 72, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_discount', 'check_0_0', 72, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/money_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;

	return $param;
}

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

		$kernel->ReadMode();
	}
	else
	{
		if (isset($_REQUEST['shop_items_catalog_item_id']))
		{
			ob_start();

			$shop = & singleton('shop');

			$count = 0;

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

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

			$error = ob_get_clean();
			$param['error'] = $error;
		}
		else
		{
			ob_start();
			$shop = & singleton('shop');

			$count = 0;

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

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

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

/**
 * Редактирование скидки
 *
 * @param array $param
 * @return boolean
 */
function edit_discount(&$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');

				if (!isset($_REQUEST['shop_items_catalog_item_id']))
				{
					// Определяем информацию об объекте
					$object_row = $shop->GetDiscount($key);
				}
				else
				{
					// Определяем информацию об объекте
					$object_row = $shop->GetItemDiscount($key);
				}

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

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

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

					// Устанавливаем <title> для страницы
					// Если идет добавление скидки к товару - то редактирование скидки не возможно, поэтому заголовок - "Добавление"
					$param['title'] = ($id == 0) ? $GLOBALS['MSG_shops']['item_discount_add_form_title']:$GLOBALS['MSG_shops']['item_discount_edit_form_title'];
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}
	$param['result'] = ob_get_clean();
	return true;
}

/**
 * Изменение статуса активности
 *
 * @param array $param
 */
function active(&$param)
{
	ob_start();
	$DataBase = & singleton('DataBase');

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

		$kernel->ReadMode();
	}
	else
	{
		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->GetDiscount($key);

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

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

						$my_query="UPDATE shop_discount_table SET `shop_discount_is_active`=1-`shop_discount_is_active` WHERE `shop_discount_id`=$id";

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

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