<?

function get_related($iblock_id, $id)
{
	$res = CIBlockElement::GetList(Array("NAME" => "ASC"), Array("IBLOCK_ID" => $iblock_id, "ID" => $id, ), false, Array("nPageSize" => 1000));

	$ar_res = Array();
	while ($obElement = $res->GetNextElement())
	{
		$ar_res = $obElement->GetFields();
		$ar_res['PROPERTIES'] = $obElement->GetProperties();
	}

	return $ar_res;
}

function get_related_array($iblock_id, $ids)
{
	$ar_res = Array();

	foreach($ids AS $id)
	{
		$res = CIBlockElement::GetList(Array("NAME" => "ASC"), Array("IBLOCK_ID" => $iblock_id, "ID" => $id, ), false, Array("nPageSize" => 1000));

		while ($obElement = $res->GetNextElement())
		{
			$ar_res_element = $obElement->GetFields();
			$ar_res_element['PROPERTIES'] = $obElement->GetProperties();
			$ar_res[] = $ar_res_element;
		}
	}

	return $ar_res;
}

function get_related_array_with_filter($iblock_id, $ids, $filter = [])
{
	$ar_res = Array();

	$query_filter = Array("IBLOCK_ID" => $iblock_id, "ID" => $id, );
	$query_filter = array_merge($query_filter, $filter);

	foreach($ids AS $id)
	{
		$res = CIBlockElement::GetList(Array("NAME" => "ASC"), $query_filter, false, Array("nPageSize" => 1000));

		while ($obElement = $res->GetNextElement())
		{
			$ar_res_element = $obElement->GetFields();
			$ar_res_element['PROPERTIES'] = $obElement->GetProperties();
			$ar_res[] = $ar_res_element;
		}
	}

	return $ar_res;
}

function get_ext_from_mime($mime)
	{
	$mime_map = [
		'application/x-compressed' => '7zip',
		'image/bmp' => 'bmp',
		'image/x-bmp' => 'bmp',
		'image/x-bitmap' => 'bmp',
		'image/x-xbitmap' => 'bmp',
		'image/x-win-bitmap' => 'bmp',
		'image/x-windows-bmp' => 'bmp',
		'image/ms-bmp' => 'bmp',
		'image/x-ms-bmp' => 'bmp',
		'application/bmp' => 'bmp',
		'application/x-bmp' => 'bmp',
		'application/x-win-bitmap' => 'bmp',
		'text/x-comma-separated-values' => 'csv',
		'text/comma-separated-values' => 'csv',
		'application/vnd.msexcel' => 'csv',
		'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
		'application/x-msdownload' => 'exe',
		'image/gif' => 'gif',
		'application/x-gzip' => 'gzip',
		'text/html' => 'html',
		'image/jpeg' => 'jpeg',
		'image/pjpeg' => 'jpeg',
		'application/pdf' => 'pdf',
		'application/octet-stream' => 'pdf',
		'image/png' => 'png',
		'image/x-png' => 'png',
		'application/powerpoint' => 'ppt',
		'application/vnd.ms-powerpoint' => 'ppt',
		'application/vnd.ms-office' => 'ppt',
		'application/msword' => 'doc',
		'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
		'application/x-rar' => 'rar',
		'application/rar' => 'rar',
		'application/x-rar-compressed' => 'rar',
		'text/rtf' => 'rtf',
		'text/richtext' => 'rtx',
		'application/x-tar' => 'tar',
		'application/x-gzip-compressed' => 'tgz',
		'image/tiff' => 'tiff',
		'text/plain' => 'txt',
		'application/excel' => 'xl',
		'application/msexcel' => 'xls',
		'application/x-msexcel' => 'xls',
		'application/x-ms-excel' => 'xls',
		'application/x-excel' => 'xls',
		'application/x-dos_ms_excel' => 'xls',
		'application/xls' => 'xls',
		'application/x-xls' => 'xls',
		'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
		'application/vnd.ms-excel' => 'xlsx',
		'application/xml' => 'xml',
		'text/xml' => 'xml',
		'text/xsl' => 'xsl',
		'application/xspf+xml' => 'xspf',
		'application/x-zip' => 'zip',
		'application/zip' => 'zip',
		'application/x-zip-compressed' => 'zip',
		'application/s-compressed' => 'zip',
		'multipart/x-zip' => 'zip',
	];

	return isset($mime_map[ $mime ]) ? $mime_map[ $mime ] : false;
}

function mb_ucfirst($string)
{
	$string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
	return $string;
}

use Bitrix\Main\Diag\ExceptionHandlerFormatter;

class HttpExceptionHandlerOutput extends \Bitrix\Main\Diag\HttpExceptionHandlerOutput
{
	public function renderExceptionMessage($exception, $debug = false)
	{
		if ($debug)
		{
			echo ExceptionHandlerFormatter::format($exception, true);
		}
		else
		{
			global $APPLICATION;
			$APPLICATION->RestartBuffer();
			$APPLICATION->__view = [];

			include($_SERVER["DOCUMENT_ROOT"] . "/local/templates/500/header.php");
			include $_SERVER['DOCUMENT_ROOT'] . '/500.php';
			include($_SERVER["DOCUMENT_ROOT"] . "/local/templates/500/footer.php");

			CHTTP::SetStatus("500 Internal Server Error");
		}
	}
}

AddEventHandler("main", "OnEpilog", "OnEpilogHandler", 1);
function OnEpilogHandler()
{
	if (defined('ERROR_404') && ERROR_404 == 'Y')
	{
		global $APPLICATION;
		$APPLICATION->RestartBuffer();
		include $_SERVER['DOCUMENT_ROOT'].'/local/templates/404/header.php';
		include $_SERVER['DOCUMENT_ROOT'].'/404.php';
		include $_SERVER['DOCUMENT_ROOT'].'/local/templates/404/footer.php';
	}
}

\Bitrix\Main\Application::getInstance()->getExceptionHandler()->setHandlerOutput(new HttpExceptionHandlerOutput());

function zerof_request($path, $query)
{
	$key_sha1 = strtoupper(sha1(ZEROF_PASSWORD, false));

	$date = gmdate('D, d M Y H:i:s T');
	$string_to_sign = "";
	$string_to_sign .= "GET\n";
	$string_to_sign .= "\n";
	$string_to_sign .= $date."\n";
	$string_to_sign .= $path;

	$data = mb_convert_encoding($string_to_sign, mb_detect_encoding($string_to_sign), "UTF-8");
	$hash = hash_hmac("SHA1", $data, $key_sha1, false);
	$hash_base64 = base64_encode(hex2bin($hash));

	$headers = [ 
		"Authorization: ZWS ".ZEROF_USERNAME.":".$hash_base64, 
		"Date: ".$date, 
		"Accept: application/json", 
	];

	$url = "https://api.zerof.ru".$path;
	if($query !== null)
	{
		$url = $url."?".http_build_query($query);
	}

	$request = curl_init();
	curl_setopt($request, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
	curl_setopt($request, CURLOPT_URL, $url);
	curl_setopt($request, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($request, CURLOPT_TIMEOUT, 30);
	curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($request, CURLOPT_HTTPHEADER, $headers);

	$response = curl_exec($request) or die(curl_error($request));
	$http_code = curl_getinfo($request, CURLINFO_HTTP_CODE);

	curl_close($request);

	return $http_code === 200 ? $response : false;
}

function zerof_get_images($task_uid)
{
	$images = [];
	$tasks_car_in_new 		= zerof_request("/v2/tasks/find", [ "status" => "new", "value" => $task_uid, "profile" => 703 ]);
	$tasks_car_in_process 	= zerof_request("/v2/tasks/find", [ "status" => "process", "value" => $task_uid, "profile" => 703 ]);
	$tasks_car_in_pass 		= zerof_request("/v2/tasks/find", [ "status" => "pass", "value" => $task_uid, "profile" => 703 ]);
	$tasks_trucks_in_new 		= zerof_request("/v2/tasks/find", [ "status" => "new", "value" => $task_uid, "profile" => 704 ]);
	$tasks_trucks_in_process 	= zerof_request("/v2/tasks/find", [ "status" => "process", "value" => $task_uid, "profile" => 704 ]);
	$tasks_trucks_in_pass 		= zerof_request("/v2/tasks/find", [ "status" => "pass", "value" => $task_uid, "profile" => 704 ]);

	$tasks_car_in_process_data = json_decode(html_entity_decode($tasks_car_in_process), true);
	$tasks_car_in_pass_data = json_decode(html_entity_decode($tasks_car_in_pass), true);
	$tasks_car_in_new_data = json_decode(html_entity_decode($tasks_car_in_new), true);
	$tasks_trucks_in_process_data = json_decode(html_entity_decode($tasks_trucks_in_process), true);
	$tasks_trucks_in_pass_data = json_decode(html_entity_decode($tasks_trucks_in_pass), true);
	$tasks_trucks_in_new_data = json_decode(html_entity_decode($tasks_trucks_in_new), true);

	$tasks = array_merge(
		$tasks_car_in_process_data[array_keys($tasks_car_in_process_data)[0]], 
		$tasks_car_in_pass_data[array_keys($tasks_car_in_pass_data)[0]], 
		$tasks_car_in_new_data[array_keys($tasks_car_in_new_data)[0]], 
		$tasks_trucks_in_process_data[array_keys($tasks_trucks_in_process_data)[0]], 
		$tasks_trucks_in_pass_data[array_keys($tasks_trucks_in_pass_data)[0]], 
		$tasks_trucks_in_new_data[array_keys($tasks_trucks_in_new_data)[0]], 
	);

	print "\n".$task_uid." TASKS:\n";
	print_r($tasks[0]);
	if(isset($tasks[0]))
	{
		$task_string = zerof_request("/v2/tasks/".$tasks[0]['id'], null);
		$task = json_decode(html_entity_decode($task_string), true);

		print "TASK:\n";
		print_r($task);

		foreach($task['views'][0]['files'] AS $file)
		{
			$image = zerof_request("/v2/tasks/downloadfile", [ "id" => $tasks[0]['id'], "name" => $file['name'] ]);
			print_r("DOWNLOADED LEN OF IMAGE FILE: ".strlen($image));
			print "\n";
			if(strlen($image) < 100)
			{
				print "IMAGE ???? ".$image."\n\n";
			}

			if($image)
			{
				array_push($images, $image);
			}
		}

		print "\n";
		print "\n";
	}
	print "\n";

	return $images;
}

function advertiser_request($url, $payload)
{
	//mbJmM6sDCeFHBb8zFEhc4pIeYLLE0Tch
	$headers = [ 
		"Authorization: ZWS ".ADVERTISER_TOKEN."", 
		'accept: application/json', 
		'content-type: application/json', 
	];

	$request = curl_init();
	curl_setopt($request, CURLOPT_TIMEOUT, 900);
	curl_setopt($request, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
	curl_setopt($request, CURLOPT_URL, $url);
	curl_setopt($request, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($request, CURLOPT_POSTFIELDS, json_encode($payload));
	curl_setopt($request, CURLOPT_HTTPHEADER, $headers);

	$response = curl_exec($request) or die(curl_error($request));
//	$http_code = curl_getinfo($request, CURLINFO_HTTP_CODE);

	curl_close($request);

	return json_decode($response, true);
	//return $http_code === 200 ? $response : false;
}

AddEventHandler("iblock", 	"OnBeforeIBlockElementAdd", 	"OnBeforeIBlockElementAddHandler");
AddEventHandler("iblock", 	"OnAfterIBlockElementAdd", 		"OnAfterIBlockElementAddHandler");
AddEventHandler("iblock", 	"OnBeforeIBlockElementUpdate", 	"OnBeforeIBlockElementUpdateHandler");

function OnBeforeIBlockElementAddHandler(&$arFields)
{
	$iblocks_array = [
		IBLOCK_ID_SPECIALS => "specials", 
		IBLOCK_ID_NEWS => "news", 
		IBLOCK_ID_SLIDER => "slider", 
		IBLOCK_ID_SPECIAL_OFFERS_BANNERS => "special_offers_banner", 
		IBLOCK_ID_SPECIAL_OFFERS_CARS => "special_offers_car_banner", 
		IBLOCK_ID_BANNERS_INNER => "banner_inner", 
	];

	if(array_key_exists($arFields['IBLOCK_ID'], $iblocks_array))
	{
		file_put_contents($_SERVER['DOCUMENT_ROOT']."/element_add.txt", var_export($arFields, true));

		$res = CIBlock::GetProperties($arFields['IBLOCK_ID'], [], []);
		$properties = [];

		while($res_arr = $res->GetNext())
		{
			$properties[$res_arr['CODE']] = $res_arr['ID'];
		}

		if(isset($properties['ADVERTISING']))
		{
			if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING']]))
			{
				//снимаем элемент с публикации по умолчанию
				$arFields['ACTIVE'] = "N";
			}
			else
			{
				$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']] = [ 'n0' => [ 'VALUE' => '' ]];
			}
		}
	}

	return true;
}

function OnAfterIBlockElementAddHandler(&$arFields)
{
	$iblocks_array = [
		IBLOCK_ID_SPECIALS => "specials", 
		IBLOCK_ID_NEWS => "news", 
		IBLOCK_ID_SLIDER => "slider", 
		IBLOCK_ID_SPECIAL_OFFERS_BANNERS => "special_offers_banner", 
		IBLOCK_ID_SPECIAL_OFFERS_CARS => "special_offers_car_banner", 
		IBLOCK_ID_BANNERS_INNER => "banner", 
	];

	if(array_key_exists($arFields['IBLOCK_ID'], $iblocks_array))
	{
		if(isset($properties['ADVERTISING']))
		{
			if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING']]))
			{
				if(!is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']]))
				{
					//если ERIR пуст
					//запускаем получение ЕРИР
					$arFields['ACTIVE'] = "Y";
					$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']] = [ array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']])[0] => [ 'VALUE' => '' ]];
				}
			}
		}

		$res = CIBlock::GetProperties($arFields['IBLOCK_ID'], [], []);
		$properties = [];

		while($res_arr = $res->GetNext())
		{
			$properties[$res_arr['CODE']] = $res_arr['ID'];
		}

		if(isset($properties['ADVERTISING']))
		{
			if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING']]))
			{
				//запускаем получение ЕРИР
				$element = new CIBlockElement;
				$result = $element->Update($arFields['ID'], [ "ACTIVE" => "Y" ]);
		
				CIBlockElement::SetPropertyValuesEx($arFields['ID'], $arFields['IBLOCK_ID'], [
					"ADVERTISING_ERIR" => "12345", 
					"ADVERTISING_SAMPLE_URL" => "67890", 
				], []);

				//ставим элемент на публикацию
				$arFields['ACTIVE'] = "Y";
			}
		}
	}

	return true;
}

function OnBeforeIBlockElementUpdateHandler(&$arFields)
{
	$iblocks_array = [
		IBLOCK_ID_SLIDER => "slider", 
		IBLOCK_ID_NEWS => "news", 
		IBLOCK_ID_SPECIALS => "special", 
		IBLOCK_ID_SPECIAL_OFFERS_BANNERS => "special_offers_banner", 
		IBLOCK_ID_SPECIAL_OFFERS_CARS => "special_offers_car_banner", 
		IBLOCK_ID_BANNERS_INNER => "banner", 
		IBLOCK_ID_CATALOG_CARS_USED => "izt", 
	];

	if(array_key_exists($arFields['IBLOCK_ID'], $iblocks_array))
	{
		$res = CIBlock::GetProperties($arFields['IBLOCK_ID'], [], []);
		$properties = [];

		while($res_arr = $res->GetNext())
		{
			$properties[$res_arr['CODE']] = $res_arr['ID'];
		}

		if(isset($properties['ADVERTISING']))
		{
			if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING']]))
			{
				if($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']][array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']])[0]]['VALUE'] === "")
				{
					//это реклама, ЕРИР нет и его надо получить
					/*
					CIBlockElement::SetPropertyValuesEx($arFields['ID'], $arFields['IBLOCK_ID'], [
						"ADVERTISING_ERIR" => "12345", 
						"ADVERTISING_SAMPLE_URL" => "67890", 
					], []);
					*/

					$payload = [
						"id" => $arFields['ID'], 
						"name" => $arFields['NAME'], 
					];

					switch($arFields['IBLOCK_ID'])
					{
						case IBLOCK_ID_SLIDER:
						{
							$k = array_keys($arFields['PROPERTY_VALUES'][$properties['URL']])[0];
							$payload['url'] = "https://".ADVERTISER_DOMAIN."".$arFields['PROPERTY_VALUES'][$properties['URL']][$k]['VALUE'];
						}
						break;

						case IBLOCK_ID_SPECIALS:
						{
							$payload['code'] = $arFields['CODE'];
							$payload['url'] = "https://".ADVERTISER_DOMAIN."/special/".$arFields['CODE'];
						}
						break;

						case IBLOCK_ID_NEWS:
						{
							$payload['code'] = $arFields['CODE'];
							$payload['url'] = "https://".ADVERTISER_DOMAIN."/news/".$arFields['CODE'];
						}
						break;

						case IBLOCK_ID_SPECIAL_OFFERS_BANNERS:
						{
							$k = array_keys($arFields['PROPERTY_VALUES'][$properties['OFFER']])[0];
							$offer = get_related(IBLOCK_ID_SPECIALS, $arFields['PROPERTY_VALUES'][$properties['OFFER']][$k]['VALUE']);
							$payload['url'] = "https://".ADVERTISER_DOMAIN.$offer['DETAIL_PAGE_URL'];
						}
						break;

						case IBLOCK_ID_SPECIAL_OFFERS_CARS:
						{
							$payload['url'] = "https://".ADVERTISER_DOMAIN."/special/";
						}
						break;

						case IBLOCK_ID_BANNERS_INNER:
						{
							$k = array_keys($arFields['PROPERTY_VALUES'][$properties['URL']])[0];
							$payload['url'] = "https://".ADVERTISER_DOMAIN."".$arFields['PROPERTY_VALUES'][$properties['URL']][$k]['VALUE'];
						}
						break;

						case IBLOCK_ID_CATALOG_CARS_USED:
						{
							$payload['code'] = $arFields['CODE'];
							$payload['url'] = "https://".ADVERTISER_DOMAIN."/izt/".$arFields['CODE'];
						}
						break;

						default:
						break;
					}

					$response = advertiser_request(ADVERTISER_URL."/".$iblocks_array[$arFields['IBLOCK_ID']], $payload);

					if($response['status'] === "success")
					{
//						file_put_contents($_SERVER['DOCUMENT_ROOT']."/adv_arfields.txt", var_export($arFields, true));
//						file_put_contents($_SERVER['DOCUMENT_ROOT']."/adv_properties.txt", var_export($properties, true));

						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']] = [ "".array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']])[0]."" => [ 'VALUE' => $response['erir'] ] ];
						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_URL']] = [ "".array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_URL']])[0]."" => [ 'VALUE' => $response['sample'] ] ];	
						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_ID']] = [ "".array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_ID']])[0]."" => [ 'VALUE' => $response['sample_id'] ] ];	
					}
					else
					{
						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING']] = '';
						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']] = '';
						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_URL']] = '';
						$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_ID']] = '';
						$arFields['ACTIVE'] = 'N';
					}
				}
			}
			else
			{
				//очистка ЕРИР и образца
				if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']]))
				{
					$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']] = [ "".array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_ERIR']])[0]."" => [ 'VALUE' => '' ] ];
				}
				if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_URL']]))
				{
					$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_URL']] = [ "".array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_URL']])[0]."" => [ 'VALUE' => '' ] ];
				}
				if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_ID']]))
				{
					$arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_ID']] = [ "".array_keys($arFields['PROPERTY_VALUES'][$properties['ADVERTISING_SAMPLE_ID']])[0]."" => [ 'VALUE' => '' ] ];
				}
			}
		}
	}

	/*
	$res = CIBlock::GetProperties($arFields['IBLOCK_ID'], [], []);
	$properties = [];

	while($res_arr = $res->GetNext())
	{
		$properties[$res_arr['CODE']] = $res_arr['ID'];
	}

	if(isset($properties['ADVERTISING']))
	{
		if(is_array($arFields['PROPERTY_VALUES'][$properties['ADVERTISING']]))
		{

		}
	}
	file_put_contents($_SERVER['DOCUMENT_ROOT']."/iblock_properties.txt", var_export($properties, true));
	*/

	return true;
}

?>