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

		$brands_filter_array = [ "ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_BRANDS, "PROPERTY_PROMO_VALUE" => "Да" ];
		if(isset($arParams['FILTER_ARRAY']))
		{
			$brands_filter_array = array_merge($brands_filter_array, $arParams['FILTER_ARRAY']);
		}

		$brands_res = CIBlockElement::GetList([ "SORT" => "ASC" ], $brands_filter_array, false, []);
		while ($brands_element = $brands_res->GetNextElement())
		{
			$brands_ar_res = $brands_element->GetFields();
			$brands_ar_res['ITEMS'] = [];

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

			$position_res = CIBlockElement::GetList([ "NAME" => "ASC" ], $positions_filter_array, 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(8, $ar_res['PROPERTIES']['BRAND']['VALUE']);
				$ar_res['PROPERTIES']['MODEL']['RELATED'] = get_related(9, $ar_res['PROPERTIES']['MODEL']['VALUE']);
				$ar_res['PROPERTIES']['MODIFICATION']['RELATED'] = get_related(10, $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, ".", " ");

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

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

		$this->IncludeComponentTemplate();
	}
}