<?
require_once($_SERVER['DOCUMENT_ROOT'] . "/bitrix/modules/main/include/prolog_before.php");
header('Content-Type: application/json; charset=utf-8');

use \Bitrix\Main\Service\GeoIp;
$httpClient = new \Bitrix\Main\Web\HttpClient();

$PARAM_1 = $_REQUEST["PARAM_1"];
$PARAM_2 = $_REQUEST["PARAM_2"];
$PARAM_3 = $_REQUEST["PARAM_3"];
$PARAM_4 = $_REQUEST["PARAM_4"];

$HEADERS = apache_request_headers();
$METHOD = $_SERVER['REQUEST_METHOD'];
$REQ = [];

$ORIGINS = [
	'http://localhost:3000',
	'https://evo.quickcode.ru',
	'https://lk-evo.quickcode.ru',
	'https://wow.evoleasing.ru',
	'https://www.evoleasing.ru',
	'https://evoleasing.ru',
	'http://lk.evoleasing.ru',
	'https://lk.evoleasing.ru',
];

$origin = $HEADERS['Origin'] ? $HEADERS['Origin'] : $HEADERS['origin'];
if($origin == "") 
{
	foreach($ORIGINS as $ORIGIN)
	{
		if(strpos($referer, $ORIGIN) !== FALSE) 
		{
			$origin = $ORIGIN;
			break;
		}
	}
}

if(in_array($origin, $ORIGINS))
{
	header('Access-Control-Allow-Origin: ' . $origin);
}

header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Cache-Control, Accept, X-Full-Url");
header('Pragma: no-cache');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Credentials: true');

$arrContextOptions = [
	"ssl" => [
		"verify_peer" => false,
		"verify_peer_name" => false,
	],
];

$secret = "YnFN1EcbB4osQyKx53OoMs0seHcIcoUVv2mCQOleHdn9o07bIniM5TreQNvQtgsQo6zWxsxLNFbSBrywjmerU5VnKZVQD1EGVcO";
$secret_crm = "lk_evolution_the_best_leasing_company_of_the_world_sSOvumhogyAtZydpaITb";

$auth = [];

use Bitrix\Main\Context,
	Bitrix\Main\Type\DateTime,
	Bitrix\Main\Loader,
	Bitrix\Iblock;

include_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/php_interface/classes/tfpdf/tfpdf.php');

class PDF extends tFPDF
{
	function Header()
	{
		$this->Image($_SERVER['DOCUMENT_ROOT']."/images/evo_pdf_header_image.jpg", 120, 10, 80, 8);
		$this->Ln(10);
	}

	function Footer()
	{
		$this->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
		$this->SetY(-30);
		$this->SetFont('DejaVu', '', 5.5);
		$this->Ln(15);
		$this->MultiCell(100, 2, "ООО «ЛК Эволюция»\nИНН/КПП 9724016636/772401001\nр/с 40701810600760000017\nв ПАО «МОСКОВСКИЙ КРЕДИТНЫЙ БАНК»\nк/с 30101810745250000659\nБИК 044525659");
	}
}

function checkRequestIsLocal()
{
	if(!MODE_PRODUCTION)
	{
		return true;
	}

	if(strpos($_SERVER['HTTP_X_FORWARDED_FOR'], SELF_IP) > -1)
	{
		return true;
	}

	return false;
}

function checkRecaptchaRequest($token, $ipAddress)
{
	$c = curl_init();
	curl_setopt($c, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
	curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($c, CURLOPT_TIMEOUT, 30);
	curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($c, CURLOPT_POST, 1);
	curl_setopt($c, CURLOPT_POSTFIELDS, [
		"secret" => RECAPTCHA_SECRET_KEY, 
		"response" => $token, 
		"remoteip" => $ipAddress, 
	]);

	$response = curl_exec($c) or die(curl_error($c));
	curl_close($c);

	$response_decoded = json_decode($response, true);

	return $response_decoded['success'];
}

function getCompaniesForUser($user_id, $except_company_id = null)
{
	if(CModule::IncludeModule('iblock'))
	{
		$filter = [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'PROPERTY_USERS' => $user_id ];
		if($except_company_id !== null)
		{
			$filter['!ID'] = $except_company_id;
		}

		$existed_client_as_user_res = CIBlockElement::GetList([ 'id' => 'desc' ], $filter, false, []);

		$companies = [];

		while ($existed_client_as_user_element = $existed_client_as_user_res->GetNextElement())
		{
			$existed_client_as_user_record = $existed_client_as_user_element->GetFields();
			$existed_client_as_user_record['PROPERTIES'] = $existed_client_as_user_element->GetProperties();
	
			$company = [
				"acc_number" => $existed_client_as_user_record['CODE'], 
				"title" => $existed_client_as_user_record['PROPERTIES']['COMPANY']['~VALUE'], 
				"inn" => $existed_client_as_user_record['PROPERTIES']['INN']['~VALUE'], 
				"kpp" => $existed_client_as_user_record['PROPERTIES']['KPP']['~VALUE'], 
				"ogrn" => $existed_client_as_user_record['PROPERTIES']['OGRN']['~VALUE'], 
				"is_admin" => false, 
			];

			foreach($existed_client_as_user_record['PROPERTIES']['ADMINS']['VALUE'] AS $k => $v)
			{
				if($v == $user_id)
				{
					$company['is_admin'] = true;
				}
			}

			array_push($companies, $company);
		}

		return $companies;
	}

	return [];
}

function getUsersForCompany($code)
{
	if(CModule::IncludeModule('iblock'))
	{
		$company_res = CIBlockElement::GetList([ 'id' => 'desc' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $code ], false, []);

		$users = [];

		while ($company_element = $company_res->GetNextElement())
		{
			$company_record = $company_element->GetFields();
			$company_record['PROPERTIES'] = $company_element->GetProperties();
			$user = [];

			foreach($company_record['PROPERTIES']['USERS']['VALUE'] AS $user_id)
			{
				$user_res = \CUser::GetList(["ID" => "ASC"], false, [ "ID" => $user_id ], []);
				while($user_element = $user_res->Fetch())
				{
					$companies = getCompaniesForUser($user_element['ID']);
					$user = [
						"email" => $user_element['LOGIN'], 
						"name" => $user_element['LAST_NAME'], 
						"last" => $user_element['LAST_LOGIN'], 
						"companies" => $companies, 
						"is_admin" => in_array($user_element['ID'], $company_record['PROPERTIES']['ADMINS']['VALUE']), 
					];

					array_push($users, $user);
				}
			}
		}

		return $users;
	}

	return [];
}

function setCompanyForUser($ID, $REQ, $replace = false)
{
	$user_properties = [
		'COMPANY' => (string)$REQ['org_title'], 
		'INN' => (string)$REQ['inn'], 
		'KPP' => (string)$REQ['kpp'], 
		'OGRN' => (string)$REQ['ogrn'], 
		'ADMINS' => [ $ID ], 
		'USERS' => [ $ID ], 
	];

	$ar_new_client = [
		'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 
		'NAME' => $REQ['org_title'], 
		'CODE' => $REQ['crm_id'], 
		'PROPERTY_VALUES' => $user_properties, 
		'ACTIVE' => 'Y', // активен
	];

	$admins_to_remove = [];

	$new_client = new CIBlockElement;
	if($new_client_id = $new_client->Add($ar_new_client))
	{
	}
	else 
	{
		$existed_client_res = CIBlockElement::GetList([ 'id' => 'desc' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $REQ['crm_id'] ], false, []);
		while ($existed_client_element = $existed_client_res->GetNextElement())
		{
			$existed_client_record = $existed_client_element->GetFields();
			$existed_client_record['PROPERTIES'] = $existed_client_element->GetProperties();

			if($replace)
			{
				$admins = [];
				$users = [];

				$admins_to_remove = $existed_client_record['PROPERTIES']['ADMINS']['VALUE'];
			}
			else
			{
				$admins = $existed_client_record['PROPERTIES']['ADMINS']['VALUE'];
				$users = $existed_client_record['PROPERTIES']['USERS']['VALUE'];
			}

			array_push($admins, $ID);
			array_push($users, $ID);

			$admins = array_unique($admins);
			$users = array_unique($users);

			$updated_fields = [
				'PROPERTY_VALUES' => [
					'ADMINS' => $admins, 
					'USERS' => $users, 
				]
			];

			CIBlockElement::SetPropertyValuesEx($existed_client_record['ID'], IBLOCK_ID_CLIENTS, [ 'ADMINS' => $admins, 'USERS' => $users, ]);

			foreach($admins_to_remove AS $admin_to_remove_id)
			{
				$another_user_companies = getCompaniesForUser($admin_to_remove_id, $existed_client_record['ID']);

				if(gettype($another_user_companies) === "array" && count($another_user_companies) === 0)
				{
					\CUser::Delete($admin_to_remove_id);
				}
			}
		}
	}
}

if($_SERVER['REMOTE_USER'] && strpos($_SERVER['REMOTE_USER'], "Bearer") > -1)
{
	$token = str_replace("Bearer ", "", $_SERVER['REMOTE_USER']);

	try
	{
		$auth = (array) \Bitrix\Main\Web\JWT::decode($token, $secret, ["HS256"]);
	}
	catch(\Exception $e)
	{
		print json_encode([
			"status" => "error", 
			"error" => "wrong_jwt", 
			"message" => $e->getMessage(), 
		]);
		die();
	}
}

switch ($METHOD)
{
	case 'GET':
	{
		$REQ = $_GET;
	}
	break;

	case 'POST':
	{
		if($_SERVER['HTTP_ACCEPT'] == 'application/json' || strstr($_SERVER['CONTENT_TYPE'], 'application/json') !== false)
		{
			$BODY = json_decode(file_get_contents('php://input'), true);
		}
		else
		{
			$BODY = $_POST;
		}

		if(is_array($BODY))
		{
			$REQ = array_merge($BODY, $_REQUEST);
		}
		else
		{
			$REQ = $_REQUEST;
		}
	}
	break;

	case 'OPTIONS':
	{
		die();
	}
	break;

	default:
	{
		die();
	}
	break;
}

switch($PARAM_1) 
{
	case "user":
	{
		switch($PARAM_2)
		{
			case "registration":
			{
				if($auth['username'] !== 'crm') { header('HTTP/1.0 401 Unauthorized'); print json_encode(["status" => "error", "error" => "unauthorized", "message" => "Unauthorized"]); die(); }

				$email = $REQ['email'];
				$phone = (int)$REQ['phone'];
				$password = $REQ['password'];

				if(empty($email) && empty($phone))
				{
					header('HTTP/1.0 400 Bad Request'); print json_encode(["status" => "error", "error" => "empty email and phone", "message" => "Bad Request"]); die();
				}

				$real_email = true;
				if(empty($email))
				{
					$email = $phone."@evoleasing.ru";
					$real_email = false;
					$password = md5($email);
				}

				$profile = [
					"XML_ID" => $REQ['crm_id'], 
					"LOGIN" => $email, 
					"NAME" => $REQ['firstname'], 
					"SECOND_NAME" => $REQ['secondname'], 
					"LAST_NAME" => $REQ['lastname'], 
					"EMAIL" => $email, 
					"UF_ORG_TITLE" => (string)$REQ['org_title'], 
					"UF_INN" => (string)$REQ['inn'], 
					"UF_KPP" => (string)$REQ['kpp'], 
					"UF_OGRN" => (string)$REQ['ogrn'], 
					"UF_PHONE_NUMBER" => (int)$REQ['phone'], 
				];

				if(!$real_email)
				{
					$profile["UF_IS_VALID_EMAIL"] = "нет";
				}

				$user_registered_id = null;
				$company_registered_id = null;

				$existed_users_res = \CUser::GetList(["ID" => "ASC"], false, [ "LOGIN" => $email ], []);
				while($existed_user = $existed_users_res->Fetch())
				{
					$user_registered_id = $existed_user["ID"];
				}

				$existed_client_as_admin_res = CIBlockElement::GetList([ 'ID' => 'ASC' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $REQ['crm_id'] ], false, []);
				while ($existed_client_as_admin_element = $existed_client_as_admin_res->GetNextElement())
				{
					$existed_client_as_admin_record = $existed_client_as_admin_element->GetFields();
					$company_registered_id = $existed_client_as_admin_record['ID'];
				}

				if($user_registered_id !== null)
				{
					//user exists

					if($company_registered_id === null)
					{
						//new company for user
						setCompanyForUser($user_registered_id, $REQ);

						$company_message = "Вам предоставлен доступ к Личному кабинету следующей организации:<br><br>\n\n";
						$company_message .= $REQ['org_title'].", ИНН: ".$REQ['inn']."<br>\n";

						if(SEND_EMAIL_REGISTRATION_JOIN && $real_email)
						{
							\Bitrix\Main\Mail\Event::send([
								"EVENT_NAME" => "CLIENT_USER_INVITE", 
								"LID" => "s1", 
								"C_FIELDS" => Array(
									"EMAIL" => $email, 
									"COMPANIES" => $company_message, 
								)
							]);
						}

						$user_properties = [
							'COMPANY' => $REQ['org_title'], 
							'INN' => (string)$REQ['inn'], 
							'KPP' => (string)$REQ['kpp'], 
							'OGRN' => (string)$REQ['ogrn'], 
							'ADMINS' => [ $ID ], 
							'USERS' => [ $ID ], 
						];

						$ar_new_client = [
							'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 
							'NAME' => $REQ['org_title'], 
							'CODE' => $REQ['crm_id'], 
							'PROPERTY_VALUES' => $user_properties, 
							'ACTIVE' => 'Y', // активен
						];

						$new_client = new CIBlockElement;
						if($new_client_id = $new_client->Add($ar_new_client))
						{
						}
						else 
						{
							$existed_client_res = CIBlockElement::GetList([ 'id' => 'desc' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $REQ['crm_id'] ], false, []);
							while ($existed_client_element = $existed_client_res->GetNextElement())
							{
								$existed_client_record = $existed_client_element->GetFields();
								$existed_client_record['PROPERTIES'] = $existed_client_element->GetProperties();

								$admins = $existed_client_record['PROPERTIES']['ADMINS']['VALUE'];
								$users = $existed_client_record['PROPERTIES']['USERS']['VALUE'];

								array_push($admins, $ID);
								array_push($users, $ID);

								$admins = array_unique($admins);
								$users = array_unique($users);

								$updated_fields = [
									'PROPERTY_VALUES' => [
										'ADMINS' => $admins, 
										'USERS' => $users, 
									]
								];

								CIBlockElement::SetPropertyValuesEx($existed_client_record['ID'], IBLOCK_ID_CLIENTS, [ 'ADMINS' => $admins, 'USERS' => $users, ]);
							}
						}

						print json_encode([
							"status" => "success"
						]);

						die();
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "company_already_registered", 
							"message" => "Company already registered", 
						]);

						die();
					}
				}
				else
				{
					if($company_registered_id === null)
					{
						$user = new \CUser;

						$profile["PASSWORD"] = $password;
						$profile["CONFIRM_PASSWORD"] = $password;

						$ID = $user->Add($profile);
						if (intval($ID) > 0)
						{
							if(SEND_EMAIL_REGISTRATION_CREATE && $real_email)
							{
								\Bitrix\Main\Mail\Event::send([
									"EVENT_NAME" => "USER_INFO", 
									"LID" => "s1", 
									"C_FIELDS" => Array(
										"EMAIL" => $email, 
										"ORG_NAME" => $REQ['org_title'], 
										"LOGIN" => $email, 
										"PASS" => $password, 
									)
								]);
							}

							//new user & new company
							setCompanyForUser($ID, $REQ);

							print json_encode([
								"status" => "success"
							]);

							die();
						}
						else
						{
							$error = $user->LAST_ERROR;
							//echo "<pre>".print_r($arFields, true)."</pre>";
							//echo $error;

							print json_encode([
								"status" => "error", 
								"error" => "wrong_payload", 
								"message" => $error, 
							]);

							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "company_already_registered", 
							"message" => "Company already registered", 
						]);

						die();
					}
				}

				die();
			}
			break;

			case "update":
			{
				if($auth['username'] !== 'crm') { header('HTTP/1.0 401 Unauthorized'); print json_encode(["status" => "error", "error" => "unauthorized", "message" => "Unauthorized"]); die(); }

				$profile = [
					"XML_ID" => $REQ['crm_id'], 
					"LOGIN" => $REQ['email'], 
					"NAME" => $REQ['firstname'], 
					"SECOND_NAME" => $REQ['secondname'], 
					"LAST_NAME" => $REQ['lastname'], 
					"EMAIL" => $REQ['email'], 
					"UF_ORG_TITLE" => (string)$REQ['org_title'], 
					"UF_INN" => (string)$REQ['inn'], 
					"UF_KPP" => (string)$REQ['kpp'], 
					"UF_OGRN" => (string)$REQ['ogrn'], 
					"UF_PHONE_NUMBER" => (int)$REQ['phone'], 
				];

				$user_registered = null;
				$company_registered_id = null;
				$company_registered = null;

				$existed_users_res = \CUser::GetList(["ID" => "ASC"], false, [ "LOGIN" => $REQ['email'] ], []);
				while($existed_user = $existed_users_res->Fetch())
				{
					$user_registered = $existed_user['ID'];
				}

				$existed_client_as_admin_res = CIBlockElement::GetList([ 'ID' => 'ASC' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $REQ['crm_id'] ], false, []);
				while ($existed_client_as_admin_element = $existed_client_as_admin_res->GetNextElement())
				{
					$existed_client_as_admin_record = $existed_client_as_admin_element->GetFields();
					$company_registered_id = $existed_client_as_admin_record['ID'];
				}

				if($user_registered !== null)
				{
					// user exists

					if($company_registered_id !== null)
					{
						//existed company

						$profile["PASSWORD"] = $REQ['password'];
						$profile["CONFIRM_PASSWORD"] = $REQ['password'];

						$user = new \CUser;
						$user->Update($user_registered, $profile);

						if(SEND_EMAIL_REGISTRATION_UPDATE)
						{
							\Bitrix\Main\Mail\Event::send([
								"EVENT_NAME" => "USER_INFO",
								"LID" => "s1",
								"C_FIELDS" => Array(
									"EMAIL" => $REQ['email'],
									"ORG_NAME" => (string)$REQ['org_title'],
									"LOGIN" => $REQ['email'],
									"PASS" => $REQ['password'],
								)
							]);
						}

						print json_encode([
							"status" => "success"
						]);

						die();
					}
					else
					{
						//new company

						print json_encode([
							"status" => "error", 
							"error" => "no_company_for_update", 
							"message" => "No company for update", 
						]);

						die();
					}
				}
				else
				{
					// new user

					if($company_registered_id !== null)
					{
						//existed company

						$profile["PASSWORD"] = $REQ['password'];
						$profile["CONFIRM_PASSWORD"] = $REQ['password'];

						$user = new \CUser;
						$ID = $user->Add($profile);

						if (intval($ID) > 0)
						{
							//new user & new company
							setCompanyForUser($ID, $REQ, true);

							if(SEND_EMAIL_REGISTRATION_COMPANY_NEW_USER)
							{
								\Bitrix\Main\Mail\Event::send([
									"EVENT_NAME" => "USER_INFO", 
									"LID" => "s1", 
									"C_FIELDS" => Array(
										"EMAIL" => $REQ['email'], 
										"ORG_NAME" => $REQ['org_title'], 
										"LOGIN" => $REQ['email'], 
										"PASS" => $REQ['password'], 
									)
								]);
							}

							print json_encode([
								"status" => "success"
							]);
	
							die();	
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_payload", 
								"message" => $user->LAST_ERROR, 
							]);

							die();
						}
					}
					else
					{
						//no company

						print json_encode([
							"status" => "error", 
							"error" => "no_company_for_update", 
							"message" => "No company for update", 
						]);

						die();
					}
				}
			}
			break;

			case "check":
			{
				if(CModule::IncludeModule('iblock'))
				{
					if(checkRequestIsLocal())
					{
						try
						{
							$user_registered = false;
							$ar_user;

							$existed_accounts = [];
							$auth = (array) \Bitrix\Main\Web\JWT::decode($REQ['token'], $secret_crm, ["HS256"]);

							$default_admin_id;

							$existed_client_as_admin_res = CIBlockElement::GetList([ 'ID' => 'ASC' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $auth['acc_number'] ], false, []);
							while ($existed_client_as_admin_element = $existed_client_as_admin_res->GetNextElement())
							{
								$existed_client_as_admin_record = $existed_client_as_admin_element->GetFields();
								$existed_client_as_admin_record['PROPERTIES'] = $existed_client_as_admin_element->GetProperties();
								$default_admin_id = $existed_client_as_admin_record['PROPERTIES']['ADMINS']['VALUE'][0];
								$user_registered = true;
							}

							$existed_users_res = \CUser::GetList(["ID" => "ASC"], false, [ "ID" => $default_admin_id ], []);
							while($existed_user = $existed_users_res->Fetch())
							{
								$rs_user = \CUser::GetByLogin($existed_user['LOGIN']);
								$ar_user = $rs_user->Fetch();

								array_push($existed_accounts, $existed_user['XML_ID']);
							}

							if(isset($REQ['filter']))
							{
								if(!in_array($auth['acc_number'], $existed_accounts))
								{
									print json_encode([
										"status" => "error", 
										"error" => "access_denied", 
									]);	
									die();	
								}
							}

							if($user_registered)
							{
								$companies = getCompaniesForUser($ar_user['ID']);
								$company_data = [
									"inn" => $companies[0]['inn'], 
									"kpp" => $companies[0]['kpp'], 
									"ogrn" => $companies[0]['ogrn'], 
									"title" => $companies[0]['title'], 
								];

								$user_data = [
									"email" => $ar_user['LOGIN'], 
									"name" => $ar_user['NAME'], 
									"secondname" => $ar_user['SECOND_NAME'], 
									"lastname" => $ar_user['LAST_NAME'], 
									"phone" => $ar_user['UF_PHONE_NUMBER'], 
									"phone_verified" => $ar_user['UF_PHONE_VERIFIED'], 
									"is_admin" => $companies[0]['is_admin'], 
									"valid_email" => $ar_user['UF_IS_VALID_EMAIL'], 
								];

								print json_encode([
									"status" => "success", 
									"user" => $user_data, 
									"company" => $company_data, 
									"companies" => $companies, 
									"token" => \Bitrix\Main\Web\JWT::encode([ "acc_number" => $auth['acc_number'], "is_admin" => $companies[0]['is_admin'], "login" => $ar_user['LOGIN'], "companies" => $companies ], $secret, 'HS256', null, null), 
								]);
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "unknown account", 
								]);
							}
							die();
						}
						catch(\Exception $e)
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_jwt", 
								"message" => $e->getMessage(), 
							]);
							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_source", 
							"error" => "Wrong source", 
						]);
					}
				}
			}
			break;

			case "check":
			{
				if(CModule::IncludeModule('iblock'))
				{
					if(checkRequestIsLocal())
					{
						try
						{
							$user_registered = false;
							$ar_user;

							$existed_accounts = [];
							$auth = (array) \Bitrix\Main\Web\JWT::decode($REQ['token'], $secret_crm, ["HS256"]);

							$default_admin_id;

							$existed_client_as_admin_res = CIBlockElement::GetList([ 'ID' => 'ASC' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $auth['acc_number'] ], false, []);
							while ($existed_client_as_admin_element = $existed_client_as_admin_res->GetNextElement())
							{
								$existed_client_as_admin_record = $existed_client_as_admin_element->GetFields();
								$existed_client_as_admin_record['PROPERTIES'] = $existed_client_as_admin_element->GetProperties();
								$default_admin_id = $existed_client_as_admin_record['PROPERTIES']['ADMINS']['VALUE'][0];
								$user_registered = true;
							}

							$existed_users_res = \CUser::GetList(["ID" => "ASC"], false, [ "ID" => $default_admin_id ], []);
							while($existed_user = $existed_users_res->Fetch())
							{
								$rs_user = \CUser::GetByLogin($existed_user['LOGIN']);
								$ar_user = $rs_user->Fetch();

								array_push($existed_accounts, $existed_user['XML_ID']);
							}

							if(isset($REQ['filter']))
							{
								if(!in_array($auth['acc_number'], $existed_accounts))
								{
									print json_encode([
										"status" => "error", 
										"error" => "access_denied", 
									]);	
									die();	
								}
							}

							if($user_registered)
							{
								$user_data = [
									"email" => $ar_user['LOGIN'], 
									"name" => $ar_user['NAME'], 
									"secondname" => $ar_user['SECOND_NAME'], 
									"lastname" => $ar_user['LAST_NAME'], 
									"phone" => $ar_user['UF_PHONE_NUMBER'], 
									"phone_verified" => $ar_user['UF_PHONE_VERIFIED'], 
									"valid_email" => $ar_user['UF_IS_VALID_EMAIL'], 
								];

								$companies = getCompaniesForUser($ar_user['ID']);
								$company_data = [
									"inn" => $companies[0]['inn'], 
									"kpp" => $companies[0]['kpp'], 
									"ogrn" => $companies[0]['ogrn'], 
									"title" => $companies[0]['title'], 
								];

								print json_encode([
									"status" => "success", 
									"user" => $user_data, 
									"company" => $company_data, 
									"companies" => $companies, 
									"token" => \Bitrix\Main\Web\JWT::encode([ "acc_number" => $auth['acc_number'], "is_admin" => $companies[0]['is_admin'], "login" => $ar_user['LOGIN'], "companies" => $companies ], $secret, 'HS256', null, null), 
								]);
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "unknown account", 
								]);
							}
							die();
						}
						catch(\Exception $e)
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_jwt", 
								"message" => $e->getMessage(), 
							]);
							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_source", 
							"error" => "Wrong source", 
						]);
					}
				}
			}
			break;

			default:
			{
				print json_encode([
					"status" => "error", 
					"error" => "wrong_user_uri", 
					"message" => "Empty user URI", 
				]);

				die();
			}
			break;
		}
	}
	break;

	case "admin":
	{
		switch($PARAM_2)
		{
			case "users":
			{
				if(CModule::IncludeModule('iblock'))
				{
					if(checkRequestIsLocal())
					{
						try
						{
							$user_registered = false;
							$ar_user;

							$existed_accounts = [];
							$auth = (array) \Bitrix\Main\Web\JWT::decode($REQ['token'], $secret_crm, ["HS256"]);

							$users = getUsersForCompany($auth['acc_number']);
							print json_encode([
								"status" => "success", 
								"users" => $users, 
							]);
						}
						catch(\Exception $e)
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_jwt", 
								"message" => $e->getMessage(), 
							]);
							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_source", 
							"error" => "Wrong source", 
						]);
					}
				}				
			}
			break;

			case "invite":
			{
				if(CModule::IncludeModule('iblock'))
				{
					if(checkRequestIsLocal())
					{
						try
						{
							$auth = (array) \Bitrix\Main\Web\JWT::decode($REQ['token'], $secret_crm, ["HS256"]);

							$rs_user = \CUser::GetByLogin($auth['email']);
							$ar_user = $rs_user->Fetch();

							$existed_user = false;
							$user_id_to_add = null;

							if(is_array($ar_user))
							{
								//existed user
								$existed_user = true;
								$user_id_to_add = intval($ar_user['ID']);

								$user = new CUser;
								$user->Update($user_id_to_add, [ "BLOCKED" => "N" ]);
							}
							else
							{
								//new user
								$password = randString(8);

								$user = new \CUser;
								$profile = [
									"LOGIN" => $auth['email'], 
									"LAST_NAME" => $auth['name'], 
									"PASSWORD" => $password, 
									"CONFIRM_PASSWORD" => $password, 
									"EMAIL" => $auth['email'], 
								];

								$ID = $user->Add($profile);
								if (intval($ID) > 0)
								{
									$user_id_to_add = intval($ID);
								}
							}

							//add user to company (companies)
							$companies_list_message = "Список компаний к которым Вам предоставлен доступ:<br><br>\n\n";
							foreach($auth['companies'] AS $company_acc_number)
							{
								$existed_client_res = CIBlockElement::GetList([ 'id' => 'desc' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $company_acc_number ], false, []);

								while ($existed_client_element = $existed_client_res->GetNextElement())
								{
									$existed_client_record = $existed_client_element->GetFields();
									$existed_client_record['PROPERTIES'] = $existed_client_element->GetProperties();

									$companies_list_message .= $existed_client_record['NAME'].", ИНН: ".$existed_client_record['PROPERTIES']['INN']['VALUE']."<br>\n";

									$users = $existed_client_record['PROPERTIES']['USERS']['VALUE'];
									array_push($users, $user_id_to_add);

									$users = array_unique($users);

									CIBlockElement::SetPropertyValuesEx($existed_client_record['ID'], IBLOCK_ID_CLIENTS, [ 'USERS' => $users, ]);
								}
							}

							if($existed_user)
							{
								if(SEND_EMAIL_REGISTRATION_COMPANY_INVITE)
								{
									\Bitrix\Main\Mail\Event::send([
										"EVENT_NAME" => "CLIENT_USER_INVITE", 
										"LID" => "s1", 
										"C_FIELDS" => Array(
											"EMAIL" => $auth['email'], 
											"COMPANIES" => $companies_list_message, 
										)
									]);
								}
							}
							else
							{
								if(SEND_EMAIL_REGISTRATION_COMPANY_INVITE_NEW_USER)
								{
									\Bitrix\Main\Mail\Event::send([
										"EVENT_NAME" => "CLIENT_NEW_USER_INVITE", 
										"LID" => "s1", 
										"C_FIELDS" => Array(
											"EMAIL" => $auth['email'], 
											"PASSWORD" => $password, 
											"COMPANIES" => $companies_list_message, 
										)
									]);
								}
							}

							print json_encode([
								"status" => "success", 
							]);
						}
						catch(\Exception $e)
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_jwt", 
								"message" => $e->getMessage(), 
							]);
							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_source", 
							"error" => "Wrong source", 
						]);
					}
				}
			}
			break;

			case "remove":
			{
				if(CModule::IncludeModule('iblock'))
				{
					if(checkRequestIsLocal())
					{
						try
						{
							$auth = (array) \Bitrix\Main\Web\JWT::decode($REQ['token'], $secret_crm, ["HS256"]);

							$existed_users = [];
							$removed_users = [];

							foreach($auth['emails'] AS $email)
							{
								$rs_user = \CUser::GetByLogin($email);
								$ar_user = $rs_user->Fetch();

								$existed_users[$ar_user['ID']] = $email;
							}

							$existed_client_res = CIBlockElement::GetList([ 'id' => 'desc' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $auth['acc_number'] ], false, []);

							$users = [];
							while ($existed_client_element = $existed_client_res->GetNextElement())
							{
								$existed_client_record = $existed_client_element->GetFields();
								$existed_client_record['PROPERTIES'] = $existed_client_element->GetProperties();

								$company_users = $existed_client_record['PROPERTIES']['USERS']['VALUE'];

								$company_new_users = [];
								foreach($company_users AS $company_user_id)
								{
									if(!isset($existed_users[$company_user_id]))
									{
										array_push($company_new_users, $company_user_id);
									}
									else
									{
										array_push($removed_users, $company_user_id);
									}
								}

								$company_new_users = array_unique($company_new_users);

								CIBlockElement::SetPropertyValuesEx($existed_client_record['ID'], IBLOCK_ID_CLIENTS, [ 'USERS' => $company_new_users, ]);
							}

							foreach($removed_users AS $removed_user_id)
							{
								$user_companies = getCompaniesForUser($removed_user_id);

								if(gettype($user_companies) === "array" && count($user_companies) === 0)
								{
									\CUser::Delete($removed_user_id);
								}
							}

							print json_encode([
								"status" => "success", 
							]);

							die();
						}
						catch(\Exception $e)
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_jwt", 
								"message" => $e->getMessage(), 
							]);
							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_source", 
							"error" => "Wrong source", 
						]);
					}
				}
			}
			break;

			default:
			{
				print json_encode([
					"status" => "error", 
					"error" => "wrong_admin_uri", 
					"message" => "Empty admin URI", 
				]);

				die();
			}
			break;
		}
	}

	case "catalog":
	{
		switch($PARAM_2)
		{
			case "count":
			{
				if(CModule::IncludeModule('iblock'))
				{
					define("USED", filter_var($REQ['USED'], FILTER_VALIDATE_BOOLEAN));
					$filter = [ "ACTIVE" => "Y", ];

					if(!empty($REQ['PROGRAM'])) { $filter['PROPERTY_LEASING_PROGRAMS'] = $REQ['PROGRAM']; }

					if(!empty($REQ['BRAND_ID'])) { $filter["PROPERTY_BRAND"] = $REQ['BRAND_ID']; }
					if(!empty($REQ['MODEL_ID'])) { $filter["PROPERTY_MODEL"] = $REQ['MODEL_ID']; }
					if(!empty($REQ['MODIFICATION'])) { $filter["PROPERTY_MODIFICATION"] = $REQ['MODIFICATION']; }

					if(!empty($REQ['GEAR'])) { $filter["PROPERTY_GEAR"] = $REQ['GEAR']; }
					if(!empty($REQ['DRIVE'])) { $filter["PROPERTY_DRIVE"] = $REQ['DRIVE']; }
					if(!empty($REQ['BODY'])) { $filter["PROPERTY_BODY"] = $REQ['BODY']; }
					if(!empty($REQ['ENGINE_FUEL'])) { $filter["PROPERTY_ENGINE_FUEL"] = $REQ['ENGINE_FUEL']; }

					if(!empty($REQ['ENGINE_VOLUME_FROM']) || !empty($REQ['ENGINE_VOLUME_TO']))
					{
						$filter['><PROPERTY_ENGINE_VOLUME'] = [ !empty($REQ['ENGINE_VOLUME_FROM']) ? $REQ['ENGINE_VOLUME_FROM'] : 0, !empty($REQ['ENGINE_VOLUME_TO']) ? $REQ['ENGINE_VOLUME_TO'] : 10000 ];
					}

					$total = CIBlockElement::GetList([ "SORT" => "ASC", "NAME" => "ASC" ], array_merge([ "IBLOCK_ID" => USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW ], $filter), [], []);

					$gear = [];
					$drive = [];
					$body = [];
					$fuel = [];
					$volume = [];

					$filter_props_ids = [];

					if(empty($REQ['GEAR'])) { array_push($filter_props_ids, 7); }
					if(empty($REQ['DRIVE'])) { array_push($filter_props_ids, 8); }
					if(empty($REQ['BODY'])) { array_push($filter_props_ids, 9); }
					if(empty($REQ['ENGINE_FUEL'])) { array_push($filter_props_ids, 12); }
					if(empty($REQ['ENGINE_VOLUME_FROM']) && empty($REQ['ENGINE_VOLUME_TO'])) { array_push($filter_props_ids, 11); }

					$iterator = CIBlockElement::GetPropertyValues( 1, $filter, true, [ 'ID' => [ 7, 8, 9, 11, 12 ] ] );
					while ($row = $iterator->Fetch())
					{
						if(empty($REQ['GEAR'])) { array_push($gear, $row[7]); }
						if(empty($REQ['DRIVE'])) { array_push($drive, $row[8]); }
						if(empty($REQ['BODY'])) { array_push($body, $row[9]); }
						if(empty($REQ['ENGINE_FUEL'])) { array_push($fuel, $row[12]); }
						if(empty($REQ['ENGINE_VOLUME_FROM']) && empty($REQ['ENGINE_VOLUME_TO'])) { array_push($volume, $row[11]); }
					}

					$gear = array_values(array_unique($gear));
					$drive = array_values(array_unique($drive));
					$body = array_values(array_unique($body));
					$fuel = array_values(array_unique($fuel));
					$volume = array_values(array_unique($volume));
					sort($volume);

					$volumes = [];
					$min = floor($volume[0] / 100) * 100;
					$max = (floor($volume[count($volume)-1] / 100) + 1) * 100;

					while($min <= $max)
					{
						if($min > 0)
						{
							array_push($volumes, $min);
						}

						$min = $min + 100;
					}

					$result = [
						"total" => $total, 
					];

					if(empty($REQ['GEAR'])) { $result["gears"] = $gear; }
					if(empty($REQ['DRIVE'])) { $result["drives"] = $drive; }
					if(empty($REQ['BODY'])) { $result["bodies"] = $body; }
					if(empty($REQ['ENGINE_FUEL'])) { $result["engine_fuels"] = $fuel; }
					if(empty($REQ['ENGINE_VOLUME_FROM']) && empty($REQ['ENGINE_VOLUME_TO'])) { $result["engine_volumes"] = $volumes; }

					print json_encode($result);
				}
			}
			break;

			case "brands":
			{
				if(CModule::IncludeModule('iblock'))
				{
					define("USED", filter_var($REQ['USED'], FILTER_VALIDATE_BOOLEAN));

					$brands = [];
					$brands_res = CIBlockElement::GetList(["NAME" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => USED ? IBLOCK_ID_BRANDS_USED : IBLOCK_ID_BRANDS ], false, []);
					while ($brands_ob_element = $brands_res->GetNextElement())
					{
						$brands_ar_res = $brands_ob_element->GetFields();
						$brands_ar_res['PROPERTIES'] = $brands_ob_element->GetProperties();

						$brands[] = [
							"ID" => $brands_ar_res['ID'], 
							"NAME" => $brands_ar_res['NAME'], 
							"UID" => $brands_ar_res['PROPERTIES']['UID']['VALUE'], 
							"CODE" => $brands_ar_res['CODE'], 
						];
					}

					print json_encode([
						"brands" => $brands, 
					]);
				}
			}
			break;

			case "models":
			{
				if(CModule::IncludeModule('iblock'))
				{
					define("USED", filter_var($REQ['USED'], FILTER_VALIDATE_BOOLEAN));

					$models = [];
					$models_res = CIBlockElement::GetList(["NAME" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => USED ? IBLOCK_ID_MODELS_USED : IBLOCK_ID_MODELS, "PROPERTY_BRAND_UID" => $REQ['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();

						$models[] = [
							"ID" => $models_ar_res['ID'], 
							"NAME" => $models_ar_res['NAME'], 
							"UID" => $models_ar_res['PROPERTIES']['UID']['VALUE'], 
							"CODE" => $models_ar_res['CODE'], 
						];
					}

					print json_encode([
						"models" => $models, 
					]);
				}
			}
			break;

			case "modifications":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$modifications = [];
					$modifications_res = CIBlockElement::GetList(["NAME" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_MODIFICATIONS, "PROPERTY_MODEL_UID" => $REQ['MODEL_UID']], false, []);
					while ($modifications_ob_element = $modifications_res->GetNextElement())
					{
						$modifications_ar_res = $modifications_ob_element->GetFields();
						$modifications_ar_res['PROPERTIES'] = $modifications_ob_element->GetProperties();

						$modifications[] = [
							"NAME" => $modifications_ar_res['PROPERTIES']['TITLE']['VALUE'], 
							"ID" => $modifications_ar_res['ID'], 
						];
					}

					print json_encode([
						"modifications" => $modifications, 
					]);
				}
			}
			break;

			case "parameters":
			{
				if(CModule::IncludeModule('iblock'))
				{
					define("USED", filter_var($REQ['USED'], FILTER_VALIDATE_BOOLEAN));
					$filter = [ "ACTIVE" => "Y", ];

					if(!empty($REQ['PROGRAM'])) { $filter['PROPERTY_LEASING_PROGRAMS'] = $REQ['PROGRAM']; }

					if(!empty($REQ['BRAND_ID'])) { $filter["PROPERTY_BRAND"] = $REQ['BRAND_ID']; }
					if(!empty($REQ['MODEL_ID'])) { $filter["PROPERTY_MODEL"] = $REQ['MODEL_ID']; }
					if(!empty($REQ['MODIFICATION'])) { $filter["PROPERTY_MODIFICATION"] = $REQ['MODIFICATION']; }

					if(!empty($REQ['GEAR'])) { $filter["PROPERTY_GEAR"] = $REQ['GEAR']; }
					if(!empty($REQ['DRIVE'])) { $filter["PROPERTY_DRIVE"] = $REQ['DRIVE']; }
					if(!empty($REQ['BODY'])) { $filter["PROPERTY_BODY"] = $REQ['BODY']; }
					if(!empty($REQ['ENGINE_FUEL'])) { $filter["PROPERTY_ENGINE_FUEL"] = $REQ['ENGINE_FUEL']; }

					if(!empty($REQ['VEHICLE_TYPE'])) { $filter["PROPERTY_VEHICLE_TYPE"] = $REQ['VEHICLE_TYPE']; }
					if(!empty($REQ['VEHICLE_SUBTYPE'])) { $filter["PROPERTY_VEHICLE_SUBTYPE"] = $REQ['VEHICLE_SUBTYPE']; }
					if(!empty($REQ['PARKING_CITY'])) { $filter["PROPERTY_PARKING_CITY"] = $REQ['PARKING_CITY']; }

					if(!empty($REQ['ENGINE_VOLUME_FROM']) || !empty($REQ['ENGINE_VOLUME_TO']))
					{
						$filter['><PROPERTY_ENGINE_VOLUME'] = [ !empty($REQ['ENGINE_VOLUME_FROM']) ? $REQ['ENGINE_VOLUME_FROM'] : 0, !empty($REQ['ENGINE_VOLUME_TO']) ? $REQ['ENGINE_VOLUME_TO'] : 10000 ];
					}

					if(!empty($REQ['YEAR_FROM']) || !empty($REQ['YEAR_TO']))
					{
						$filter['><PROPERTY_YEAR'] = [ !empty($REQ['YEAR_FROM']) ? $REQ['YEAR_FROM'] : 2000, !empty($REQ['YEAR_TO']) ? $REQ['YEAR_TO'] : date("YYYY") ];
					}

					if(!empty($REQ['MILEAGE_FROM']) || !empty($REQ['MILEAGE_TO']))
					{
						$filter['><PROPERTY_MILEAGE'] = [ !empty($REQ['MILEAGE_FROM']) ? $REQ['MILEAGE_FROM'] : 0, !empty($REQ['MILEAGE_TO']) ? $REQ['MILEAGE_TO'] : 10000000 ];
					}

					$total = CIBlockElement::GetList([ "SORT" => "ASC", "NAME" => "ASC" ], array_merge([ "IBLOCK_ID" => USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW ], $filter), [], []);
					$result = [
						"total" => $total, 
						"possible_volumes" => [], 
					];

					$vehicle_types = [];
					$vehicle_subtypes = [];
					$cities = [];

					$brands = [];
					$models = [];
					$modifications = [];

					$gears = [];
					$drives = [];
					$bodies = [];
					$engine_fuels = [];
					$engine_volumes = [];

					$filter_props_ids = [];

					$years = [];
					$mileages = [];

					array_push($filter_props_ids, 3);
					if(!empty($REQ['BRAND_ID'])) { array_push($filter_props_ids, 4); }
					array_push($filter_props_ids, 7);
					array_push($filter_props_ids, 8);
					array_push($filter_props_ids, 9);
					array_push($filter_props_ids, 12);
					//if(empty($REQ['ENGINE_VOLUME_FROM']) || empty($REQ['ENGINE_VOLUME_TO'])) { array_push($filter_props_ids, 11); }

					$result['filter'] = $filter;

					if(USED)
					{
						//filter for types
						$filter_vehicle_types = $filter;
						unset($filter_vehicle_types['PROPERTY_VEHICLE_TYPE']);

						$vehicle_types_list = [];
						$iterator = CIBlockElement::GetPropertyValues( IBLOCK_ID_CATALOG_CARS_USED, $filter_vehicle_types, true, [ 'ID' => [ PROPERTY_ID_CATALOG_CARS_USED_VEHICLE_TYPE ] ] );
						while ($row = $iterator->Fetch())
						{
							array_push($vehicle_types_list, $row[ PROPERTY_ID_CATALOG_CARS_USED_VEHICLE_TYPE ]);
						}

						$vehicle_types_list = array_values(array_unique($vehicle_types_list));

						$types_asc = [];
						$types_asc_res = CIBlockElement::GetList([ "SORT" => "ASC", "NAME" => "ASC" ], [ "IBLOCK_ID" => IBLOCK_ID_USED_TYPES ], false, []);
						while ($type_asc_ob_element = $types_asc_res->GetNextElement())
						{
							$type_asc_ar_res = $type_asc_ob_element->GetFields();
							if(in_array($type_asc_ar_res['NAME'], $vehicle_types_list))
							{
								array_push($vehicle_types, $type_asc_ar_res['NAME']);
							}
						}

						if(!empty($REQ['VEHICLE_TYPE']))
						{
							//filter for subtypes
							$filter_vehicle_subtypes = $filter;
							unset($filter_vehicle_subtypes['PROPERTY_VEHICLE_SUBTYPE']);

							$vehicle_type = null;
							$type_res = CIBlockElement::GetList([], [ "IBLOCK_ID" => IBLOCK_ID_USED_TYPES, "NAME" => $REQ['VEHICLE_TYPE'] ], false, []);
							while ($type_ob_element = $type_res->GetNextElement())
							{
								$type_ar_res = $type_ob_element->GetFields();
								$vehicle_type = $type_ar_res['ID'];
							}

							$iterator = CIBlockElement::GetPropertyValues( IBLOCK_ID_CATALOG_CARS_USED, array_merge($filter_vehicle_subtypes, [ "VEHICLE_TYPE" => $vehicle_type ]), true, [ 'ID' => [ PROPERTY_ID_CATALOG_CARS_USED_VEHICLE_SUBTYPE ] ] );
							while ($row = $iterator->Fetch())
							{
								array_push($vehicle_subtypes, $row[ PROPERTY_ID_CATALOG_CARS_USED_VEHICLE_SUBTYPE ]);
							}
						}

						//filter for years
						$filter_years = $filter;
						unset($filter_years['><PROPERTY_YEAR']);

						$bitrix_years = [];
						$iterator = CIBlockElement::GetPropertyValues( IBLOCK_ID_CATALOG_CARS_USED, $filter_years, true, [ 'ID' => [ PROPERTY_ID_CATALOG_CARS_USED_YEAR ] ] );
						while ($row = $iterator->Fetch())
						{
							array_push($bitrix_years, $row[ PROPERTY_ID_CATALOG_CARS_USED_YEAR ]);
						}
						sort($bitrix_years);
						$bitrix_years = array_values(array_unique($bitrix_years));

						for($y = $bitrix_years[0]; $y <= $bitrix_years[count($bitrix_years)-1]; $y++)
						{
							array_push($years, $y);
						}

						//filter for mileages
						$filter_mileages = $filter;
						unset($filter_mileages['><PROPERTY_MILEAGE']);

						$bitrix_mileages = [];
						$iterator = CIBlockElement::GetPropertyValues( IBLOCK_ID_CATALOG_CARS_USED, $filter_mileages, true, [ 'ID' => [ PROPERTY_ID_CATALOG_CARS_USED_MILEAGE ] ] );
						while ($row = $iterator->Fetch())
						{
							array_push($bitrix_mileages, $row[ PROPERTY_ID_CATALOG_CARS_USED_MILEAGE ]);
						}
						sort($bitrix_mileages);
						$bitrix_mileages = array_values(array_unique($bitrix_mileages));

						$mileage_min = floor($bitrix_mileages[0] / 50000);
						$mileage_max = $bitrix_mileages[count($bitrix_mileages)-1];
						$mileage_max = ceil($mileage_max / 50000);

						$m = $mileage_min;
						while($m <= ($mileage_max))
						{
							array_push($mileages, $m * 50000);
							$m++;
						}

						//filter for cities
						$filter_cities = $filter;
						unset($filter_cities['PROPERTY_PARKING_CITY']);

						$iterator = CIBlockElement::GetPropertyValues( IBLOCK_ID_CATALOG_CARS_USED, $filter_cities, true, [ 'ID' => [ PROPERTY_ID_CATALOG_CARS_USED_PARKING_CITY ] ] );
						while ($row = $iterator->Fetch())
						{
							//print_r($row[ PROPERTY_ID_CATALOG_CARS_USED_PARKING_CITY ]);
							array_push($cities, $row[ PROPERTY_ID_CATALOG_CARS_USED_PARKING_CITY ]);
						}
						//print "\n\ncities\n\n";
						//print_r($cities);
						//die();
					}

					//filter for brands
					$filter_brands = $filter;
					unset($filter_brands['PROPERTY_BRAND']);

					$brands_ids = [];
					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_brands, true, [ 'ID' => [ USED ? PROPERTY_ID_CATALOG_CARS_USED_BRAND : PROPERTY_ID_CATALOG_CARS_NEW_BRAND ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($brands_ids, $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_BRAND : PROPERTY_ID_CATALOG_CARS_NEW_BRAND ]);
					}

					$brands_ids = array_values(array_unique($brands_ids));

					$brands_res = CIBlockElement::GetList(["NAME" => "ASC"], array_merge([ "IBLOCK_ID" => USED ? IBLOCK_ID_BRANDS_USED : IBLOCK_ID_BRANDS ], [ "ID" => $brands_ids ]), false, []);
					while ($brands_ob_element = $brands_res->GetNextElement())
					{
						$brands_ar_res = $brands_ob_element->GetFields();
						$brands_ar_res['PROPERTIES'] = $brands_ob_element->GetProperties();

						array_push($brands, [
							"id" => $brands_ar_res['ID'], 
							"value" => $brands_ar_res['CODE'], 
							"text" => $brands_ar_res['NAME'], 
							"uid" => $brands_ar_res['PROPERTIES']['UID']['VALUE'], 
						]);
					}

					//filter for models
					if(!empty($REQ['BRAND_ID'])) 
					{ 
						$filter_models = $filter;
						unset($filter_models['PROPERTY_MODEL']);

						$models_ids = [];
						$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_models, true, [ 'ID' => [ USED ? PROPERTY_ID_CATALOG_CARS_USED_MODEL : PROPERTY_ID_CATALOG_CARS_NEW_MODEL ] ] );
						while ($row = $iterator->Fetch())
						{
							array_push($models_ids, $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_MODEL : PROPERTY_ID_CATALOG_CARS_NEW_MODEL ]);
						}

						$models_ids = array_values(array_unique($models_ids));

						$models_res = CIBlockElement::GetList(["NAME" => "ASC"], array_merge([ "IBLOCK_ID" => USED ? IBLOCK_ID_MODELS_USED : IBLOCK_ID_MODELS ], [ "ID" => $models_ids ]), false, []);
						while ($models_ob_element = $models_res->GetNextElement())
						{
							$models_ar_res = $models_ob_element->GetFields();
							$models_ar_res['PROPERTIES'] = $models_ob_element->GetProperties();
	
							array_push($models, [
								"id" => $models_ar_res['ID'], 
								"value" => $models_ar_res['CODE'], 
								"text" => $models_ar_res['NAME'], 
								"uid" => $models_ar_res['PROPERTIES']['UID']['VALUE'], 
							]);
						}
					}

					//filter for modifications
					if(!empty($REQ['MODEL_ID'])) 
					{ 
						$filter_modifications = $filter;
						unset($filter_modifications['PROPERTY_MODIFICATION']);

						$modifications_ids = [];

						$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_modifications, true, [ 'ID' => [ 5 ] ] );
						while ($row = $iterator->Fetch())
						{
							array_push($modifications_ids, $row[ 5 ]);
						}

						$modifications_ids = array_values(array_unique($modifications_ids));

						$modifications_res = CIBlockElement::GetList(["NAME" => "ASC"], array_merge([ "IBLOCK_ID" => IBLOCK_ID_MODIFICATIONS ], [ "ID" => $modifications_ids ]), false, []);
						while ($modifications_ob_element = $modifications_res->GetNextElement())
						{
							$modifications_ar_res = $modifications_ob_element->GetFields();

							array_push($modifications, [
								"id" => $modifications_ar_res['ID'], 
								"text" => $modifications_ar_res['NAME'], 
							]);
						}
					}

					//filter for bodies
					$filter_bodies = $filter;
					unset($filter_bodies['PROPERTY_BODY']);

					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_bodies, true, [ 'ID' => [ 9 ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($bodies, $row[ 9 ]);
					}

					//filter for gears
					$filter_gears = $filter;
					unset($filter_gears['PROPERTY_GEAR']);

					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_gears, true, [ 'ID' => [ 7 ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($gears, $row[ 7 ]);
					}

					//filter for drives
					$filter_drives = $filter;
					unset($filter_drives['PROPERTY_DRIVE']);

					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_drives, true, [ 'ID' => [ 8 ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($drives, $row[ 8 ]);
					}

					//filter for engine fuels
					$filter_engine_fuels = $filter;
					unset($filter_engine_fuels['PROPERTY_ENGINE_FUEL']);

					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_engine_fuels, true, [ 'ID' => [ USED ? PROPERTY_ID_CATALOG_CARS_USED_ENGINE_FUEL : PROPERTY_ID_CATALOG_CARS_NEW_ENGINE_FUEL ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($engine_fuels, $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_ENGINE_FUEL : PROPERTY_ID_CATALOG_CARS_NEW_ENGINE_FUEL ]);
					}

					//filter for engine fuels
					$filter_engine_volumes = $filter;
					unset($filter_engine_volumes['><PROPERTY_ENGINE_VOLUME']);

					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter_engine_volumes, true, [ 'ID' => [ USED ? PROPERTY_ID_CATALOG_CARS_USED_ENGINE_VOLUME : PROPERTY_ID_CATALOG_CARS_NEW_ENGINE_VOLUME ] ] );
					while ($row = $iterator->Fetch())
					{
						if($row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_ENGINE_VOLUME : PROPERTY_ID_CATALOG_CARS_NEW_ENGINE_VOLUME ] != 0)
						{
							array_push($engine_volumes, $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_ENGINE_VOLUME : PROPERTY_ID_CATALOG_CARS_NEW_ENGINE_VOLUME ]);
							array_push($result["possible_volumes"], $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_ENGINE_VOLUME : PROPERTY_ID_CATALOG_CARS_NEW_ENGINE_VOLUME ]);
						}
					}
					/*
					$iterator = CIBlockElement::GetPropertyValues( IBLOCK_ID_CATALOG_CARS_NEW, $filter, true, [ 'ID' => $filter_props_ids ] );
					while ($row = $iterator->Fetch())
					{
						if(!empty($REQ['BRAND_ID'])) { array_push($models, $row[4]); }

						array_push($gear, $row[7]);
						array_push($drive, $row[8]);
						array_push($fuel, $row[12]);
					}
					*/

					/*
					$result['filter2'] = array_merge($filter, [ "><PROPERTY_ENGINE_VOLUME" => [ 0, 10000 ]]);

					$iterator_volume = CIBlockElement::GetPropertyValues( 1, array_merge($filter, [ "><PROPERTY_ENGINE_VOLUME" => [ 0, 10000 ]]), true, [ 'ID' => [ 11 ] ] );
					while ($row = $iterator_volume->Fetch())
					{
						if($row[11] != 0)
						{
							array_push($volume, $row[11]);
							array_push($result["vvv"], $row[11]);
						}
					}
					*/

					//$models = array_values(array_unique($models));

					$cities = array_values(array_unique($cities));
					sort($cities);

					$gears = array_values(array_unique($gears));
					$drives = array_values(array_unique($drives));
					$bodies = array_values(array_unique($bodies));
					$engine_fuels = array_values(array_unique($engine_fuels));
					$engine_volumes = array_values(array_unique($engine_volumes));
					sort($engine_volumes);

					$vehicle_subtypes = array_values(array_unique($vehicle_subtypes));

					$years = array_values(array_unique($years));
					$mileages = array_values(array_unique($mileages));

					$bodies_slugs = [];
					foreach($bodies AS $bk => $bv)
					{
						$bodies_slugs[$bv] = CUtil::translit( $bv, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );
					}

					$engine_fuels_slugs = [];
					foreach($engine_fuels AS $efk => $efv)
					{
						$engine_fuels_slugs[$efv] = CUtil::translit( $efv, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );
					}

					$volumes = [];
					$min = floor($engine_volumes[0] / 100) * 100;
					$max = (floor($engine_volumes[count($engine_volumes)-1] / 100) + 1) * 100;

					while($min <= $max)
					{
						if($min > 0)
						{
							array_push($volumes, $min);
						}

						$min = $min + 100;
					}

					$result["vehicle_types"] = $vehicle_types;
					$result["vehicle_subtypes"] = $vehicle_subtypes;

					$result["brands"] = $brands;
					$result["models"] = $models;
					$result["modifications"] = $modifications;

					$result["gears"] = $gears;
					$result["drives"] = $drives;
					$result["bodies"] = $bodies;
					$result["bodies_slugs"] = $bodies_slugs;
					$result["engine_fuels"] = $engine_fuels;
					$result["engine_fuels_slugs"] = $engine_fuels_slugs;

					$result["cities"] = $cities;
					$result["years"] = $years;
					$result["mileages"] = $mileages;
					$result["bitrix_mileages"] = $bitrix_mileages;
					$result["bitrix_years"] = $bitrix_years;

					//if(empty($REQ['ENGINE_VOLUME_FROM']) || empty($REQ['ENGINE_VOLUME_TO'])) { 
						$result["engine_volumes"] = $volumes;
					//}

					print json_encode($result);
				}
			}
			break;

			/*
			case "-arameters":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$GEAR = [];
					$DRIVE = [];
					$BODY = [];
					$ENGINE_POWER = [];
					$ENGINE_VOLUME = [];
					$ENGINE_FUEL = [];

					$iterator = CIBlockElement::GetPropertyValues(1, ['ACTIVE' => 'Y', ], false, ['ID' => [ 7, 8, 9, 10, 11, 12, ] ]);
					while ($row = $iterator->Fetch())
					{
						if(!in_array($row[7], $GEAR)) { array_push($GEAR, $row[7]); }
						if(!in_array($row[8], $DRIVE)) { array_push($DRIVE, $row[8]); }
						if(!in_array($row[9], $BODY)) { array_push($BODY, $row[9]); }
						if(!in_array(floor($row[10]), $ENGINE_POWER)) { array_push($ENGINE_POWER, floor($row[10])); }
						if(!in_array(floor($row[11]), $ENGINE_VOLUME)) { array_push($ENGINE_VOLUME, floor($row[11])); }
						if(!in_array($row[12], $ENGINE_FUEL)) { array_push($ENGINE_FUEL, $row[12]); }
					}

					sort($ENGINE_POWER);
					sort($ENGINE_VOLUME);

					sort($BODY);
					print json_encode([
						"bodies" => $BODY, 
						"gears" => $GEAR, 
						"drives" => $DRIVE, 
						"engine_powers" => [ $ENGINE_POWER[0], $ENGINE_POWER[count($ENGINE_POWER) - 1] ], 
						"engine_volumes" => [ $ENGINE_VOLUME[0], $ENGINE_VOLUME[count($ENGINE_VOLUME) - 1] ], 
						"engine_fuels" => $ENGINE_FUEL, 
					]);
				}
			}
			break;
			*/

			case "pdf":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$images = [];
					$car = [];

					if(!empty($REQ['contract']))
					{
						$car_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_USED, "CODE" => $REQ['contract'] ], false, [], [] );
						while($car_search_ob = $car_search_res->GetNextElement())
						{
							$car = $car_search_ob->GetFields();
							$car['PROPERTIES'] = $car_search_ob->GetProperties();
							$car['PROPERTIES']['BRAND']['RELATED'] = get_related(IBLOCK_ID_BRANDS_USED, $car['PROPERTIES']['BRAND']['VALUE']);
							$car['PROPERTIES']['MODEL']['RELATED'] = get_related(IBLOCK_ID_MODELS_USED, $car['PROPERTIES']['MODEL']['VALUE']);

							$images = [];

							foreach($car['PROPERTIES']['PHOTOS_1080']['VALUE'] AS $photo_id)
							{
								array_push($images, $_SERVER['DOCUMENT_ROOT'].CFile::GetPath($photo_id));
							}

							$tech_array = [];
							if(!empty($car['PROPERTIES']['YEAR']['VALUE'])) { array_push($tech_array, "· Год выпуска: ".$car['PROPERTIES']['YEAR']['VALUE']); }
							if(!empty($car['PROPERTIES']['MILEAGE']['VALUE'])) { array_push($tech_array, "· Пробег: ".$car['PROPERTIES']['MILEAGE']['VALUE']." км"); }
							if(!empty($car['PROPERTIES']['ENGINE_HOURS']['VALUE'])) { array_push($tech_array, "· Моточасы: ".$car['PROPERTIES']['ENGINE_HOURS']['VALUE']); }
							if(!empty($car['PROPERTIES']['ENGINE_POWER']['VALUE'])) { array_push($tech_array, "· Л.с.: ".$car['PROPERTIES']['ENGINE_POWER']['VALUE']); }
							if(!empty($car['PROPERTIES']['ENGINE_VOLUME']['VALUE'])) { array_push($tech_array, "· Объем: ".$car['PROPERTIES']['ENGINE_VOLUME']['VALUE']); }
							if(!empty($car['PROPERTIES']['ENGINE_FUEL']['VALUE'])) { array_push($tech_array, "· Топливо: ".$car['PROPERTIES']['ENGINE_FUEL']['VALUE']); }
							if(!empty($car['PROPERTIES']['PARKING_REGION']['VALUE'])) { array_push($tech_array, "· Регион размещения: ".$car['PROPERTIES']['PARKING_REGION']['VALUE']); }
							if(!empty($car['PROPERTIES']['PARKING_CITY']['VALUE'])) { array_push($tech_array, "· Регион размещения: ".$car['PROPERTIES']['PARKING_CITY']['VALUE']); }
						}

						if(isset($car['NAME']))
						{	
							$pdf = new PDF();
							$pdf->AddPage();

							$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
							$pdf->AddFont('DejaVuBold','','DejaVuSansCondensed-Bold.ttf',true);
							$pdf->SetFont('DejaVuBold','',13);
							$pdf->Ln(-10);
							$pdf->Write(8,"Коммерческое предложение");
							$pdf->Ln(5);
							$pdf->SetFont('DejaVu','',12);
							$pdf->SetTextColor(110,110,110);
							$pdf->Write(8,"на транспортное средство с пробегом");
							$pdf->Ln(20);
							$pdf->SetFont('DejaVuBold','',14);
							$pdf->SetTextColor(0,0,0);
							$top_line_y = $pdf->GetY();
							$pdf->MultiCell(100, 6, $car['PROPERTIES']['BRAND']['RELATED']['NAME']." ".$car['PROPERTIES']['MODEL']['RELATED']['NAME']);
							$pdf->SetFont('DejaVu','',12);
							$pdf->SetTextColor(110,110,110);
							$pdf->MultiCell(100, 6, $car['PROPERTIES']['MODIFICATION']['VALUE']);
							$pdf->Ln(10);

							$pdf->Image(isset($images[0]) ? $images[0] : $_SERVER['DOCUMENT_ROOT']."/images/no_image_650.png", 11, $pdf->GetY(), 100, 75);

							$under_photo_y = $pdf->GetY() + 75;

							$pdf->SetXY(120, $top_line_y - 2);
							$pdf->SetFont('DejaVuBold','', 13);
							if($car['PROPERTIES']['PRICE_WITH_DISCOUNT']['VALUE'] > 0)
							{
								$pdf->SetTextColor(110,110,110);
								$pdf->Write(8, "Цена: ".number_format($car['PROPERTIES']['PRICE']['VALUE'], 0, " ", " ")." ₽");
								$pdf->SetXY(120, $top_line_y + 5);
								$pdf->SetTextColor(0,0,0);
								$pdf->Write(8, "Цена со скидкой: ".number_format($car['PROPERTIES']['PRICE_WITH_DISCOUNT']['VALUE'], 0, " ", " ")." ₽");
								$pdf->Line(136, $top_line_y + 2, 165, $top_line_y + 2);
							}
							else
							{
								$pdf->SetTextColor(0,0,0);
								$pdf->Write(8, "Цена: ".number_format($car['PROPERTIES']['PRICE']['VALUE'], 0, " ", " ")." ₽");
							}

							$pdf->SetXY(120, 55);
							$pdf->SetFont('DejaVuBold','', 11);
							$pdf->Write(8, "Артикул");
							$pdf->SetFont('DejaVu','', 11);
							$pdf->Write(8, ": ".$car['PROPERTIES']['CONTRACT']['VALUE']);
							$pdf->Ln(1);
							$pdf->SetXY(120, 62);
							$pdf->SetFont('DejaVuBold','', 11);
							$pdf->Write(8, "VIN");
							$pdf->SetFont('DejaVu','', 11);
							$pdf->Write(8, ": ".str_repeat("*", 12).substr($car['PROPERTIES']['VIN']['VALUE'], 12, 5));
							$pdf->SetXY(120, 75);
							$pdf->SetFont('DejaVuBold','', 11);
							$pdf->Write(8, "Ключевые характеристики");
							$pdf->SetXY(120, 82);
							$pdf->SetFont('DejaVu','', 11);
							$pdf->MultiCell(100, 6, implode("\n", $tech_array));

							$pdf->SetXY(10, $under_photo_y + 5);
							$pdf->SetFont('DejaVuBold','', 11);
							$pdf->Write(8, "Комплектация");
							$pdf->Ln(6);
							$pdf->SetFont('DejaVu','', 10);
							$pdf->MultiCell(0, 4, str_replace("\t", " ", $car['~DETAIL_TEXT']));

							$pdf->Ln(6);
							$pdf->SetFont('DejaVuBold','', 16);
							$pdf->Write(10, "Остались вопросы?");
							$pdf->Ln(7);
							$pdf->SetFont('DejaVuBold','', 13);
							$pdf->Write(8, "Позвоните по телефону горячей линии 8 800 333 75 75");
							$pdf->Ln(5);
							$pdf->SetFont('DejaVu','',12);
							$pdf->SetTextColor(110,110,110);
							$pdf->Write(8, "Или напишите по адресу электронной почты izt@evoleasing.ru");
							if(count($images) > 1)
							{
								$pdf->Ln(15);
								$pdf->SetFont('DejaVuBold','', 16);
								$pdf->SetTextColor(0,0,0);
								$pdf->Write(10, "Остальные фотографии");
								$pdf->Ln(10);

								$pdf->SetFont('DejaVu','',10);

								if($pdf->GetY() >= 199)
								{
									$pdf->AddPage();
								}

								$x = 0;
								$y = 0;
								foreach($images AS $k => $image)
								{
									if($k > 0)
									{
										if($pdf->GetY() >= 199)
										{
											$pdf->AddPage();
											$y = 0;
										}

										$pdf->Image($image, ($x * 90) + ($x > 0 ? 18 : 11), ((68 * $y) + $pdf->GetY()) + 10, 90, 68, "JPEG");
										if($x === 1)
										{
											$x = 0;
											$y = 0;
											$pdf->SetY($pdf->GetY() + 75);
										}
										else
										{
											$x++;
										}
									}
								}
							}

							$pdf->Output('D');
							die();
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_contract", 
								"message" => "Wrong contract number", 
							]);

							die();
						}
					}
					else
					{
						print json_encode([
							"status" => "error", 
							"error" => "empty_contract", 
							"message" => "Empty contract number", 
						]);

						die();
					}
				}
			}

			case "reset":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$cars = [];
					$cars_res = CIBlockElement::GetList(["ID" => "ASC"], [ "IBLOCK_ID" => 1 ], false, []);
					while ($cars_ob_element = $cars_res->GetNextElement())
					{
						$cars_ar_res = $cars_ob_element->GetFields();
						CIBlockElement::Delete($cars_ar_res['ID']);
					}

					$modifications_res = CIBlockElement::GetList(["ID" => "ASC"], [ "IBLOCK_ID" => 10 ], false, []);
					while ($modifications_ob_element = $modifications_res->GetNextElement())
					{
						$modifications_ar_res = $modifications_ob_element->GetFields();
						CIBlockElement::Delete($modifications_ar_res['ID']);
					}

					$models_res = CIBlockElement::GetList(["NAME" => "ASC"], [ "IBLOCK_ID" => 9 ], false, []);
					while ($models_ob_element = $models_res->GetNextElement())
					{
						$models_ar_res = $models_ob_element->GetFields();
						CIBlockElement::Delete($models_ar_res['ID']);
					}

					$brands_res = CIBlockElement::GetList(["NAME" => "ASC"], [ "IBLOCK_ID" => 8 ], false, []);
					while ($brands_ob_element = $brands_res->GetNextElement())
					{
						$brands_ar_res = $brands_ob_element->GetFields();
						CIBlockElement::Delete($brands_ar_res['ID']);
					}
				}

				die();
			}
			break;
		}
	}
	break;

	case "programs":
	{
		switch($PARAM_2)
		{
			case "brands":
			{
				if(CModule::IncludeModule('iblock'))
				{
					define("USED", filter_var($REQ['USED'], FILTER_VALIDATE_BOOLEAN));
					$filter = [ "ACTIVE" => "Y", ];

					if(!empty($REQ['PROGRAM'])) { $filter['PROPERTY_LEASING_PROGRAMS'] = $REQ['PROGRAM']; }

					$brands = [];
					$brands_ids = [];
					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter, true, [ 'ID' => [ USED ? PROPERTY_ID_CATALOG_CARS_USED_BRAND : PROPERTY_ID_CATALOG_CARS_NEW_BRAND ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($brands_ids, $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_BRAND : PROPERTY_ID_CATALOG_CARS_NEW_BRAND ]);
					}

					$brands_ids = array_values(array_unique($brands_ids));

					$brands_res = CIBlockElement::GetList(["NAME" => "ASC"], array_merge([ "IBLOCK_ID" => USED ? IBLOCK_ID_BRANDS_USED : IBLOCK_ID_BRANDS ], [ "ID" => $brands_ids ]), false, []);
					while ($brands_ob_element = $brands_res->GetNextElement())
					{
						$brands_ar_res = $brands_ob_element->GetFields();
						$brands_ar_res['PROPERTIES'] = $brands_ob_element->GetProperties();

						array_push($brands, [
							"id" => $brands_ar_res['ID'], 
							"value" => $brands_ar_res['CODE'], 
							"text" => $brands_ar_res['NAME'], 
							"uid" => $brands_ar_res['PROPERTIES']['UID']['VALUE'], 
						]);
					}

					print json_encode([
						"brands" => $brands, 
					]);
				}
			}
			break;

			case "models":
			{
				if(CModule::IncludeModule('iblock'))
				{
					define("USED", filter_var($REQ['USED'], FILTER_VALIDATE_BOOLEAN));
					$filter = [ "ACTIVE" => "Y", "PROPERTY_BRAND" => $REQ['BRAND_ID'] ];

					if(!empty($REQ['PROGRAM'])) { $filter['PROPERTY_LEASING_PROGRAMS'] = $REQ['PROGRAM']; }

					$models = [];
					$models_ids = [];
					$iterator = CIBlockElement::GetPropertyValues( USED ? IBLOCK_ID_CATALOG_CARS_USED : IBLOCK_ID_CATALOG_CARS_NEW, $filter, true, [ 'ID' => [ USED ? PROPERTY_ID_CATALOG_CARS_USED_MODEL : PROPERTY_ID_CATALOG_CARS_NEW_MODEL ] ] );
					while ($row = $iterator->Fetch())
					{
						array_push($models_ids, $row[ USED ? PROPERTY_ID_CATALOG_CARS_USED_MODEL : PROPERTY_ID_CATALOG_CARS_NEW_MODEL ]);
					}

					$models_ids = array_values(array_unique($models_ids));

					$models_res = CIBlockElement::GetList(["NAME" => "ASC"], array_merge([ "IBLOCK_ID" => USED ? IBLOCK_ID_MODELS_USED : IBLOCK_ID_MODELS ], [ "ID" => $models_ids ]), false, []);
					while ($models_ob_element = $models_res->GetNextElement())
					{
						$models_ar_res = $models_ob_element->GetFields();
						$models_ar_res['PROPERTIES'] = $models_ob_element->GetProperties();

						array_push($models, [
							"id" => $models_ar_res['ID'], 
							"value" => $models_ar_res['CODE'], 
							"text" => $models_ar_res['NAME'], 
							"uid" => $models_ar_res['PROPERTIES']['UID']['VALUE'], 
						]);
					}

					print json_encode([
						"models" => $models, 
					]);
				}
			}
			break;

			default:
			{
				if(CModule::IncludeModule('iblock'))
				{
					$programs = [];
					$programs_res = CIBlockElement::GetList(["SORT" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => 3], false, []);
					while ($programs_ob_element = $programs_res->GetNextElement())
					{
						$programs_ar_res = $programs_ob_element->GetFields();

						$programs[] = [
							"name" => $programs_ar_res['NAME'], 
							"code" => $programs_ar_res['CODE'], 
						];
					}

					print json_encode([
						"programs" => $programs, 
					]);
				}
			}
			break;
		}
	}
	break;

	case "announcements":
	{
		if(CModule::IncludeModule('iblock'))
		{
			$announcements = [];
			$announcements_res = CIBlockElement::GetList(["SORT" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_ACCOUNT_ANNOUNCEMENTS], false, []);
			while ($announcements_ob_element = $announcements_res->GetNextElement())
			{
				$announcements_ar_res = $announcements_ob_element->GetFields();
				$announcements_ar_res['PROPERTIES'] = $announcements_ob_element->GetProperties();

				$announcements[] = [
					"title" => $announcements_ar_res['NAME'], 
					"content" => $announcements_ar_res['PREVIEW_TEXT'], 
					"url" => !empty($announcements_ar_res['PROPERTIES']['URL']['VALUE']) ? $announcements_ar_res['PROPERTIES']['URL']['VALUE'] : null, 
				];
			}

			print json_encode([
				"announcements" => $announcements, 
			]);
		}
	}
	break;

	case "regions":
	{
		if(CModule::IncludeModule('iblock'))
		{
			$regions = [];
			$regions_res = CIBlockElement::GetList(["SORT" => "ASC", "NAME" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => 5, ], false, []);
			while ($regions_ob_element = $regions_res->GetNextElement())
			{
				$regions_ar_res = $regions_ob_element->GetFields();
				$regions_ar_res['PROPERTIES'] = $regions_ob_element->GetProperties();
				$regions_ar_res['PROPERTIES']['REGION']['RELATED'] = get_related(15, $regions_ar_res['PROPERTIES']['REGION']['VALUE']);

				$regions[] = [
					"NAME" => $regions_ar_res['PROPERTIES']['REGION']['RELATED']['NAME'], 
					"ID" => $regions_ar_res['PROPERTIES']['REGION']['RELATED']['ID'], 
				];
			}

			print json_encode([
				"regions" => $regions, 
			]);
		}
	}
	break;

	case "forms":
	{
		if(CModule::IncludeModule('form'))
		{
			$ipAddress = GeoIp\Manager::getRealIp();
			$result = GeoIp\Manager::getDataResult($ipAddress, "ru");
			$arr = Array();

			if(checkRecaptchaRequest($_REQUEST['recaptcha_token'], $ipAddress))
			{
				$_REQUEST['FORM_FIELD_REGION'] = $result->getGeoData()->regionName.", ".$result->getGeoData()->cityName;

				$error = "";
				$form_errors = Array(); 
				$arParams['request'] = $_REQUEST;
				$attach = false;

				$form_code = trim($_REQUEST['form']);

				$form = CForm::GetBySID($form_code);
				$form = $form->Fetch();

				$formQuestions = Array();
				$formAnswers = Array();

				$sort = "s_sort";
				$order = "asc";
				$filtered = false;
				$resFormQuestions = CFormField::GetList($form['ID'], "N", $$sort, $$order, Array(), $$filtered);
				while($arFormQuestion = $resFormQuestions->Fetch())
				{
					$rsAnswers = CFormAnswer::GetList($arFormQuestion['ID'], $$sort, $$order, Array(), $$filtered);
					$arAnswer = $rsAnswers->Fetch();

					$arFormQuestion['ANSWER'] = $arAnswer;
					$formQuestions[] = $arFormQuestion;
				}

				$c = 1;
				foreach($formQuestions AS $fq)
				{
					if($fq['REQUIRED'] == "Y")
					{
						if($_REQUEST[$fq['SID']] == "" && $fq['ANSWER']['FIELD_TYPE'] != "file")
						{
							array_push($form_errors, $fq['SID']);
						}
						if($fq['ANSWER']['FIELD_TYPE'] == "email")
						{
							if(!filter_var($_REQUEST[$fq['SID']], FILTER_VALIDATE_EMAIL))
							{
								array_push($form_errors, $fq['SID']);
							}
						}
					}

					if($fq['ANSWER']['FIELD_TYPE'] == "file")
					{
						if(is_array($_FILES[$fq['SID']]))
						{
							if(CFormValidator::Execute(
								array("PARAMS" => Array("EXT" => "doc,docx,rtf,pdf,txt,jpg,jpeg,png,gif,bmp"),"NAME" => "file_type"),
								array(),
								array(),
								array($_FILES[$fq['SID']])
							))
							{
								$formAnswers["form_".$fq['ANSWER']['FIELD_TYPE']."_".$fq['ANSWER']['ID']] = $_FILES[$fq['SID']];
								$attach = true;
							}
							else
							{
								array_push($form_errors, $fq['SID']);
							}
						}
						else
						{
							if($fq['REQUIRED'] == "Y")
							{
								array_push($form_errors, $fq['SID']);
							}
						}
					}
					else
					{
						if(strpos($fq['TITLE'], "utm_") > -1)
						{
							$formAnswers["form_".$fq['ANSWER']['FIELD_TYPE']."_".$fq['ANSWER']['ID']] = $_COOKIE[strtolower($fq['TITLE'])];
						}
						else
						{
							$formAnswers["form_".$fq['ANSWER']['FIELD_TYPE']."_".$fq['ANSWER']['ID']] = $_REQUEST[$fq['SID']];
						}
					}

					$arr['q'][] = $fq;

					$c++;
				}

				if(!empty($_SESSION[$_REQUEST['form']."_CAPTCHA"]))
				{
					if($_SESSION[$_REQUEST['form'].'_CAPTCHA'] != $_REQUEST[$_REQUEST['form'].'_CAPTCHA'])
					{
						array_push($form_errors, $_REQUEST['form'].'_CAPTCHA');
					}
				}

				$arr['FILES'] = $_FILES;

				if(count($form_errors) == 0)
				{
					if($RESULT_ID = CFormResult::Add($form['ID'], $formAnswers))
					{
						$arr['status'] = "complete";

						if($attach || array_key_exists("FORM_FILLING", $_REQUEST))
						{
							if($attach)
							{
								$arAnswer = CFormResult::GetDataByID($RESULT_ID, Array(), $arResult, $arAnswer2);

								$fields = Array();
								$attached_files = Array();
								foreach($arAnswer AS $k => $v)
								{
									$fields[$k] = $v[0]['USER_TEXT'];
									if($v[0]['USER_FILE_ID'] != NULL)
									{
										array_push($attached_files, $v[0]['USER_FILE_ID']);
									}
								}

								$post_event_name = "FORM_FILLING_".$_REQUEST['form'];

								CEvent::Send($post_event_name, "s1", $fields, "N", "", $attached_files);
							}
							else
							{
								CFormResult::Mail($RESULT_ID);
							}
						}
						else
						{
							CFormResult::Mail($RESULT_ID);
						}

						if($form_code === "FORM_LEASING_REQUESTS")
						{
							$url = API_HOST."/site/RequestFromSite";

							$payload = [ 
								"region" => $_REQUEST['FORM_FIELD_REGION'], 
								"name" => $REQ['FORM_FIELD_FIO'], 
								"phone" => $REQ['FORM_FIELD_PHONE'], 
								"email" => $REQ['FORM_FIELD_EMAIL'], 
								"org_title" => $REQ['FORM_FIELD_COMPANY'], 
								"brand" => $REQ['FORM_FIELD_BRAND'], 
								"model" => $REQ['FORM_FIELD_MODEL'], 
								"modification" => $REQ['FORM_FIELD_MODIFICATION'], 
								"price" => (int) $REQ['FORM_FIELD_PRICE'], 
								"prepaid" => (int) $REQ['FORM_FIELD_PREPAID'], 
								"term" => (int) $REQ['FORM_FIELD_TERM'], 
								"redemption" => (int) $REQ['FORM_FIELD_REDEMPTION'], 
								"utm_source" => $_COOKIE['utm_source'], 
								"utm_medium" => $_COOKIE['utm_medium'], 
								"utm_campaign" => $_COOKIE['utm_campaign'], 
								"utm_term" => $_COOKIE['utm_term'], 
								"utm_content" => $_COOKIE['utm_content'], 
								"page_url" => $REQ['FORM_FIELD_PAGE_URL'], 
								"page_name" => $REQ['FORM_FIELD_PAGE_NAME'], 
								"sale_type" => $REQ['FORM_FIELD_SALE_TYPE'], 
								"inn" => $REQ['FORM_FIELD_INN'], 
							];
							if(!empty($REQ['FORM_FIELD_IS_IZT']))
							{
								$payload['sale_type'] = "izt";
							}

							$payload_json = json_encode($payload);

							$c = curl_init();
							curl_setopt($c, CURLOPT_URL, API_HOST."/site/RequestFromSite");
							curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
							curl_setopt($c, CURLOPT_TIMEOUT, 30);
							curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
							curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
							curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
							curl_setopt($c, CURLOPT_POST, 1);
							curl_setopt($c, CURLOPT_POSTFIELDS, $payload_json);
							curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

							$response = curl_exec($c);
							curl_close($c);
						}
					}
					else
					{
						$arr['status'] = "error";
						global $strError;
						$arr['message'] = $strError;
					}
				}
				else
				{
					$arr['status'] = "error";
					$arr['errors'] = $form_errors;
				}

				$arr['request'] = $_REQUEST;
				$arr['answers'] = $formAnswers;
			}
			else
			{
				$arr['status'] = "error";
				$arr['message'] = "recaptcha_error";
			}

			print json_encode($arr);
			die();
		}
	}
	break;

	case "account":
	{
		switch($PARAM_2)
		{
			case "token":
			{
				print \Bitrix\Main\Web\JWT::encode(["acc_number" => $REQ['acc_number']], $secret, 'HS256', null, null);
				die();
			}
			break;

			case "recovery":
			{
				switch($PARAM_3)
				{
					case "email":
					{
						if(checkRequestIsLocal())
						{
							$rs_user = \CUser::GetByLogin($REQ['email']);
							$ar_user = $rs_user->Fetch();

							if(is_array($ar_user))
							{
								if(SEND_EMAIL_PASSWORD_RECOVERY_CODE)
								{
									\Bitrix\Main\Mail\Event::send([
										"EVENT_NAME" => "USER_PASSWORD_RECOVERY_CODE",
										"LID" => "s1",
										"C_FIELDS" => Array(
											"EMAIL" => $REQ['email'], 
											"CODE" => $REQ['code'], 
										)
									]);
								}

								print json_encode([
									"status" => "success", 
								]);
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "wrong_email", 
									"message" => "Wrong email", 
								]);
							}
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_source", 
								"message" => "Wrong source", 
							]);
						}
					}
					break;

					case "password":
					{
						if(checkRequestIsLocal())
						{
							$rs_user = \CUser::GetByLogin($REQ['email']);
							$ar_user = $rs_user->Fetch();

							if(is_array($ar_user))
							{
								$user = new \CUser;
								$profile = [
									"PASSWORD" => $REQ['password'], 
									"CONFIRM_PASSWORD" => $REQ['password'], 
								];

								$user->Update($ar_user['ID'], $profile);

								if($user->LAST_ERROR)
								{
									print json_encode([
										"status" => "error", 
										"error" => "wrong_payload", 
										"message" => $user->LAST_ERROR, 
									]);
								}
								else
								{
									print json_encode([
										"status" => "success", 
									]);
								}
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "wrong_email", 
									"message" => "Wrong email", 
								]);
							}
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_source", 
								"message" => "Wrong source", 
							]);
						}
					}
					break;
				}
			}
			break;

			case "change":
			{
				switch($PARAM_3)
				{
					case "password":
					{
						if(checkRequestIsLocal())
						{
							$user = new \CUser;
							$login_result = $user->Login($REQ['email'], $REQ['password'], "N");

							if($login_result == 1)
							{
								$existed_user_res = \CUser::GetByLogin($REQ['email']);
								$existed_user = $existed_user_res->Fetch();

								if(is_array($existed_user))
								{
									$profile = [
										"PASSWORD" => $REQ['new_password'], 
										"CONFIRM_PASSWORD" => $REQ['new_password_repeat'], 
									];

									$user->Update($existed_user['ID'], $profile);

									if($user->LAST_ERROR)
									{
										print json_encode([
											"status" => "error", 
											"error" => "wrong_payload", 
											"message" => $user->LAST_ERROR, 
										]);
									}
									else
									{	
										print json_encode([
											"status" => "success", 
										]);
									}
								}
								else
								{
									print json_encode([
										"status" => "error", 
										"error" => "unknow_user", 
										"message" => "Unknown user", 
									]);
								}
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "wrong_email", 
									"message" => "Wrong email", 
								]);
							}
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_source", 
								"message" => "Wrong source", 
							]);
						}
					}
					break;

					case "phone":
					{
						if(checkRequestIsLocal())
						{
							$token = str_replace("Bearer ", "", $_SERVER['REMOTE_USER']);
							$auth = (array) \Bitrix\Main\Web\JWT::decode($token, $secret, ["HS256"]);

							$user = new \CUser;

							$existed_user_res = \CUser::GetByLogin($REQ['email']);
							$existed_user = $existed_user_res->Fetch();

							if(is_array($existed_user))
							{
								if($existed_user['XML_ID'] == $auth['acc_number'])
								{
									$existed_phone_users_res = \CUser::GetList(["ID" => "ASC"], false, [ "UF_PHONE_NUMBER" => $REQ['phone'] ], []);
									while($existed_phone_user = $existed_phone_users_res->Fetch())
									{
										$user->Update($existed_user['ID'], [
											"UF_PHONE_NUMBER" => "", 
										]);
									}

									$profile = [
										"UF_PHONE_NUMBER" => $REQ['phone'], 
									];

									$user->Update($existed_user['ID'], $profile);

									if($user->LAST_ERROR)
									{
										print json_encode([
											"status" => "error", 
											"error" => "wrong_payload", 
											"message" => $user->LAST_ERROR, 
										]);
									}
									else
									{	
										print json_encode([
											"status" => "success", 
										]);
									}
								}
								else
								{
									print json_encode([
										"status" => "error", 
										"error" => "wrong_company", 
										"message" => "Wrong company", 
									]);
								}
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "wrong_email", 
									"message" => "Wrong email", 
								]);
							}
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_source", 
								"message" => "Wrong source", 
							]);
						}
					}
					break;
				}
			}
			break;

			case "auth":
			{
				switch($PARAM_3)
				{
					case "email":
					{
						$user = new \CUser;
						$ar_auth_result = $user->Login($REQ['email'], $REQ['password'], "N");

						if($ar_auth_result == 1)
						{
							$rs_user = \CUser::GetByLogin($REQ['email']);
							$ar_user = $rs_user->Fetch();

							$companies = getCompaniesForUser($ar_user['ID']);
							$company_data = [
								"inn" => $companies[0]['inn'], 
								"kpp" => $companies[0]['kpp'], 
								"ogrn" => $companies[0]['ogrn'], 
								"title" => $companies[0]['title'], 
							];

							$user_data = [
								"email" => $ar_user['LOGIN'], 
								"name" => $ar_user['NAME'], 
								"secondname" => $ar_user['SECOND_NAME'], 
								"lastname" => $ar_user['LAST_NAME'], 
								"phone" => $ar_user['UF_PHONE_NUMBER'], 
								"phone_verified" => $ar_user['UF_PHONE_VERIFIED'], 
								"is_admin" => $companies[0]['is_admin'], 
								"valid_email" => $ar_user['UF_IS_VALID_EMAIL'], 
							];

							print json_encode([
								"status" => "success", 
								"user" => $user_data, 
								"company" => $company_data, 
								"companies" => $companies, 
								"token" => \Bitrix\Main\Web\JWT::encode([ "acc_number" => $companies[0]['acc_number'], "is_admin" => $companies[0]['is_admin'], "login" => $ar_user['LOGIN'], "companies" => $companies ], $secret, 'HS256', null, null), 
							]);
						}
						else
						{
							print json_encode([
								"status" => "error", 
								"error" => "wrong_credentials", 
								"message" => "Wrong username or password", 
							]);
						}
					}
					break;

					case "phone":
					{
						if(!empty($REQ['phone']))
						{
							if(checkRequestIsLocal())
							{
								$user = new \CUser;
								$filter = ["UF_PHONE_NUMBER" => $REQ['phone']];

								$numbers = [];
								$rsUsers = CUser::GetList(["ID" => "ASC"], false, $filter, array("SELECT"=>array("UF_*")));
								while($arUser = $rsUsers->Fetch())
								{
									array_push($numbers, $arUser);
								}

								if(count($numbers) > 0)
								{
									$ar_user =  $numbers[count( $numbers ) - 1];
									$companies = getCompaniesForUser($ar_user['ID']);

									print json_encode([
										"status" => "success", 
										"acc_number" => $ar_user['XML_ID'], 
										"user" => [
											"email" => $ar_user['LOGIN'], 
											"name" => $ar_user['NAME'], 
											"secondname" => $ar_user['SECOND_NAME'], 
											"lastname" => $ar_user['LAST_NAME'], 
											"phone_number" => $ar_user['UF_PHONE_NUMBER'], 
											"phone_verified" => $ar_user['UF_PHONE_VERIFIED'], 
											"is_admin" => $companies[0]['is_admin'], 
											"valid_email" => $ar_user['UF_IS_VALID_EMAIL'], 
										], 
										"company" => [
											"inn" => $companies[0]['inn'], 
											"kpp" => $companies[0]['kpp'], 
											"ogrn" => $companies[0]['ogrn'], 
											"title" => $companies[0]['title'], 
										], 
										"companies" => $companies, 
									]);
								}
								else
								{
									print json_encode([
										"status" => "error", 
										"error" => "unknown_user", 
										"message" => "Unknown user", 	
									]);
								}
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "wrong_source", 
									"message" => "Wrong source", 
								]);
							}
						}
						else
						{
							print json_encode([
								"status" => "error", 
							]);
						}
					}
					break;

					default:
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_auth_uri", 
							"message" => "Empty auth URI", 
						]);
					}
					break;
				}
				die();
			}
			break;

			case "companies":
			{
				try
				{
					$auth = (array) \Bitrix\Main\Web\JWT::decode($token, $secret, ["HS256"]);
					print_r($auth);
				}
				catch(\Exception $e)
				{
					print json_encode([
						"status" => "error", 
						"error" => "wrong_jwt", 
						"message" => $e->getMessage(), 
					]);
					die();
				}
			}
			break;

			case "rules":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$sort = ["ACTIVE_FROM" => "DESC", "SORT" => "DESC"];
					$filter = ["ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_ACCOUNT_RULES];
					$options = [];

					if(!empty($REQ['date']))
					{
						$filter['<DATE_ACTIVE_FROM'] = $REQ['date'];
						$options['nPageSize'] = 1;
						$sort["ACTIVE_FROM"] = "DESC";
					}

					$rules = [];
					$rules_res = CIBlockElement::GetList($sort, $filter, false, $options);
					while ($rules_ob_element = $rules_res->GetNextElement())
					{
						$rules_ar_res = $rules_ob_element->GetFields();
						$rules_ar_res['PROPERTIES'] = $rules_ob_element->GetProperties();

						$f = CFile::GetByID($rules_ar_res['PROPERTIES']['FILE']['VALUE']);

						$rules[] = [
							"name" => $rules_ar_res['NAME'], 
							"active_from" => $rules_ar_res['ACTIVE_FROM'], 
							"filename" => $f->Fetch()['ORIGINAL_NAME'], 
							"url" => "https://".SITE_SERVER_NAME.CFile::GetPath($rules_ar_res['PROPERTIES']['FILE']['VALUE']), 
						];
					}

					print json_encode([
						"rules" => $rules, 
					]);
				}
			}
			break;

			case "materials":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$sort = ["ACTIVE_FROM" => "DESC", "SORT" => "DESC"];
					$filter = ["ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_ACCOUNT_MATERIALS];
					$options = [];

					$materials = [];
					$materials_res = CIBlockElement::GetList($sort, $filter, false, $options);
					while ($materials_ob_element = $materials_res->GetNextElement())
					{
						$materials_ar_res = $materials_ob_element->GetFields();
						$materials_ar_res['PROPERTIES'] = $materials_ob_element->GetProperties();

						$f = CFile::GetByID($materials_ar_res['PROPERTIES']['FILE']['VALUE']);

						$materials[] = [
							"name" => $materials_ar_res['NAME'], 
							"description" => $materials_ar_res['PREVIEW_TEXT'], 
							"filename" => $f->Fetch()['ORIGINAL_NAME'], 
							"url" => "https://".SITE_SERVER_NAME.CFile::GetPath($materials_ar_res['PROPERTIES']['FILE']['VALUE']), 
						];
					}

					print json_encode([
						"materials" => $materials, 
					]);
				}
			}
			break;

			case "support":
			{
				switch($PARAM_3)
				{
					case "themes":
					{
						if(CModule::IncludeModule('iblock'))
						{
							$sort = ["ACTIVE_FROM" => "DESC", "SORT" => "DESC"];
							$filter = ["ACTIVE" => "Y", "IBLOCK_ID" => IBLOCK_ID_ACCOUNT_SUPPORT];
							$options = [];

							$themes = [];
							$themes_res = CIBlockSection::GetList( [ "SORT" => "ASC" ], [ 'IBLOCK_ID' => IBLOCK_ID_ACCOUNT_SUPPORT, 'GLOBAL_ACTIVE' => 'Y', ], false, );
							while($theme_result = $themes_res->GetNext())
							{
								$theme = ["id" => md5($theme_result['NAME']), "name" => $theme_result['NAME']];

								$question_filter = [ 'IBLOCK_ID' => IBLOCK_ID_ACCOUNT_SUPPORT, 'SECTION_ID' => $theme_result['ID'], 'ACTIVE' => 'Y', ];

								if(isset($REQ['query']) && !empty($REQ['query']))
								{
									$question_filter[ 'SEARCHABLE_CONTENT' ] = '%'.$REQ['query'].'%';
								}

								$questions = [];
								$questions_res = CIBlockElement::GetList([ "SORT" => "ASC" ], $question_filter, false, []);
								while ($questions_ob_element = $questions_res->GetNextElement())
								{
									$questions_ar_res = $questions_ob_element->GetFields();
									$questions_ar_res['PROPERTIES'] = $questions_ob_element->GetProperties();

									$templates = [];
									if(gettype($questions_ar_res['PROPERTIES']['TEMPLATE_FILE']['VALUE']) === "array" && count($questions_ar_res['PROPERTIES']['TEMPLATE_FILE']['VALUE']) > 0)
									{
										foreach($questions_ar_res['PROPERTIES']['TEMPLATE_FILE']['VALUE'] AS $file_id)
										{
											$f = CFile::GetByID($file_id);

											$file = [
												"filename" => $f->Fetch()['ORIGINAL_NAME'], 
												"url" => "https://".SITE_SERVER_NAME.CFile::GetPath($file_id), 
											];
											$file['extension'] = strtoupper(get_ext_from_mime($f->arResult[0]['CONTENT_TYPE']));

											$templates[] = $file;
										}
									}

									$documents = null;

									$question = [
										"theme_id" => md5($theme['name']), 
										"theme" => $theme['name'], 
										"id" => md5($questions_ar_res['NAME']), 
										"title" => $questions_ar_res['NAME'], 
										"answer" => $questions_ar_res['PREVIEW_TEXT'], 
										"request" => $questions_ar_res['PROPERTIES']['REQUEST']['VALUE_XML_ID'] == "YES" ? true : false, 
										"templates" => gettype($templates) === "array" && count($templates) > 0 ? $templates : null, 
										"documents" => $questions_ar_res['PROPERTIES']['DOCUMENTS']['~VALUE'] !== "" ? $questions_ar_res['PROPERTIES']['DOCUMENTS']['~VALUE']['TEXT'] : null, 
									];

									$questions[] = $question;
								}

								$theme['questions'] = $questions;
								array_push($themes, $theme);
							}

							print json_encode([
								"themes" => $themes, 
							]);
						}
					}
					break;
				}
			}
			break;

			default:
			{
				print json_encode([
					"status" => "error", 
					"error" => "wrong_user_uri", 
					"message" => "Empty user URI", 
				]);

				die();
			}
			break;
		}
	}
	break;

	case "calculation":
	{
		$payload = json_encode([
			"car_price" => $REQ['car_price'], 
			"initial_payment" => $REQ['initial_payment'], 
			"lease_period" => $REQ['lease_period'], 
			"redemption_payment" => $REQ['redemption_payment'], 
		]);

		$c = curl_init();
		curl_setopt($c, CURLOPT_URL, API_HOST."/calculator/");
		curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($c, CURLOPT_TIMEOUT, 30);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($c, CURLOPT_POST, 1);
		curl_setopt($c, CURLOPT_POSTFIELDS, $payload);
		curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

		$response = curl_exec($c) or die(curl_error($c));
		curl_close($c);

		print $response;

		die();
	}
	break;

	case "vizitka":
	{
		$c = curl_init();
		curl_setopt($c, CURLOPT_URL, API_HOST."/site/GetUserBusinessCard/?guid=".$_REQUEST['guid']);
		curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($c, CURLOPT_TIMEOUT, 30);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

		$response = curl_exec($c) or die(curl_error($c));

		curl_close($c);
		print $response;

		die();
	}
	break;

	case "preapproval":
	{
		$payload = [ 
			"inn" => $_REQUEST['vat'], 
		];

		$payload_json = json_encode($payload);

		$c = curl_init();
		curl_setopt($c, CURLOPT_URL, API_HOST."/site/FindClientInDatabase?inn=".$_REQUEST['vat']);
		curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($c, CURLOPT_TIMEOUT, 30);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

		$response = curl_exec($c);
		$response_decoded = json_decode($response, true);
		curl_close($c);

		print json_encode([
			"client" => $response_decoded['client_status'], 
		]);

		die();
	}
	break;

	case "feedbacks":
	{
		switch($PARAM_2)
		{
			case "add":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$auth = (array) \Bitrix\Main\Web\JWT::decode($REQ['token'], $secret_crm, ["HS256"]);

					$rs_user = \CUser::GetByLogin($auth['login']);
					$ar_user = $rs_user->Fetch();

					$company_res = CIBlockElement::GetList([ 'id' => 'desc' ], [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, 'CODE' => $auth['acc_number'] ], false, []);
			
					while ($company_element = $company_res->GetNextElement())
					{
						$company_record = $company_element->GetFields();
						$company_record['PROPERTIES'] = $company_element->GetProperties();
					}

					$feedback_properties = [
						"NAME" => "Отзыв от ".date("Y.m.d H:i:s"), 
						"CLIENT" => $company_record['ID'], 
						"CLIENT_CODE" => $auth['acc_number'], 
						"USER" => $ar_user['ID'], 
						"PERSON" => $REQ['name'], 
						"PHONE" => $REQ['phone'], 
						"EVALUATION" => $REQ['rating'], 
						"COMPANY_NAME" => $company_record['NAME'], 
						"COMPANY_INN" => $company_record['PROPERTIES']['INN']['VALUE'], 
					];

					$ar_new_feedback = [
						'IBLOCK_ID' => IBLOCK_ID_FEEDBACKS, 
						'NAME' => "Отзыв от ".$company_record['NAME']." ".date("Y.m.d H:i:s"), 
						"PREVIEW_TEXT" => $REQ['comment'], 
						'PROPERTY_VALUES' => $feedback_properties, 
						'ACTIVE' => 'Y', // активен
					];

					$new_feedback = new CIBlockElement;
					if($new_feedback_id = $new_feedback->Add($ar_new_feedback))
					{
		
					}

					print json_encode([
						"status" => "success", 
						"auth" => $auth, 
					]);

					die();
				}
			}
			break;

			default:
			{
				die();
			}
			break;
		}
	}
	break;

	default:
	{
		print json_encode([]);

		die();
	}
	break;
}