<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
/** @var CBitrixComponent $this */
/** @var array $arParams */
/** @var array $arResult */
/** @var string $componentPath */
/** @var string $componentName */
/** @var string $componentTemplate */
/** @global CDatabase $DB */
/** @global CUser $USER */
/** @global CMain $APPLICATION */

use Bitrix\Main\Context,
	Bitrix\Main\Type\DateTime,
	Bitrix\Main\Loader,
	Bitrix\Iblock;

if($this->StartResultCache(60*60*24, md5(var_export($_POST, true))))
{
	if(CModule::IncludeModule('iblock'))
	{
		$arResult = [
			'ITEMS' => [], 
			'SEARCH' => $_REQUEST['search'], 
			'SORT' => $_REQUEST['sort'], 
			'ORDER' => $_REQUEST['order'], 
		];

		$query = null;
		$query_arr = [];

		$sort = Array("SORT" => "ASC");
		if(!empty($_REQUEST['sort']))
		{
			$query_arr['sort'] = $_REQUEST['sort'];

			if($_REQUEST['sort'] === "to")
			{
				if($_REQUEST['order'] === "desc")
				{ $sort = array_merge($sort, ["ACTIVE_TO" => "DESC" ]); }
				else
				{ $sort = array_merge($sort, ["ACTIVE_TO" => "ASC" ]); }
			}
			elseif($_REQUEST['sort'] === "from")
			{
				$query_arr['sort'] = $_REQUEST['sort'];
				if($_REQUEST['order'] === "desc")
				{ $sort = array_merge($sort, ["ACTIVE_FROM" => "DESC" ]); }
				else
				{ $sort = array_merge($sort, ["ACTIVE_FROM" => "ASC" ]); }
			}
			elseif($_REQUEST['sort'] === "number")
			{
				$query_arr['sort'] = $_REQUEST['sort'];
				if($_REQUEST['order'] === "desc")
				{ $sort = array_merge($sort, ["NAME" => "DESC" ]); }
				else
				{ $sort = array_merge($sort, ["NAME" => "ASC" ]); }
			}
			elseif($_REQUEST['sort'] === "name")
			{
				$query_arr['sort'] = $_REQUEST['sort'];
				if($_REQUEST['order'] === "desc")
				{ $sort = array_merge($sort, ["CODE" => "DESC" ]); }
				else
				{ $sort = array_merge($sort, ["CODE" => "ASC" ]); }
			}
		}
		else
		{
			$sort = array_merge($sort, ["ACTIVE_TO" => "DESC" ]);
		}

		if(!empty($_REQUEST['order']))
		{
			$query_arr['order'] = $_REQUEST['order'];
		}

		$filter = Array("IBLOCK_ID" => 17);
		$options = Array("nPageSize" => 10);

		if(!empty($_REQUEST['search']))
		{
			$filter = array_merge($filter, [ 
				[
					"LOGIC" => "OR",
					"NAME" => "%".$_REQUEST['search']."%", 
					"CODE" => "%".$_REQUEST['search']."%"
				]
			]);
			$query_arr['search'] = $_REQUEST['search'];
		}

		if(count($query_arr) > 0)
		{
			$query = http_build_query($query_arr);
		}

		$res = CIBlockElement::GetList($sort, $filter, false, $options);	
		while ($element = $res->GetNextElement())
		{
			$ar_res = $element->GetFields();
			$arResult['ITEMS'][] = $ar_res;
		}

		$arResult["NAV_STRING"] = $res->GetPageNavStringEx(
			$navComponentObject, 
			"", 
			"catalog", 
			"N",
			null, 
			[
				 "section_code" => "/revocation/", 
				 "query" => $query, 
			]
		);

		$this->IncludeComponentTemplate();
	}
}