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


	// Генерируем дополнительные хлебные крошки
	$path_array = $shop->GetAdditionalPropertyPathArray($ext_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_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&ext_shop_groups_parent_id=$key", 67, '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", 67, 'load_data'),
			'name' => $value);
		}
	}

	$param['path_array'] = $new_path_array;

	// Запрос для выборки каталогов
	$param['data'][] = "SELECT shop_properties_items_dir_id AS code,
	shop_properties_items_dir_name AS name,
	shop_properties_items_dir_order AS order_field
	FROM `shop_properties_items_dir_table`
	WHERE `shop_shops_id`='$shop_shops_id'
	AND `shop_properties_items_dir_parent_id`='$ext_shop_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

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

	// Запрос для выборки элементов
	$param['data'][] = "SELECT shop_list_of_properties_id AS code,
	shop_list_of_properties_name AS name,
	shop_list_of_properties_order AS order_field, shop_list_of_properties_xml_name
	FROM `shop_list_of_properties_table`
	WHERE `shop_shops_id` = '$shop_shops_id'
	AND `shop_properties_items_dir_id`='$ext_shop_groups_parent_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	$count = "SELECT count(shop_list_of_properties_id) AS count
	FROM `shop_list_of_properties_table` 
	WHERE `shop_shops_id` = '$shop_shops_id' 
	AND `shop_properties_items_dir_id`='$ext_shop_groups_parent_id'
	{FILTER_STRING}";

	// Формируем верхнее меню.
	$k = 0;
	$menu = array();
	$menu[$k]['name'] = $GLOBALS['MSG_shops']['items_catalog'];
	$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', 67, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_external_prop', 'check_1_0', 67, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/page_gear_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

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

	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['menu_add_group_for_external_properties'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_external_prop', 'check_0_0', 67, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_external_prop', 'check_0_0', 67, 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", 67, '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", 67, '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']['show_list_of_properties_title'].' "'.$row['shop_shops_name'].'"';

	return $param;
}

function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0:
			{
				switch ($field_name)
				{
					case 'code':
						{
							$field_name = 'shop_properties_items_dir_id';
							break;
						}
					case 'name':
						{
							$field_name = 'shop_properties_items_dir_name';
							break;
						}
					case 'order_field':
						{
							$field_name = 'shop_properties_items_dir_order';
							break;
						}
					case 'shop_list_of_properties_xml_name':
						{
							$field_name = '';
							break;
						}
					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
		case 1:
			{
				switch ($field_name)
				{
					case 'code':
						{
							$field_name = 'shop_list_of_properties_id';
							break;
						}
					case 'name':
						{
							$field_name = 'shop_list_of_properties_name';
							break;
						}
					case 'order_field':
						{
							$field_name = 'shop_list_of_properties_order';
							break;
						}
					case 'shop_list_of_properties_xml_name':
						{
							$field_name = 'shop_list_of_properties_xml_name';
							break;
						}
					default:
						{
							$field_name = '';
							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;

		$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->GetPropertiesItemsDir($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->DeletePropertiesItemsDir($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']['dir_list_of_properties_success_delete']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['dir_lists_of_properties_success_delete']);
				}
			}
		}
		// Удаление элемента
		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))
				{					
					if (!$shop->DeletePropretyOfItems($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']['list_of_properties_success_delete']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['lists_of_properties_success_delete']);
				}
			}
		}
	}
	$error = ob_get_clean();
	$param['error'] = $error;
}


// Обработчик события "Копировать" дополнительного свойства товаров
function copy_shop_items_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->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->CopyItemsProperty($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->GetPropretyOfItems($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_list_of_properties.php');

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

					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->GetPropertiesItemsDir($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_dir_property.php');

					// Устанавливаем <title> для страницы
					$param['title'] = ($id == 0) ? $GLOBALS['MSG_shops']['form_edit_add_title_add']:$GLOBALS['MSG_shops']['form_edit_add_title_edit'];
				}
				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();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

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

		$params = array();

		$shop = & singleton('shop');

		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))
					{
						$row = $shop->GetPropretyOfItems($key);

						$params['id'] = to_int($key);

						$shop_list_of_properties_id = $row['shop_list_of_properties_id'];

						$params['shop_shops_id'] = $row['shop_shops_id'];

						$params['mesures_id'] = $row['shop_mesures_id'];

						$params['list_id'] = $row['lists_id'];
						
						$params['shop_properties_items_dir_id'] = $row['shop_properties_items_dir_id'];

						$params['name'] = $row['shop_list_of_properties_name'];

						$params['xml_name'] = $row['shop_list_of_properties_xml_name'];

						$params['type'] = $row['shop_list_of_properties_type'];

						$params['prefics'] = $row['shop_list_of_properties_prefics'];
						
						$params['shop_list_of_properties_default_big_width'] = $row['shop_list_of_properties_default_big_width'];
						$params['shop_list_of_properties_default_big_height'] = $row['shop_list_of_properties_default_big_height'];
						$params['shop_list_of_properties_default_small_width'] = $row['shop_list_of_properties_default_small_width'];
						$params['shop_list_of_properties_default_small_height'] = $row['shop_list_of_properties_default_small_height'];

						$params['default_value'] = $row['shop_list_of_properties_default_value'];

						$params['order'] = to_int($value['order_field']);

						$params['shop_list_of_properties_show_kind'] = $row['shop_list_of_properties_show_kind'];

						$params['users_id'] = $row['users_id'];

						$params['shop_list_of_properties_cml_id'] = $row['shop_list_of_properties_cml_id'];
						
						$shop->InsertPropretyOfItems($params);
					}
					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->GetPropertiesItemsDir($key);

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

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