<?
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'))
	{
		$breadcrumbs = [];
		$canonical = [];

		$arResult = [
			'SELECTED' => [], 
			'TITLES' => [], 
			'ITEMS' => []
		];

		$query = null;
		$query_arr = [];

		$sort = Array("SORT" => "DESC", "ID" => "DESC");
		if(isset($arParams['SORT']))
		{
			if($arParams['SORT'] === "name")
			{
				$sort = Array("SORT" => "DESC", "NAME" => "ASC");
				$arResult['SCROLL'] = true;
			}
			if($arParams['SORT'] === "date")
			{
				$sort = Array("SORT" => "DESC", "ID" => "DESC");
				$arResult['SCROLL'] = true;
			}
			if($arParams['SORT'] === "low")
			{
				$sort = Array("SORT" => "DESC", "PROPERTY_PRICE" => "ASC");
				$query_arr['SORT'] = $arParams['SORT'];
				$arResult['SCROLL'] = true;
			}
			if($arParams['SORT'] === "high")
			{
				$sort = Array("SORT" => "DESC", "PROPERTY_PRICE" => "DESC");
				$query_arr['SORT'] = $arParams['SORT'];
				$arResult['SCROLL'] = true;
			}

			$arResult['SELECTED']['SORT'] = $arParams['SORT'];
		}
		$filter = Array("IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_USED);
		$options = Array("nPageSize" => !empty($arParams['COUNT_PER_PAGE']) ? $arParams['COUNT_PER_PAGE'] : 15);

		$pages_url = $arParams['PATH'];

		$arResult['BRAND_DISABLED'] = false;
		$arResult['MODEL_DISABLED'] = false;
		$arResult['EXTENDED'] = false;
		$arResult['BY_OPTIONS'] = false;
		$arResult['FILTER_SMALL'] = $arParams['FILTER_SMALL'] ? true : false;

		$arResult['SHOW_BRANDS_LIST'] = true;
		$arResult['SHOW_MODELS_LIST'] = false;

		if(empty($arParams['PROGRAM']))
		{
			$arResult['SHOW_SPECIAL_OFFERS'] = true;
			$arResult['SHOW_PROMO_BRANDS'] = true;
		}

		if(!empty($arParams['BRAND']))
		{
			$brands_res = CIBlockElement::GetList(["NAME" => "ASC"], ["IBLOCK_ID" => IBLOCK_ID_BRANDS_USED, "CODE" => $arParams['BRAND']], false, []);
			while ($brands_ob_element = $brands_res->GetNextElement())
			{
				$brands_ar_res = $brands_ob_element->GetFields();
				$brands_ar_res['PROPERTIES'] = $brands_ob_element->GetProperties();

				$filter['PROPERTY_BRAND'] = $brands_ar_res['ID'];
				$pages_url = $pages_url.$brands_ar_res['CODE']."/";
				$arResult['SELECTED']['BRAND'] = $brands_ar_res['CODE'];
				$arResult['SELECTED']['BRAND_ID'] = $brands_ar_res['ID'];
				$arResult['SELECTED']['BRAND_UID'] = $brands_ar_res['PROPERTIES']['UID']['VALUE'];
				$arResult['TITLES']['BRAND'] = $brands_ar_res['NAME'];
				$arResult['TITLES']['TRANSCRIPTION'] = !empty($brands_ar_res['PROPERTIES']['TRANSCRIPTION']['VALUE']) ? $brands_ar_res['PROPERTIES']['TRANSCRIPTION']['VALUE'] : $brands_ar_res['NAME'];

				if($brands_ar_res['ACTIVE'] === "Y")
				{
					$arResult['BRAND_DISABLED'] = false;
					$arResult['SHOW_BRANDS_LIST'] = false;
					$arResult['SHOW_MODELS_LIST'] = true;
					$arResult['MODEL_DISABLED'] = false;
				}
				else
				{
					$arResult['BRAND_DISABLED'] = true;
					$arResult['MODEL_DISABLED'] = true;
					$arResult['SHOW_MODELS_LIST'] = false;
				}

				$arResult['SHOW_PROMO_BRANDS'] = false;

				array_push($breadcrumbs, [ 
					"NAME" => $brands_ar_res['NAME'], 
					"URL" => "https://".SITE_SERVER_NAME.$arParams['PATH'].$arResult['SELECTED']['BRAND']."/", 
				]);

				array_push($canonical, $arParams['BRAND']);
			}

			$arResult['EXTENDED'] = true;
			$arResult['FILTER_SMALL'] = false;
			$arResult['SCROLL'] = true;

			if(empty($arResult['SELECTED']['BRAND']))
			{
				define('ERROR_404', 'Y');
			}
		}

		if(!empty($arParams['MODEL']))
		{
			$models_res = CIBlockElement::GetList(["NAME" => "ASC"], ["IBLOCK_ID" => IBLOCK_ID_MODELS_USED, "CODE" => $arParams['MODEL'], "PROPERTY_BRAND_UID" => $arResult['SELECTED']['BRAND_UID']], false, []);
			while ($models_ob_element = $models_res->GetNextElement())
			{
				$models_ar_res = $models_ob_element->GetFields();
				$models_ar_res['PROPERTIES'] = $models_ob_element->GetProperties();

				$filter['PROPERTY_MODEL'] = $models_ar_res['ID'];
				$pages_url = $pages_url.$models_ar_res['CODE']."/";
				$arResult['SELECTED']['MODEL'] = $models_ar_res['CODE'];
				$arResult['TITLES']['MODEL'] = $models_ar_res['NAME'];

				if($models_ar_res['ACTIVE'] === "Y")
				{
					$arResult['MODEL_DISABLED'] = false;
					$arResult['SHOW_MODELS_LIST'] = false;
				}
				else
				{
					$arResult['MODEL_DISABLED'] = true;
					$arResult['SHOW_PROMO_BRANDS'] = false;
				}

				array_push($breadcrumbs, [ 
					"NAME" => $models_ar_res['NAME'], 
					"URL" => "https://".SITE_SERVER_NAME.$arParams['PATH'].$arResult['SELECTED']['BRAND']."/".$arResult['SELECTED']['MODEL']."/", 
				]);

				array_push($canonical, $arParams['MODEL']);

				if(!is_null($arParams['REGION']) && $arParams['REGION'] !== "root")
				{
					if($models_ar_res['PROPERTIES']['REGIONS']['VALUE'] !== "Да")
					{
						$APPLICATION->SetPageProperty("robots", "noindex, nofollow");
					}
				}

				if($models_ar_res['PROPERTIES']['SEO_INDEXING']['VALUE_XML_ID'] !== 'YES')
				{
					$APPLICATION->SetPageProperty("robots", "noindex, nofollow");					
				}
			}

			$arResult['EXTENDED'] = true;
			$arResult['SCROLL'] = true;

			if(empty($arResult['SELECTED']['MODEL']))
			{
				define('ERROR_404', 'Y');
			}
		}

		if(isset($arParams['MODIFICATION']))
		{
			if(!empty($arParams['MODIFICATION']))
			{
				$arResult['EXTENDED'] = true;
				$arResult['SELECTED']['MODIFICATION'] = $arParams['MODIFICATION'];
				$arResult['SCROLL'] = true;
	
				$filter['PROPERTY_MODIFICATION'] = $arParams['MODIFICATION'];
				$query_arr['MODIFICATION'] = $arParams['MODIFICATION'];
			}
			else
			{
				LocalRedirect("https://".SITE_SERVER_NAME.$arParams['PATH'].$arResult['SELECTED']['BRAND']."/".$arResult['SELECTED']['MODEL']."/", true, "301 Moved permanently");
			}
		}

		$parameters_filter_count = 0;

		if(!empty($arParams['DRIVE']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['DRIVE'] = $arParams['DRIVE'];
			$filter['=PROPERTY_DRIVE'] = $arParams['DRIVE'];

			$query_arr['DRIVE'] = $arParams['DRIVE'];
		}

		if(!empty($arParams['GEAR']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['GEAR'] = $arParams['GEAR'];
			$filter['=PROPERTY_GEAR'] = $arParams['GEAR'];

			$query_arr['GEAR'] = $arParams['GEAR'];
		}

		if(!empty($arParams['ENGINE_FUEL']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['ENGINE_FUEL'] = $arParams['ENGINE_FUEL'];
			$filter['=PROPERTY_ENGINE_FUEL'] = $arParams['ENGINE_FUEL'];

			$query_arr['ENGINE_FUEL'] = $arParams['ENGINE_FUEL'];
		}

		if(!empty($arParams['ENGINE_POWER_FROM']) || !empty($arParams['ENGINE_POWER_TO']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$filter['><PROPERTY_ENGINE_POWER'] = [ !empty($arParams['ENGINE_POWER_FROM']) ? $arParams['ENGINE_POWER_FROM'] : 0, !empty($arParams['ENGINE_POWER_TO']) ? $arParams['ENGINE_POWER_TO'] : 1000 ];

			if(!empty($arParams['ENGINE_POWER_FROM']))
			{
				$arResult['SELECTED']['ENGINE_POWER_FROM'] = $arParams['ENGINE_POWER_FROM'];
				$query_arr['ENGINE_POWER_FROM'] = $arParams['ENGINE_POWER_FROM'];
			}
			if(!empty($arParams['ENGINE_POWER_TO']))
			{
				$arResult['SELECTED']['ENGINE_POWER_TO'] = $arParams['ENGINE_POWER_TO'];
				$query_arr['ENGINE_POWER_TO'] = $arParams['ENGINE_POWER_TO'];
			}
		}

		if(!empty($arParams['ENGINE_VOLUME_FROM']) || !empty($arParams['ENGINE_VOLUME_TO']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$filter['><PROPERTY_ENGINE_VOLUME'] = [ !empty($arParams['ENGINE_VOLUME_FROM']) ? $arParams['ENGINE_VOLUME_FROM'] : 0, !empty($arParams['ENGINE_VOLUME_TO']) ? $arParams['ENGINE_VOLUME_TO'] : 10000 ];

			if(!empty($arParams['ENGINE_VOLUME_FROM']))
			{
				$arResult['SELECTED']['ENGINE_VOLUME_FROM'] = $arParams['ENGINE_VOLUME_FROM'];
				$query_arr['ENGINE_VOLUME_FROM'] = $arParams['ENGINE_VOLUME_FROM'];
			}
			if(!empty($arParams['ENGINE_VOLUME_TO']))
			{
				$arResult['SELECTED']['ENGINE_VOLUME_TO'] = $arParams['ENGINE_VOLUME_TO'];
				$query_arr['ENGINE_VOLUME_TO'] = $arParams['ENGINE_VOLUME_TO'];
			}
		}

		if(!empty($arParams['YEAR_FROM']) || !empty($arParams['YEAR_TO']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$filter['><PROPERTY_YEAR'] = [ !empty($arParams['YEAR_FROM']) ? $arParams['YEAR_FROM'] : 0, !empty($arParams['YEAR_TO']) ? $arParams['YEAR_TO'] : 10000 ];

			if(!empty($arParams['YEAR_FROM']))
			{
				$arResult['SELECTED']['YEAR_FROM'] = $arParams['YEAR_FROM'];
				$query_arr['YEAR_FROM'] = $arParams['YEAR_FROM'];
			}
			if(!empty($arParams['YEAR_TO']))
			{
				$arResult['SELECTED']['YEAR_TO'] = $arParams['YEAR_TO'];
				$query_arr['YEAR_TO'] = $arParams['YEAR_TO'];
			}
		}

		if(!empty($arParams['MILEAGE_FROM']) || !empty($arParams['MILEAGE_TO']))
		{
			$parameters_filter_count++;

			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$filter['><PROPERTY_MILEAGE'] = [ !empty($arParams['MILEAGE_FROM']) ? $arParams['MILEAGE_FROM'] : 0, !empty($arParams['MILEAGE_TO']) ? $arParams['MILEAGE_TO'] : 10000000 ];

			if(!empty($arParams['MILEAGE_FROM']))
			{
				$arResult['SELECTED']['MILEAGE_FROM'] = $arParams['MILEAGE_FROM'];
				$query_arr['MILEAGE_FROM'] = $arParams['MILEAGE_FROM'];
			}
			if(!empty($arParams['MILEAGE_TO']))
			{
				$arResult['SELECTED']['MILEAGE_TO'] = $arParams['MILEAGE_TO'];
				$query_arr['MILEAGE_TO'] = $arParams['MILEAGE_TO'];
			}
		}

		if(!empty($arParams['BODY']))
		{
			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['BODY'] = $arParams['BODY'];
			$filter['=PROPERTY_BODY'] = $arParams['BODY'];

			$query_arr['BODY'] = $arParams['BODY'];
		}

		if(!empty($arParams['VEHICLE_TYPE']))
		{
			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['VEHICLE_TYPE'] = $arParams['VEHICLE_TYPE'];
			$filter['=PROPERTY_VEHICLE_TYPE'] = $arParams['VEHICLE_TYPE'];

			$query_arr['VEHICLE_TYPE'] = $arParams['VEHICLE_TYPE'];
		}

		if(!empty($arParams['VEHICLE_SUBTYPE']))
		{
			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['VEHICLE_SUBTYPE'] = $arParams['VEHICLE_SUBTYPE'];
			$filter['=PROPERTY_VEHICLE_SUBTYPE'] = $arParams['VEHICLE_SUBTYPE'];

			$query_arr['VEHICLE_SUBTYPE'] = $arParams['VEHICLE_SUBTYPE'];
		}

		if(!empty($arParams['PARKING_CITY']))
		{
			$arResult['EXTENDED'] = true;
			$arResult['BY_OPTIONS'] = true;
			$arResult['SCROLL'] = true;

			$arResult['SELECTED']['PARKING_CITY'] = $arParams['PARKING_CITY'];
			$filter['=PROPERTY_PARKING_CITY'] = $arParams['PARKING_CITY'];

			$query_arr['PARKING_CITY'] = $arParams['PARKING_CITY'];
		}

		if(count($query_arr) > 0)
		{
			$query = http_build_query($query_arr);
		}

		$arResult['SHOW_SPECIAL_OFFERS'] = false;
		$arResult['SHOW_PROMO_BRANDS'] = false;
		$arResult['SHOW_PROMO_MODELS'] = false;

		$res = CIBlockElement::GetList($sort, $filter, false, $options);

		while ($obElement = $res->GetNextElement())
		{
			print "<!-- MODEL RELATED";
			print_r($ar_res['PROPERTIES']['MODEL']['VALUE']);
			print "-->";
			$ar_res = $obElement->GetFields();
			$ar_res['PROPERTIES'] = $obElement->GetProperties();
			if(!empty($ar_res['PROPERTIES']['BRAND']['VALUE']))
			{
				$ar_res['PROPERTIES']['BRAND']['RELATED'] = get_related(IBLOCK_ID_BRANDS_USED, $ar_res['PROPERTIES']['BRAND']['VALUE']);
			}
			if(!empty($ar_res['PROPERTIES']['MODEL']['VALUE']))
			{
				$ar_res['PROPERTIES']['MODEL']['RELATED'] = get_related(IBLOCK_ID_MODELS_USED, $ar_res['PROPERTIES']['MODEL']['VALUE']);
			}
			if(!empty($ar_res['PROPERTIES']['MODIFICATION']['VALUE']))
			{
				$ar_res['PROPERTIES']['MODIFICATION']['RELATED'] = get_related(10, $ar_res['PROPERTIES']['MODIFICATION']['VALUE']);
			}

			$price = $ar_res['PROPERTIES']['PRICE_WITH_DISCOUNT']['VALUE'] > 0 ? $ar_res['PROPERTIES']['PRICE_WITH_DISCOUNT']['VALUE'] : $ar_res['PROPERTIES']['PRICE']['VALUE'];

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

			$ar_res['PREVIEW_PICTURE'] = CFile::GetPath($ar_res['PROPERTIES']['PHOTO']['VALUE']);

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

		if($_REQUEST['PAGEN_1'] > 1)
		{
			$arResult['SCROLL'] = true;
		}

		if(!empty($arResult['TITLES']['BRAND']))
		{
			if(!empty($arResult['TITLES']['MODEL']))
			{
				$APPLICATION->SetPageProperty("title", $arResult['TITLES']['BRAND']." ".$arResult['TITLES']['MODEL']." с пробегом (б/у) в лизинг для юридических лиц и ИП в Москве - купить подержанные автомобили ".$arResult['TITLES']['TRANSCRIPTION']." ".$arResult['TITLES']['MODEL']." в лизинг | Эволюция");
				$APPLICATION->SetPageProperty("description", "Каталог автомобилей ".$arResult['TITLES']['BRAND']." ".$arResult['TITLES']['MODEL']." с пробегом (б/у) в лизинг для юридических лиц и ИП в Москве и в других регионах России. Вы можете купить подержанные машины ".$arResult['TITLES']['BRAND']." ".$arResult['TITLES']['MODEL']." с пробегом в лизинг от официальных дилеров, автосалонов на выгодных условиях со скидкой. Телефон горячей линии ".CENTRAL_PHONE_FORMATTED." - звонок по России бесплатный.");	
				$APPLICATION->SetPageProperty("keywords", $arResult['TITLES']['BRAND']." ".$arResult['TITLES']['MODEL']." с пробегом в лизинг, ".$arResult['TITLES']['BRAND']." ".$arResult['TITLES']['MODEL']." подержанные в лизинг, ".$arResult['TITLES']['BRAND']." ".$arResult['TITLES']['MODEL']." бу в лизинг");
			}
			else
			{
				$APPLICATION->SetPageProperty("title", $arResult['TITLES']['BRAND']." с пробегом (б/у) в лизинг для юридических лиц и ИП в Москве - купить подержанные автомобили ".$arResult['TITLES']['TRANSCRIPTION']." в лизинг | Эволюция");
				$APPLICATION->SetPageProperty("description", "Каталог автомобилей ".$arResult['TITLES']['BRAND']." с пробегом (б/у) в лизинг для юридических лиц и ИП в Москве и в других регионах России. Вы можете купить подержанные машины ".$arResult['TITLES']['BRAND']." с пробегом в лизинг от официальных дилеров, автосалонов на выгодных условиях со скидкой. Телефон горячей линии ".CENTRAL_PHONE_FORMATTED." - звонок по России бесплатный.");
				$APPLICATION->SetPageProperty("keywords", $arResult['TITLES']['BRAND']." с пробегом в лизинг, ".$arResult['TITLES']['BRAND']." подержанные в лизинг, ".$arResult['TITLES']['BRAND']." бу в лизинг");
			}
		}

		$arResult['SECTION_CODE'] = !empty($arParams['section_code']) ? $arParams['section_code'] : $pages_url;
		$arResult['QUERY'] = $query;

		if(count($arResult['ITEMS']) > 0 && $arParams["PAGINATION"] == "Y")
		{
			$arResult["NAV_STRING"] = $res->GetPageNavStringEx(
				$navComponentObject, 
				"", 
				"catalog", 
				"N", 
				null, 
				[
					"section_code" => $arResult['SECTION_CODE'], 
					"query" => $arResult['QUERY'], 
				]
			);
		}

		$arResult['PAGE_CURRENT'] = $res->NavPageNomer;
		$arResult['PAGE_COUNT'] = $res->NavPageCount;

		$APPLICATION->AddHeadString('<link rel="canonical" href="https://'.SITE_SERVER_NAME.'/used/'.implode("/", $canonical).(count($canonical) > 0 ? "/" : "").'"/>');

		if($arResult['MODEL_DISABLED'])
		{
			$arResult['MODEL'] = null;
			$arResult['SELECTED']['MODEL'] = null;
			$arResult['SELECTED']['MODEL_ID'] = null;
			$arResult['SELECTED']['MODEL_UID'] = null;
			$arResult['SHOW_SPECIAL_OFFERS'] = false;
		}

		if($arResult['BRAND_DISABLED'])
		{
			$arResult['BRAND'] = null;
			$arResult['SELECTED']['BRAND'] = null;
			$arResult['SELECTED']['BRAND_ID'] = null;
			$arResult['SELECTED']['BRAND_UID'] = null;
			$arResult['SHOW_SPECIAL_OFFERS'] = false;
		}

		foreach($breadcrumbs AS $breadcrumb)
		{
			$APPLICATION->AddChainItem($breadcrumb['NAME'], $breadcrumb['URL']);
		}

		if(isset($_REQUEST['ajax']))
		{
			$GLOBALS['APPLICATION']->RestartBuffer();

			$this->IncludeComponentTemplate();
			$items = ob_get_contents();
			ob_end_clean();

			header('Content-Type: application/json; charset=utf-8');

			$response = [ 
				'ITEMS' => json_encode(str_replace(["\t","\r","\n"], ["","",""], $items), JSON_UNESCAPED_SLASHES), 
				'PAGE_CURRENT' => $arResult['PAGE_CURRENT'], 
				'PAGE_COUNT' => $arResult['PAGE_COUNT'], 
				'PAGINATION' => json_encode(str_replace(["\t","\r","\n"], ["","",""], $arResult['NAV_STRING']), JSON_UNESCAPED_SLASHES), 
			];

			print json_encode($response, JSON_UNESCAPED_SLASHES);

			die();
		}
		else
		{
			$this->IncludeComponentTemplate();
		}
	}
}