<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка оформленных заказов.
 *
 * Файл: /admin/shop/action/load_order.php
 *
 * @author Hostmake LLC
 * @version 5.x
 */
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` LEFT JOIN `shop_order_status_table` USING(`shop_order_status_id`)
	WHERE `shop_shops_id` = '$shop_shops_id'
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Число нужных записей.
	$count = "SELECT count(shop_order_id) AS count 
	FROM `shop_order_table` LEFT JOIN `shop_order_status_table` USING(`shop_order_status_id`)
	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_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';
	$param['field_params'][0]['shop_order_status_name']['callback_function'] = 'callback_function_shop_order_status';

	function callback_function_shop_order_status($field_value, $value, $row)
	{
		if ($value != '')
		{
			echo $value;
		}
		else
		{
			echo $GLOBALS['MSG_shops']['status_not_specify'];
		}
	}
	
	// Функция обратного вызова для расчета суммы
	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 "&nbsp;{$currency_row['shop_currency_name']}";
		}
	}
	
	$param['field_params'][0]['shop_order_weight']['callback_function'] = 'callback_function_shop_order_weight';
	
	// Функция обратного вызова
	function callback_function_shop_order_weight($field_value, $value, $row)
	{
		$shop = & singleton('shop');

		$order_weight = 0;

		// Получаем информацию о товарах в заказе
		$resource_order_items =  $shop->GetOrderItems($row['shop_order_id']);

		// Цикл по товарам, находящимся в заказе
		while($order_item_row = mysql_fetch_assoc($resource_order_items))
		{
			// Получаем информацию о товаре
			$item_row = $shop->GetItem($order_item_row['shop_items_catalog_item_id']);

			$order_weight += $order_item_row['shop_order_items_quantity'] * $item_row['shop_items_catalog_weight'];
		}

		// Получение информации о единице измерения товаров, применяемой в магазине
		$shop_info = $shop->GetShop($row['shop_shops_id']);

		$shop_meure_info = $shop->GetMesure($shop_info['shop_mesures_id']);

		echo $order_weight . ' ' .$shop_meure_info['shop_mesures_name'];
	}

	// Функция обратного вызова для ФИЛЬТРА поля "Статус заказа"
	$param['field_params']['filter']['shop_order_status_name']['filter_callback_function'] = 'filter_callback_function_shop_order_status_name';
	$param['field_params']['filter']['shop_order_status_name']['admin_forms_field_type'] = 10;

	function filter_callback_function_shop_order_status_name ($field_value, $value, $row)
	{		
		//$shop_shops_id = to_int($_REQUEST['shop_shops_id']);
		
		$shop = & singleton('shop');
		
		$mas_status = $shop->GetAllOrderStatus();
				
		$selected_value = to_str($_REQUEST["admin_form_filter_" . $row['admin_forms_field_id']]);

		// Получаем список типов социальной сети
		?>
		<select name="admin_form_filter_<?php echo $row['admin_forms_field_id']?>" id="id_admin_form_filter_<?php echo $row['admin_forms_field_id']?>" onkeydown="DoKeyDownFilter(event)">
		<option value=""><?php echo $GLOBALS['MSG_shops']['all']?></option>
		<?php 
		while ($row_order_status = mysql_fetch_assoc($mas_status))
		{
			if ($row_order_status['shop_order_status_name'] == $selected_value)
			{
				$selected = ' selected';
			}
			else
			{
				$selected = '';
			}
			
			$sns_type_name = htmlspecialchars($row_order_status['shop_order_status_name']);
			?>
				<option value="<?php echo $sns_type_name?>" <?php echo $selected?>><?php echo $sns_type_name;?></option>
			<?php 
		}
		?>
		</select>
		<?php		
	}
	
	$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'");

						$aExecParam = array('shop_order_id' => $key, 'action' => 'cancel');
	
						// Предыдущие даные о заказе до редактирования
						$aExecParam['prev_order_row'] = $order_row;

						// Вызываем обработчик платежной системы для события "Удаление"
						$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], $aExecParam);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

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


function recalc_delivery(&$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))
					{
						//echo "Редактирование заказа #$key";
						// Необходимо пересчитать вес товаров в заказе, получаем список товаров заказа
						$order_items_res = $shop->GetOrderItems($key);
						
						$items_weight = 0.0;
						$items_price = 0.0;
						
						if($order_items_res)
						{
							while($order_items_row = mysql_fetch_assoc($order_items_res))
							{
								if(to_int($order_items_row['shop_items_catalog_item_id']) == 0)
								{
									// нашли доставку, либо ошибка базы
									continue;
								}
								else
								{
									$item_data = $shop->GetItem($order_items_row['shop_items_catalog_item_id']);
									
									$items_weight += to_float($item_data['shop_items_catalog_weight']) * to_float($order_items_row['shop_order_items_quantity']);
									$items_price += to_float($order_items_row['shop_order_items_price']) * to_float($order_items_row['shop_order_items_quantity']);
								}
							}
						}
						
						//$items_price = $shop->GetOrderSum($key);
						
						// Получаем данные о заказе
						$order_row = $shop->GetOrder($key);
						
						// Получаем тип доставки через условие доставки
						$cond_of_delivery_row = $shop->GetCondOfDelivery($order_row['shop_cond_of_delivery_id']);

						$array_data = $shop->GetTypeOfDeliveryForOrder($cond_of_delivery_row['shop_type_of_delivery_id'], $order_row['shop_country_id'], $order_row['shop_location_id'], $order_row['shop_city_id'], $order_row['shop_city_area_id'], $items_weight, $items_price);
					
						if($array_data === false)
						{
							// Тип доставки и условие не найден, ошибка автоматической смены типа доставки и условия
							
							//$query = "UPDATE `shop_order_table` SET `shop_cond_of_delivery_id`='0' WHERE `shop_order_id`='$key'";
							
							//$DataBase->query($query);
							
							// Удаляем доставку из списка товаров заказа
							//$query = "DELETE FROM `shop_order_items_table` WHERE `shop_order_items_type`='1' AND `shop_order_id`='$key'";
							
							//$DataBase->query($query);
							
							// Тип доставки и условие найдены, делаем замену
							//$shop->InsertOrder($order_row);
							
							show_error_message($GLOBALS['MSG_shops']['order_new_cond_of_delivery_not_found']);
						}
						//elseif(to_int($array_data['shop_cond_of_delivery_id']) == to_int($order_row['shop_cond_of_delivery_id']))
						//{
							// Текущий тип доставки и условие корректны
						//	show_message($GLOBALS['MSG_shops']['order_new_cond_of_delivery_error']);
						//}
						else
						{
						
							// Необходимо обновить информацию о старой доставке
							$query = "UPDATE `shop_order_table` SET `shop_cond_of_delivery_id`='" . $array_data['shop_cond_of_delivery_id'] . "' WHERE `shop_order_id`='$key'";
							
							$DataBase->query($query);
							
							// Плучаем информацию о типе доставки
							$cond_of_delivery_row = $shop->GetCondOfDelivery($array_data['shop_cond_of_delivery_id']);
							
							$type_of_delivery_row = $shop->GetTypeOfDelivery($cond_of_delivery_row['shop_type_of_delivery_id']);
							
							$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

							$row = $shop->GetShop($shop_shops_id);
							
							$shop_currency_id = to_int($row['shop_currency_id']);
							
							$coefficient = $shop->GetCurrencyCoefficientToShopCurrency($cond_of_delivery_row['shop_currency_id'], $shop_currency_id);
						
							$aPriceDelivery = $shop->GetPriceForCondOfDelivery($cond_of_delivery_row['shop_cond_of_delivery_id']);
							
							$price_delivery = sprintf("%.2f", $aPriceDelivery['price_tax'] * $coefficient);

							//$cond_of_delivery_price = $cond_of_delivery_row['shop_cond_of_delivery_price'];
							$cond_of_delivery_price = $price_delivery;
							
							$query = "UPDATE `shop_order_items_table` SET `shop_order_items_price`='$cond_of_delivery_price' WHERE `shop_order_id`='$key' AND `shop_order_items_type`='1'";
							
							$DataBase->query($query);
							
							show_message($GLOBALS['MSG_shops']['order_new_cond_of_delivery_accept']);
						}
					}
				}
			}
		}
	}
	
	$error = ob_get_clean();

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

/**
 * Изменение статуса (оплачено/неоплачено)
 *
 * @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);

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

						// Информация о заказе
						$order_row = $shop->GetOrder($shop_order_id);

						// Текущий статус соответствует установленному статусу в базе данных
						if ($current_status == $order_row['shop_order_status_of_pay'])
						{
							// Изменяем статус оплаты
							$shop->SetOrderPaymentStatus($shop_order_id);

							$submit_order_data = $current_status == 0 ? 1 : 0;
						}

						// Если предыдущий статус заказа был равен 0 (был выключен), то отправляем данные о заказе
						//if (to_int($order_row['shop_order_status_of_pay']) == 1)
						if (isset($submit_order_data))
						{
							if ($submit_order_data)
							{
								$affiliate = & singleton('affiliate');
								$affiliate->AcceptAffiliatePlanForSiteUsers($order_row['site_users_id'], $shop_order_id);
							}
							else
							{
								// Снимаем активность с проводок по этому заказу т.к. он отменен
    							$query = "UPDATE `shop_site_users_account_table`
        						SET `shop_site_users_account_active` = '0'
        						WHERE `shop_order_id` = '$shop_order_id'";
    							$DataBase->query($query);
							}
						}

						$aExecParam = array('shop_order_id' => $shop_order_id, 'action' => 'status');
	
						// Предыдущие даные о заказе до редактирования
						$aExecParam['prev_order_row'] = $order_row;
						
						// Вызываем обработчик платежной системы для события сменя статуса
						$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], $aExecParam);
					}
					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))
					{
						$aExecParam = array('shop_order_id' => $key, 'action' => 'delete');
	
						// Предыдущие даные о заказе до редактирования
						$aExecParam['prev_order_row'] = $order_row;
						
						// Вызываем обработчик платежной системы для события "Удаление"
						$shop->ExecSystemsOfPayChangeStatus($order_row['shop_system_of_pay_id'], $aExecParam);

						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;
}
?>