<?php 
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка магазинов и разделов интернет-магазинов.
 * 
 * Файл: /admin/shop/action/shop.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_dir_parent_id = to_int($_REQUEST['shop_dir_parent_id']);
	
	$shop = & singleton('shop');
	
	if ($shop_dir_parent_id)
	{
		// Строим "хлебные крошки"
		$path_array = $shop->GetShopsDirPathArray($shop_dir_parent_id);
	
		$new_path_array = array();
		
		$new_path_array[] = array(
		'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '&shop_dir_parent_id=0', 54, 'load_data'),
		'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '&shop_dir_parent_id=0', 54, 'load_data'),
		'name' => $GLOBALS['MSG_shops']['header_admin__list_forms']);
		
		// Меняем порядок следования элементов в массиве на обратный
		$path_array = array_reverse($path_array, true);

		// Преобразуем идентификаторы групп в ссылки на группы.
		if ($path_array)
		{
			foreach ($path_array as $key => $value)
			{
				$new_path_array[] = array (
				'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_dir_parent_id={$key}", 54, 'load_data'),
				'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_dir_parent_id={$key}", 54, 'load_data'),
				'name' => $value['shop_dir_name']);
			}
		}

		$param['path_array'] = $new_path_array;
	}

	$site_id = CURRENT_SITE;
	
	// Запрос для выборки разделов магазинов
	$param['data'][] = "SELECT shop_dir_id AS key_field, shop_dir_name AS name
	FROM shop_dir_table
	WHERE `site_id` = " . intval(CURRENT_SITE) . " AND `shop_dir_parent_id` = $shop_dir_parent_id 	 
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество разделов магазинов
	$count_dirs = "SELECT count(shop_dir_id) as count
	FROM shop_dir_table
	WHERE `site_id` = " . intval(CURRENT_SITE) . " AND `shop_dir_parent_id` = $shop_dir_parent_id
	{FILTER_STRING}";
	
	// Выборка интернет-магазинов
	$param['data'][] = "
	SELECT shop_shops_id AS key_field, shop_shops_name AS name, shop_currency_name, shop_shops_admin_mail 
	FROM shop_shops_table 
	LEFT JOIN shop_currency_table 
	USING(shop_currency_id) 
	WHERE site_id='$site_id' AND `shop_dir_id` = $shop_dir_parent_id
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "
	SELECT count(*) AS count 
	FROM shop_shops_table 
	LEFT JOIN shop_currency_table 
	USING(shop_currency_id) 
	WHERE site_id='$site_id' AND `shop_dir_id` = $shop_dir_parent_id
	{FILTER_STRING}";

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

	$p = 0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['shop_dir_sub_menu_add'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_shop', 'check_0_0', 11, 0, 0, false, false, false, '&shop_dir_parent_id=' . $shop_dir_parent_id);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_shop', 'check_0_0', 11, 0, 0, false, false, false, '&shop_dir_parent_id=' . $shop_dir_parent_id);
	$sub_menu[$p]['icon'] = '/admin/images/folder_page_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;
	
	
	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['header_admin_forms'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';
	
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['show_shops_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_shop', 'check_1_0', 54, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_shop', 'check_1_0', 54, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/shop_add.gif';

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

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

	$p = 0;

	$sub_menu = array();

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['shop_orders_status'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 63, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 63, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/order_status.gif';

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

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['mesures'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 62, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 62, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/mesures.gif';

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

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['countrys'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 58, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 58, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/country.gif';

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


	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['company_show_link2'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 64, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 64, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/company.gif';

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

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

	$p=0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['show_tax_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 55, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 55, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/coins.gif';

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

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_currency_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 56, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 56, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/money_euro.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;
	
	if (class_exists('SiteUsers'))
	{
		$menu[++$k]['name'] = $GLOBALS['MSG_shops']['affiliate_menu_title'];
		$menu[$k]['link'] = '';
		$menu[$k]['icon'] = '';

		$sub_menu = array();
		$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['affiliate_menu_title'];
		$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 162, 'load_data');
		$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 162, 'load_data');
		$sub_menu[$p]['icon'] = '/admin/images/money.gif';

		// Добавляем подэлементы.
		$menu[$k]['sub_items'] = $sub_menu;
	}
	
	
	// Формируем массив меню.
	$menu_array = array();
	$menu_array[] = $menu;

	$param['total_count'][0] = $count_dirs;
	$param['total_count'][1] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;
	$param['title'] = $GLOBALS['MSG_shops']['header_admin_forms'];
	
	$param['field_params'][0][865]['admin_forms_field_image'] = "=/admin/images/folder.gif";
	
	$param['field_params'][0][213]['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&shop_dir_parent_id={key_field}", 54, 'load_data');
	$param['field_params'][0][213]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&shop_dir_parent_id={key_field}", 54, 'load_data');
	
	$param['field_params'][1][213]['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&shop_groups_parent_id=0&shop_shops_id={key_field}", 65, 'load_data');
	$param['field_params'][1][213]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&shop_groups_parent_id=0&shop_shops_id={key_field}", 65, 'load_data');

	return $param;
}

// Необязательная функция для определения реального имени столбца по псевдониму.
function ResolveFieldName(&$field_name, $dataset_id)
{

	switch ($dataset_id)
	{
		case 0: // Список разделов магазинов
			{				
				if ($field_name == 'key_field')
				{
					$field_name = 'shop_dir_id';
				}
				elseif ($field_name == 'name')
				{
					$field_name = 'shop_dir_name';
				}
				else
				{
					$field_name = '';
				}	

				break;
			}
		case 1: // Список интернет-магазинов
			{
				if ($field_name == 'key_field')
				{
					$field_name = 'shop_shops_id';
				}
				elseif ($field_name == 'name')
				{
					$field_name = 'shop_shops_name';
				}				
				
				break;
			}
	}
	return true;
}

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

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

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

		$count = 0;
		$count_deleted_shop_dir = 0;

		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->GetShopsDir($key);

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$shop->DeleteShopsDir($key))
						{
							$flag_success_dir = false;
						}
						else
						{
							$count_deleted_shop_dir++;

							$flag_success_dir = true;
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success_dir = false;
					}

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

					$shop = & singleton('shop');

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$shop->DeleteShop($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']['shop_success_delete']);
					}
					else
					{
						show_message($GLOBALS['MSG_shops']['shop_success_deletes']);
					}
				}
			}

			
		}

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

	}
}

/**
 * Функция копирования магазина
 *
 * @param array $param
 */
function CopyShop(&$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->GetShop($key);

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$shop->CopyShop($key);
						
						$count++;
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success = false;
					}

				}
			}

			if (1)
			{
				if ($count == 1)
				{
					show_message($GLOBALS['MSG_shops']['copy_shop']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['copy_shops']);
				}
			}
		}

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

	}
}

/**
 * Функция добавления/редактирования магазина
 *
 * @param array $param
 * @return boolean
 */
function edit_shop(&$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 $shop_dir_id => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				$shop = & singleton('shop');

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

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

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

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

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

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

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

				$shop = & singleton('shop');

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

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

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

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

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

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

			}
		}
	}

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