<?
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 = [
			'SECTIONS' => [], 
		];

		$sort = [ "SORT" => "ASC" ];
		$filter = [ "ACTIVE" => "Y", "IBLOCK_ID" => $arParams['IBLOCK_ID'] ];
		$section_filter = $filter;
		$element_filter = $filter;
		$options = false;

		$types_ids = [];

		if(isset($arParams['GROUP']))
		{
			$section_filter['ID'] = $arParams['GROUP'];
		}

		if(isset($arParams['BRAND']))
		{
			$res_filter = CIBlockElement::GetList(
				[ "SORT" => "ASC" ], 
				[ "ACTIVE" => "Y", "IBLOCK_ID" => $arParams['IBLOCK_ID_RULES'], "PROPERTY_VEHICLE_BRAND" => $arParams['BRAND'], "!PROPERTY_VEHICLE_TYPE" => false, ], 
				false, false, ['ID', 'NAME', 'PROPERTY_VEHICLE_TYPE']
			);
			while ($ar_element_filter = $res_filter->GetNextElement())
			{
				$ar_res_filter = $ar_element_filter->GetFields();
				array_push($types_ids, $ar_res_filter['PROPERTY_VEHICLE_TYPE_VALUE']);
			}

		}

		
		$sec_res = CIBlockSection::GetList($sort, $section_filter, false, [], false);
		while ($section = $sec_res->GetNext())
		{	
			if(!empty($section['PICTURE']))
			{
				$section['PICTURE'] = CFile::GetPath($section['PICTURE']);
			}
			
			$section['ITEMS'] = [];
			
			$res = CIBlockElement::GetList($sort, array_merge($element_filter, [ "SECTION_ID" => $section['ID'] ]), false, $options);	
			while ($element = $res->GetNextElement())
			{
				$ar_res = $element->GetFields();

				if(isset($arParams['BRAND']))
				{
					if(in_array($ar_res['ID'], $types_ids))
					{
						$section['ITEMS'][] = $ar_res;
					}
				}
				else
				{
					$section['ITEMS'][] = $ar_res;
				}
			}

			if(count($section['ITEMS']) > 0)
			{
				$arResult['SECTIONS'][] = $section;
			}
		}

		$this->IncludeComponentTemplate();
	}
}