<?php 
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2008 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка оформленных заказов.
 * 
 * Файл: /admin/shop/action/load_order.php
 * 
 * @author Hostmake LLC
 * @version 5.2
 */
function LoadAjaxData(&$admin_forms)
{
	$on_page = $admin_forms->GetOnPageCount();

	if (isset($_REQUEST['limit']))
	{
		$page = to_int($_REQUEST['limit']);
	}
	else
	{
		$page = 0;
	}

	$begin = ($page == 0) ? 0 : ($page - 1) * $on_page;

	$param = array();

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

	$shop = & singleton('shop');

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

	$new_path_array[] = array("name" => $GLOBALS['MSG_shops']['shops_add_form_link_orders'],
	"link" => $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 75, 'load_data'),
	"onclick" => $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 75, 'load_data')
	);
	$param['path_array'] = $new_path_array;

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

	// Число нужных записей.
	$count = "
	select count(shop_order_id) AS count 
	FROM `shop_order_table` 
	WHERE `shop_shops_id` = '$shop_shops_id'
	{FILTER_STRING}";

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

	$p = 0;

	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['add_order_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_order', 'check_0_0', 75, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_order', 'check_0_0', 75, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/order_add.gif';

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

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

	// Переопределение некоторых параметров выводимой таблицы
	$param['field_params'][0]['shop_order_status_of_pay']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('status', 'check_0_{shop_order_id}', 75, 0, 0);
	$param['field_params'][0]['shop_order_status_of_pay']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('status', 'check_0_{shop_order_id}', 75, 0, 0);

	$param['field_params'][0]['shop_order_cancel']['admin_forms_field_link'] = $admin_forms->GetHtmlCallTrigerSingleAction('cancel', 'check_0_{shop_order_id}', 75, 0, 0);
	$param['field_params'][0]['shop_order_cancel']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('cancel', 'check_0_{shop_order_id}', 75, 0, 0);

	$param['field_params'][0]['tovar']['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id={shop_shops_id}&view_order_id={shop_order_id}", 76, 'load_data');
	$param['field_params'][0]['tovar']['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id={shop_shops_id}&view_order_id={shop_order_id}", 76, 'load_data');

	$param['field_params'][0]['shop_order_sum']['callback_function'] = 'callback_function_shop_order_sum';

	// Функция обратного вызова
	function callback_function_shop_order_sum($field_value, $value, $row)
	{
		$shop = & singleton('shop');

		echo $shop->Round($shop->GetOrderSum($row['shop_order_id']));

		$currency_row = $shop->GetCurrency($row['shop_currency_id']);

		if ($currency_row)
		{
			echo ' '.$currency_row['shop_currency_name'];
		}
	}

	$param['total_count'][] = $count;
	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;
	$param['title'] = sprintf($GLOBALS['MSG_shops']['show_order_title'], $row['shop_shops_name']);

	return $param;
}

/**
 * Изменение статуса "отменен"
 *
 * @param array $param
 */
function cancel(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$DataBase = & 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');

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

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

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

						$DataBase->query("UPDATE shop_order_table SET `shop_order_cancel` = 1-`shop_order_cancel`" .
								"WHERE `shop_order_id` = '$key'");
						
						// Вызываем обработчик платежной системы для события "Удаление"
						$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], array('shop_order_id' => $key, 'action' => 'cancel'));
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

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

/**
 * Изменение статуса (оплачено/неоплачено)
 *
 * @param array $param
 */
function status(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				$shop = & singleton('shop');

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

					$shop = & singleton('shop');

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$shop_order_id = intval($key);
						
						// Изменяем статус оплаты
						$shop->SetOrderPaymentStatus($shop_order_id);
						
						// Если статус - включен, отправляем пользователю информацию об оплате и списываем эл.товары (если есть)
						$order_row = $shop->GetOrder($shop_order_id);

						// Проверяем, если товар - электронный, то выводим сообщение, что письмо с эл. товаром отправлено.
						//show_message("");
						
						// Получаем информацию о магазине
						$shop_shops_id = to_int($order_row['shop_shops_id']);

						$shop_row = $shop->GetShop($shop_shops_id);

						$structure = & singleton('Structure');
						$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));

						$lib = new lib();
						$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));

						if ($order_row)
						{
							$DateClass = new DateClass();
							$date_str = $DateClass->datetime_format($order_row['shop_order_date_time']);
						}
						else
						{
							$date_str = '';
						}

						// Если предыдущий статус заказа был равен 0 (был выключен), то отправляем данные о заказе
						if (to_int($order_row['shop_order_status_of_pay']) == 1)
						{
							$affiliate = new affiliate();
							
							$affiliate->AcceptAffiliatePlanForSiteUsers($order_row['site_users_id'], $shop_order_id);
							
							$shop->SendMailAboutOrder($order_row['shop_shops_id'],
							$shop_order_id,
							$order_row['site_users_id'],
							to_str($LA['xsl_letter_to_admin']),
							to_str($LA['xsl_letter_to_user']),
							$order_row['shop_order_users_email'],
							array(
							'admin-content-type' => 'html',
							'user-content-type' => 'html',
							'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'], $shop_order_id, $shop_row['shop_shops_name'], $date_str),
							'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_user_subject'], $shop_order_id, $shop_row['shop_shops_name'], $date_str)));
						}
						
						// Вызываем обработчик платежной системы для события сменя статуса
						$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], array('shop_order_id' => $shop_order_id, 'action' => 'status'));
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

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

/**
 * Удаление оформленного заказа
 *
 * @param array $param
 */
function delete_order(&$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');

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// Вызываем обработчик платежной системы для события "Удаление"
						$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], array('shop_order_id' => $key, 'action' => 'delete'));
						
						if (!$shop->DeleteOrder($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_order(&$param)
{
	ob_start();

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

				$shop = & singleton('shop');

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

				if ($order_row)
				{
					$object_user_id = $order_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_order.php');

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

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