<?
//define('BX_SECURITY_SESSION_VIRTUAL', true);
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',
];

//$referer = $HEADERS['Referer'] ? $HEADERS['Referer'] : $HEADERS['referer'];
$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);
	//	$HEADERS['X-Full-Url-From-Referer'] = str_replace($origin, "", $referer);
	//	if ($HEADERS['X-Full-Url-From-Referer'] == "") {
	//		$HEADERS['X-Full-Url-From-Referer'] = "/";
	//	}
}

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');

//print_r(json_encode($_SERVER));
//die();

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

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

//$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImNybSJ9.WxzNiB4W5kwqZoy6-kenc1X6Q7XDCVjGraux9rU9zro";
//print \Bitrix\Main\Web\JWT::encode(["username" => "crm"], $secret, 'HS256', $keyId = null, $head = null);
//die();

$auth = [];
//$token = "";

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

function checkRequestIsLocal()
{
	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'];
}

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"]);
		//print json_encode([
		//	"status" => "success", 
		//	"token" => $auth['username'], 
		//]);
		//die();
	}
	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(); }

				$user_registered = false;

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

				if($user_registered)
				{
					print json_encode([
						"status" => "error", 
						"error" => "user_already_registered", 
						"message" => "User already registered", 
					]);
				}
				else
				{
					$user = new \CUser;
					$profile = [
						"XML_ID" => $REQ['crm_id'], 
						"LOGIN" => $REQ['email'], 
						"NAME" => $REQ['firstname'], 
						"SECOND_NAME" => $REQ['secondname'], 
						"LAST_NAME" => $REQ['lastname'], 
						"PASSWORD" => $REQ['password'], 
						"CONFIRM_PASSWORD" => $REQ['password'], 
						"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'], 
					];

					$ID = $user->Add($profile);
					if (intval($ID) > 0)
					{
						\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"
						]);
					}
					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();
			}
			break;

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

				$user_registered = false;

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

					$user = new \CUser;
					$profile = [
						"XML_ID" => $REQ['crm_id'], 
						"LOGIN" => $REQ['email'], 
						"NAME" => $REQ['firstname'], 
						"SECOND_NAME" => $REQ['secondname'], 
						"LAST_NAME" => $REQ['lastname'], 
						"PASSWORD" => $REQ['password'], 
						"CONFIRM_PASSWORD" => $REQ['password'], 
						"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->Update($existed_user['ID'], $profile);

					if($user->LAST_ERROR)
					{
						print json_encode([
							"status" => "error", 
							"error" => "wrong_payload", 
							"message" => $user->LAST_ERROR, 
						]);
					}
					else
					{
						\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"
						]);
					}
				}

				if(!$user_registered)
				{
					print json_encode([
						"status" => "error", 
						"error" => "unknown_user", 
						"message" => "Unknown user", 
					]);
				}

				die();
			}
			break;

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

				die();
			}
			break;
		}
	}
	break;

	case "catalog":
	{
		switch($PARAM_2)
		{
			case "count":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$filter = [ "ACTIVE" => "Y", "IBLOCK_ID" => 1 ];

					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" ], $filter, [], []);

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

			case "brands":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$brands = [];
					$brands_res = CIBlockElement::GetList(["NAME" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => 8], 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'))
				{
					$models = [];
					$models_res = CIBlockElement::GetList(["NAME" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => 9, "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" => 10, "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'))
				{
					$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 "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":
	{
		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;

	case "announcements":
	{
		if(CModule::IncludeModule('iblock'))
		{
			$announcements = [];
			$announcements_res = CIBlockElement::GetList(["SORT" => "ASC"], ["ACTIVE" => "Y", "IBLOCK_ID" => 24], 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 = json_encode([ 
								"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'], 
							]);

							$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);
							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))
							{
								\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", 
								]);
							}
						}
					}
					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
								{
									/*
									\Bitrix\Main\Mail\Event::send([
										"EVENT_NAME" => "USER_INFO",
										"LID" => "s1",
										"C_FIELDS" => Array(
											"EMAIL" => $REQ['email'],
											"ORG_NAME" => $ar_user['UF_ORG_TITLE'],
											"LOGIN" => $REQ['email'],
											"PASS" => $REQ['password'],
										)
									]);
									*/

									print json_encode([
										"status" => "success", 
									]);
								}
							}
							else
							{
								print json_encode([
									"status" => "error", 
									"error" => "wrong_email", 
									"message" => "Wrong email", 
								]);
							}
						}
					}
					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", 
								]);
							}
						}
					}
					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", 
								]);
							}
						}
					}
					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();

							$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'], 
							];

							$company_data = [
								"inn" => $ar_user['UF_INN'], 
								"kpp" => $ar_user['UF_KPP'], 
								"ogrn" => $ar_user['UF_OGRN'], 
								"title" => $ar_user['UF_ORG_TITLE'], 
							];

							print json_encode([
								"status" => "success", 
								"user" => $user_data, 
								"company" => $company_data, 
								"token" => \Bitrix\Main\Web\JWT::encode(["acc_number" => $ar_user['XML_ID']], $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']))
						{
							$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];

								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'], 
									], 
									"company" => [
										"inn" => $ar_user['UF_INN'], 
										"kpp" => $ar_user['UF_KPP'], 
										"ogrn" => $ar_user['UF_OGRN'], 
										"title" => $ar_user['UF_ORG_TITLE'], 
									], 
								]);
							}
							else
							{
								print json_encode([
									"status" => "error", 
								]);
							}
						}
						else
						{
							print json_encode([
								"status" => "error", 
							]);
						}
					}
					break;
				}
				die();
			}
			break;

			case "rules":
			{
				if(CModule::IncludeModule('iblock'))
				{
					$sort = ["ACTIVE_FROM" => "DESC", "SORT" => "DESC"];
					$filter = ["ACTIVE" => "Y", "IBLOCK_ID" => 18];
					$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" => 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" => 21];
					$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" => CFile::GetPath($materials_ar_res['PROPERTIES']['FILE']['VALUE']), 
						];
					}

					print json_encode([
						"materials" => $materials, 
					]);
				}
			}
			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;

	default:
	{
		print json_encode([]);

		die();
	}
	break;
}