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

global $NavNum;
$NavNum = 0;

if(CModule::IncludeModule('iblock'))
{
	$arResult = [
		'MODELS' => [], 
	];
	$options = Array( "nPageSize" => 6 );

	$models_res = CIBlockElement::GetList([ "RAND" => "ASC" ], [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_MODELS, "PROPERTY_BRAND_UID" => $arParams['BRAND_UID'], "!ID" => $arParams['EXCEPT'] ], false, $options);
	while ($models_ob_element = $models_res->GetNextElement())
	{
		$models_ar_res = $models_ob_element->GetFields();
		$models_ar_res['PROPERTIES'] = $models_ob_element->GetProperties();

		if(!empty($models_ar_res['PREVIEW_PICTURE']))
		{
			$models_ar_res['IMAGE_PREPARED'] = true;
			$models_ar_res['PREVIEW_PICTURE'] = CFile::GetPath($models_ar_res['PREVIEW_PICTURE']);
		}
		else
		{
			$cars_res = CIBlockElement::GetList([ "NAME" => "ASC" ], [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_NEW, "PROPERTY_MODEL" => $models_ar_res['ID'] ], 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();

				$models_ar_res['IMAGE_PREPARED'] = false;
				$models_ar_res['PREVIEW_PICTURE'] = $cars_ar_res['PROPERTIES']['IMAGE_URL']['VALUE'];
			}
		}	

		$models_ar_res['URL'] = "/catalog/".$arParams['BRAND_CODE']."/".$models_ar_res['CODE']."/";

		$arResult['MODELS'][] = $models_ar_res;
	}

	$this->IncludeComponentTemplate();
}