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

	// Идентификатор формы, поля которой необходимо отобразить.
	$admin_forms_id = to_int($_REQUEST['admin_forms_edit_id']);

	// Выборка нужных записей.
	$param['data'][] = "SELECT * FROM `admin_forms_events_table`
	LEFT JOIN `admin_words_table` ON admin_forms_events_table.admin_words_id = admin_words_table.admin_words_id
	LEFT JOIN `admin_words_value_table` ON admin_words_table.admin_words_id = admin_words_value_table.admin_words_id
	WHERE admin_forms_events_table.admin_forms_id = $admin_forms_id AND (admin_words_value_table.admin_language_id = ".CURRENT_LANGUAGE_ID." OR admin_forms_events_table.admin_words_id = 0)
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(admin_forms_events_id) as count FROM `admin_forms_events_table`
	LEFT JOIN `admin_words_table` ON admin_forms_events_table.admin_words_id = admin_words_table.admin_words_id
	LEFT JOIN `admin_words_value_table` ON admin_words_table.admin_words_id = admin_words_value_table.admin_words_id
	WHERE admin_forms_events_table.admin_forms_id = $admin_forms_id AND (admin_words_value_table.admin_language_id = ".CURRENT_LANGUAGE_ID." OR admin_forms_events_table.admin_words_id = 0)
	{FILTER_STRING}";

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

	$p = 0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_admin_forms']['show_form_events_menu_add_new'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_event', 'check_0_0', 4, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_event', 'check_0_0', 4, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/lightning_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// Формируем массив меню.
	$menu_array = array($menu);

	$form_row = $admin_forms->GetAdminForm($admin_forms_id);

	if ($form_row)
	{
		$form_word_row = $admin_forms->GetAdminFormsWord(to_int($form_row['admin_words_id']));
	}

	// Формируем "хлебные крошки"
	$new_path_array[] = array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/admin_forms/admin_forms.php', '', 1, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/admin_forms/admin_forms.php', '', 1, 'load_data'),
	'name' => $GLOBALS['MSG_admin_forms']['show_form_fields_menu_admin_forms']);

	$new_path_array[] = array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/admin_forms/admin_forms.php', "&admin_forms_edit_id=$admin_forms_id", 4, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/admin_forms/admin_forms.php', "&admin_forms_edit_id=$admin_forms_id", 4, 'load_data'),
	'name' => htmlspecialchars(to_str($form_word_row['name'])));

	$param['path_array'] = $new_path_array;

	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;

	$param['title'] = sprintf($GLOBALS['MSG_admin_forms']['show_form_events_title'], $form_word_row['name']);

	return $param;
}


/**
 * Обработчик события "Применить" события формы Центра администрирования
 */
function apply_changes_events(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$adm_forms = new admin_forms();

		$count_changes_events = 0;

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

				$adm_forms = new admin_forms();

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$field_param = array();
					$field_param['admin_forms_events_id'] = intval($key);
					$field_param['admin_forms_events_show_button'] = to_int($row['admin_forms_events_show_button']);
					$field_param['admin_forms_events_group_operation'] = to_int($row['admin_forms_events_group_operation']);
					$field_param['admin_forms_events_order'] = to_int($row['admin_forms_events_order']);

					if ($adm_forms->InsertAdminFormsEvent($field_param))
					{
						++$count_changes_events;
						$flag_success_change_event = true;
					}
					else
					{
						$flag_success_change_event = false;
					}
				}
				else
				{
					$flag_success_change_event = false;
					$user_access->MessageOnlyOwn();
				}
			}

			// Не было ошибок при изменении события формы
			if ($flag_success_change_event)
			{
				// Изменили одно событие
				if ($count_changes_events == 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_event_edit_success']);
				}
				// Изменили несколько событий
				elseif ($count_changes_events > 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_events_edit_success']);
				}
			}
			else // Возникли ошибки при изменении события формы
			{
				show_error_message($GLOBALS['MSG_admin_forms']['show_form_event_edit_error']);
			}
		}
	}
	$param['error'] = ob_get_clean();
}

/**
 * Обработчик события "Редактировать" события (дейтсвия) формы Центра администрирования
 */
function edit_event(&$param)
{
	ob_start();

	$admin_forms = & singleton('admin_forms');
	$user_access = & singleton('user_access');

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

	if (isset($param['data'][0]))
	{
		foreach ($param['data'][0] as $key => $value)
		{
			// Определяем информацию об объекте
			$object_row = $admin_forms->GetAdminFormsEvent($key);

			if ($object_row)
			{
				$object_user_id = $object_row['users_id'];
			}
			else
			{
				$object_user_id = 0;
			}
			
			// Определяем режим доступа пользователя и принадлежит ли объект пользователю
			if ($user_access->IssetUserAccessForObject($object_user_id))
			{
				$admin_forms_events_id = intval($key);

				include(CMS_FOLDER . '/admin/admin_forms/action/form_edit_add_admin_forms_event.php');

				$form_row = $admin_forms->GetAdminForm($admin_forms_id);

				if ($form_row)
				{
					$form_word_row = $admin_forms->GetAdminFormsWord(to_int($form_row['admin_words_id']));
				}

				$param['title'] = $admin_forms_events_id == 0
				? $GLOBALS['MSG_admin_forms']['form_add_forms_event_title']
				: sprintf($GLOBALS['MSG_admin_forms']['form_edit_forms_event_title'], to_str($form_word_row['name']));

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

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


/**
 * Обработчик события "Удалить" события(дейтсвия) формы Центра администрирования
 */
function delete_event(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$adm_forms = new admin_forms();

		$count_deleted_admin_form_events = 0;

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

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					if ($adm_forms->DeleteAdminFormsEvent($key))
					{
						++$count_deleted_admin_form_events;
						$flag_success_delete_admin_form_event = true;
					}
					else
					{
						$flag_success_delete_admin_form_event = false;
					}
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$flag_success_delete_admin_form_event = false;
				}
			}

			if ($flag_success_delete_admin_form_event)
			{
				if ($count_deleted_admin_form_events == 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_event_delete_success']);
				}
				elseif ($count_deleted_admin_form_events >1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_events_delete_success']);
				}
			}
			else
			{
				show_error_message($GLOBALS['MSG_admin_forms']['show_form_event_delete_error']);
			}
		}


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

}


/**
 * Обработчик события "Копировать" события формы Центра администрирования
 */
function copy_event(&$param)
{
	ob_start();

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

		$kernel->ReadMode();
	}
	else
	{
		$adm_forms_fields = new admin_forms_fields();

		$count_copy_admin_form_events = 0;

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

				$adm_forms = new admin_forms();

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

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

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					if ($adm_forms_fields->CopyAdminFormEvent($key))
					{
						++$count_copy_admin_form_events;
						$flag_success_copy_admin_form_event = true;
					}
					else
					{
						$flag_success_copy_admin_form_event = false;
					}
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$flag_success_copy_admin_form_event = false;
				}

			}

			if ($flag_success_copy_admin_form_event)
			{
				if ($count_copy_admin_form_events == 1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_event_copy_success']);
				}
				elseif ($count_copy_admin_form_events >1)
				{
					show_message($GLOBALS['MSG_admin_forms']['show_form_events_copy_success']);
				}
			}
			else
			{
				show_error_message($GLOBALS['MSG_admin_forms']['show_form_event_copy_error']);
			}
		}


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

}

?>