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

	$shop_country_id = to_int($_REQUEST['shop_country_id']);
	$shop_location_id = to_int($_REQUEST['shop_location_id']);
	$shop_city_id = to_int($_REQUEST['shop_city_id']);

	$DataBase = & singleton('DataBase');

	$shop = new shop();

	$rows = $shop->GetLocation($shop_location_id);

	$row = $shop->GetCountry($shop_country_id);

	$country_row = $shop->GetCountry($shop_country_id);

	$row_city = $shop->GetCity($shop_city_id);

	// Строим "хлебные крошки".
	$array = array();
	$array['name'] = $GLOBALS['MSG_shops']['header_admin__list_forms'];
	$array['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');
	$array['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');
	$param['path_array'][] = $array;

	$array = array();
	$array['name'] = $GLOBALS['MSG_shops']['country_add_form_link1'];
	$array['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 58, 'load_data');
	$array['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 58, 'load_data');
	$param['path_array'][] = $array;

	$array = array();
	$array['name'] = $GLOBALS['MSG_shops']['show_location_title'].' "'.$row['shop_country_name'].'"';
	$array['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_country_id=$shop_country_id", 59, 'load_data');
	$array['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_country_id=$shop_country_id", 59, 'load_data');
	$param['path_array'][] = $array;

	$array = array();
	$array['name'] = $GLOBALS['MSG_shops']['show_city_title'].' "'.$rows['shop_location_name'].'"';
	$array['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_country_id=$shop_country_id&shop_location_id=$shop_location_id", 60, 'load_data');
	$array['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_country_id=$shop_country_id&shop_location_id=$shop_location_id", 60, 'load_data');
	$param['path_array'][] = $array;

	$array = array();
	$array['name'] = $GLOBALS['MSG_shops']['show_city_area_title'].' "'.$row_city['shop_city_name'].'"';
	$array['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_country_id=$shop_country_id&shop_location_id=$shop_location_id&shop_city_id=$shop_city_id", 61, 'load_data');
	$array['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_country_id=$shop_country_id&shop_location_id=$shop_location_id&shop_city_id=$shop_city_id", 61, 'load_data');
	$param['path_array'][] = $array;

	// Выборка нужных записей.
	$param['data'][] = "SELECT * FROM shop_city_area_table
	WHERE shop_city_id='$shop_city_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(shop_city_area_id) AS count FROM shop_city_area_table
	WHERE shop_city_id='$shop_city_id'
	{FILTER_STRING}";

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

	$p = 0;

	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['city_area_add_form_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_area', 'check_0_0', 61, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_area', 'check_0_0', 61, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/city_area_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_city_area_title'].' "'.$row_city['shop_city_name'].'"';

	return $param;

}

// Удаление района города
function delete_area(&$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->GetCityArea($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->DeleteCityArea($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']['delete_city_area_success']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['delete_city_areas_success']);
				}
			}
		}
	}

	$error = ob_get_clean();

	$param['error'] = $error;

}

// добавление/редактирование района города
function edit_area(&$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->GetCityArea($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_add_edit_city_area.php');

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

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

	return true;
}

// применить изменения
function apply_change(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$params = array();

		$db = & 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->GetCityArea($key);

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// Делаем запрос на обновление информации о порядке сортировки элемента с индексом $key ($value['structure_order'])
						$val = to_int($value['shop_city_area_order']);

						$query = "UPDATE `shop_city_area_table` SET `shop_city_area_order` = '$val' WHERE `shop_city_area_id` = '$key'";

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

				}
			}
		}
	}
	$error = ob_get_clean();

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