<?
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($this->StartResultCache(60*60*24, md5(var_export($_POST, true))))
{
	if(CModule::IncludeModule('iblock'))
	{
		$arResult = [
			'MODELS' => [], 
		];

		$models_sort = [ "SORT" => "ASC" ];
		$models_filter = [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_MODELS, "PROPERTY_BRAND_UID" => $arParams['BRAND_UID'], "PROPERTY_PROMO_VALUE" => "Да" ];

		$models_res = CIBlockElement::GetList($models_sort, $models_filter, false, []);
		while ($models_element = $models_res->GetNextElement())
		{
			$models_ar_res = $models_element->GetFields();
			$models_ar_res['PROPERTIES'] = $models_element->GetProperties();
			$models_ar_res['ITEMS'] = [];

			$cars_sort = [ "NAME" => "ASC" ];
			$cars_filter = [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_NEW, "PROPERTY_MODEL" => $models_ar_res['ID'], ];

			$position_res = CIBlockElement::GetList($cars_sort, $cars_filter, false, [ "nPageSize" => 3 ]);

			while ($position_element = $position_res->GetNextElement())
			{
				$ar_res = $position_element->GetFields();
				$ar_res['PROPERTIES'] = $position_element->GetProperties();
				$ar_res['PROPERTIES']['BRAND']['RELATED'] = get_related(IBLOCK_ID_BRANDS, $ar_res['PROPERTIES']['BRAND']['VALUE']);
				$ar_res['PROPERTIES']['MODEL']['RELATED'] = get_related(IBLOCK_ID_MODELS, $ar_res['PROPERTIES']['MODEL']['VALUE']);
				$ar_res['PROPERTIES']['MODIFICATION']['RELATED'] = get_related(IBLOCK_ID_MODIFICATIONS, $ar_res['PROPERTIES']['MODIFICATION']['VALUE']);

				$ar_res['CALCULATION'] = [];
				$ar_res['CALCULATION']['MONTHLY'] = number_format(($ar_res['PROPERTIES']['PRICE']['VALUE'] / CALCULATION_COEFFICIENT), 0, ".", " ");
				$ar_res['CALCULATION']['SAVINGS_TAX'] = number_format((($ar_res['PROPERTIES']['PRICE']['VALUE'] / 100) * 4), 0, ".", " ");
				$ar_res['CALCULATION']['SAVINGS_VAT'] = number_format((($ar_res['PROPERTIES']['PRICE']['VALUE'] / 100) * 4), 0, ".", " ");

				$models_ar_res['ITEMS'][] = $ar_res;
			}

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

		$this->IncludeComponentTemplate();
	}
}