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

		$brands_filter = [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_BRANDS ];
		if(isset($arParams['BRANDS_IDS']) && count($arParams['BRANDS_IDS']) > 0)
		{
			$brands_filter[ "ID" ] = $arParams['BRANDS_IDS'];
		}

		$brands_res = CIBlockElement::GetList([ "NAME" => "ASC" ], $brands_filter, false, []);
		while ($brands_ob_element = $brands_res->GetNextElement())
		{
			$brands_ar_res = $brands_ob_element->GetFields();
			$brands_ar_res['PROPERTIES'] = $brands_ob_element->GetProperties();

			if(!empty($brands_ar_res['PREVIEW_PICTURE']))
			{
				$brands_ar_res['PREVIEW_PICTURE'] = CFile::GetPath($brands_ar_res['PREVIEW_PICTURE']);
			}

			if(isset($arParams['PROPERTIES_FILTER_ARRAY']))
			{
				$brand_image_filter = array_merge(
					[ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_NEW, "PROPERTY_BRAND" => $brands_ar_res['ID'], ], 
					$arParams['PROPERTIES_FILTER_ARRAY']
				);

				$cars_res = CIBlockElement::GetList([ "PROPERTY_PRICE" => "DESC" ], $brand_image_filter, false, [ "nPageSize" => 1 ]);
				while ($cars_ob_element = $cars_res->GetNextElement())
				{
					$cars_ar_res = $cars_ob_element->GetFields();
					$cars_ar_res['PROPERTIES'] = $cars_ob_element->GetProperties();

					$brands_ar_res['PREVIEW_PICTURE'] = $cars_ar_res['PROPERTIES']['IMAGE_URL']['VALUE'];
				}
			}
			else
			{
				if(empty($brands_ar_res['PREVIEW_PICTURE']))
				{
					$brand_image_filter = [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_NEW, "PROPERTY_BRAND" => $brands_ar_res['ID'] ];

					$cars_res = CIBlockElement::GetList([ "PROPERTY_PRICE" => "DESC" ], $brand_image_filter, false, [ "nPageSize" => 1 ]);
					while ($cars_ob_element = $cars_res->GetNextElement())
					{
						$cars_ar_res = $cars_ob_element->GetFields();
						$cars_ar_res['PROPERTIES'] = $cars_ob_element->GetProperties();

						$brands_ar_res['PREVIEW_PICTURE'] = $cars_ar_res['PROPERTIES']['IMAGE_URL']['VALUE'];
					}
				}
			}

			$arResult['BRANDS'][] = $brands_ar_res;
		}

		$this->IncludeComponentTemplate();
	}
}