<?
define('STOP_STATISTICS', true);
define('NO_KEEP_STATISTIC', 'Y');
define('NO_AGENT_STATISTIC', 'Y');
define('DisableEventsCheck', true);
define('BX_SECURITY_SHOW_MESSAGE', true);
define('NOT_CHECK_PERMISSIONS', true);

$_SERVER['DOCUMENT_ROOT'] = dirname(__DIR__, 1);
require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php'); 
CModule::IncludeModule('iblock');
CModule::IncludeModule('search');
use Bitrix\Main;
use Bitrix\Main\IO;
use Bitrix\Main\SiteTable;
use Bitrix\Main\Localization\Loc;
use Bitrix\Seo\RobotsFile;
use Bitrix\Seo\SitemapIblock;
use Bitrix\Seo\SitemapTable;
use Bitrix\Seo\SitemapIndex;
use Bitrix\Seo\SitemapRuntime;
use Bitrix\Seo\SitemapRuntimeTable;

Main\Loader::includeModule('seo');

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

$api_used_url = API_HOST."/site/GetCatalogIZT";
$content = file_get_contents($api_used_url, false, stream_context_create($arrContextOptions));
print $api_used_url."\n\n";

file_put_contents("get_catalog_izt.json", $content);
$json = json_decode($content, true);

$flags = [];
$flag_names = [ "SPECIAL_OFFER", "LEASING_AVAILABLE", "AFTER_ACCIDENT" ];

foreach($flag_names AS $f)
{
	$properties = CIBlockPropertyEnum::GetList([ "sort" => "asc", "name" => "asc" ], [ "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_USED, "CODE" => $f ]);
	while ($prop_fields = $properties->GetNext())
	{
		$flags[ $f ] = $prop_fields["ID"];
	}
}

print "flags\n";
print_r($flags);

print "\n\n";

foreach($json as $car)
{
	print "CAR\n";
	print_r($car);

	print "\n\n";
}

$api_data = [];
$api_data_titles = [];

$api_types = [];

$bitrix_types = [];
$bitrix_subtypes = [];

$bitrix_brands = [];
$bitrix_models = [];

$bitrix_cars = [];
$api_cars = [];

//prepare brands list from API
foreach($json AS $entry)
{
	$id = strtolower($entry['brand']['id']);
	$name = $entry['brand']['name'];

	if(!isset($api_data[ $id ]))
	{
		$api_data[ $id ] = [
			"name" => $name, 
			"models" => [], 
		];
	}

	if(!isset($api_types[ $entry['vehicle_type'] ]))
	{
		$api_types[ $entry['vehicle_type'] ] = [];
		$api_types[ $entry['vehicle_type'] ][] = $entry['vehicle_subtype'];
	}
	else
	{
		if(!in_array($entry['vehicle_subtype'], $api_types[ $entry['vehicle_type'] ]))
		{
			$api_types[ $entry['vehicle_type'] ][] = $entry['vehicle_subtype'];
		}
	}
}

//prepare models list from API
foreach($json AS $entry)
{
	$brand_id = strtolower($entry['brand']['id']);
	$model_id = strtolower($entry['model']['id']);
	$brand_name = $entry['brand']['name'];
	$model_name = $entry['model']['name'];

	if(!isset($api_data[ $brand_id ]['models'][ $model_id ]))
	{
		$api_data[ $brand_id ]['models'][ $model_id ] = [
			"name" => $model_name, 
		];
	}
}

print_r($api_data);

$types_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_USED_TYPES, ], false, [], [] );
while($type_search_ob = $types_search_res->GetNextElement())
{
	$type_existed = $type_search_ob->GetFields();
	$type_existed['PROPERTIES'] = $type_search_ob->GetProperties();

	$subtypes = [];

	$subtypes_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_USED_SUBTYPES, "PROPERTY_VEHICLE_TYPE" => $type_existed['ID'] ], false, [], [] );
	while($subtype_search_ob = $subtypes_search_res->GetNextElement())
	{
		$subtypes_existed = $subtype_search_ob->GetFields();
		$subtypes[] = $subtypes_existed['ID'];
	}

	$bitrix_types[ $type_existed['NAME'] ] = [
		"ID" => $type_existed['ID'], 
		"SUBTYPES" => $subtypes, 
	];
}

function insert_subtypes($type_id, $subtypes)
{
	print "insert_subtypes, ".$type_id."\n";
	foreach($subtypes AS $subtype_name)
	{
		$code = CUtil::translit( $type_id."_".$subtype_name, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

		$subtype_element = new CIBlockElement;
		$subtype_payload = [ "IBLOCK_ID" => IBLOCK_ID_USED_SUBTYPES, "NAME" => $subtype_name, "CODE" => $code, "PROPERTY_VALUES" => [ "VEHICLE_TYPE" => $type_id ], "ACTIVE" => "Y", ];

		$subtype_element->Add($subtype_payload);
	}
}

foreach($api_types AS $api_type_name => $api_subtypes)
{
	$code = CUtil::translit( $api_type_name, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

	$type_element = new CIBlockElement;
	$type_payload = [ "IBLOCK_ID" => IBLOCK_ID_USED_TYPES, "NAME" => $api_type_name, "CODE" => $code, "ACTIVE" => "Y", ];

	if($type_new_id = $type_element->Add($type_payload))
	{
		insert_subtypes($type_new_id, $api_subtypes);
	}
	else
	{
		insert_subtypes($bitrix_types[ $api_type_name ]['ID'], $api_subtypes);
	}
}

$cars_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_USED, ], false, [], [] );
while($car_search_ob = $cars_search_res->GetNextElement())
{
	$car_existed = $car_search_ob->GetFields();
	$bitrix_cars[$car_existed['CODE']] = $car_existed['ID'];
}

//кешируем список имеющихся в bitrix марок
$bitrix_existed_brands = [];
$api_existed_brands = [];

$brands_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_BRANDS_USED, ], false, [], [] );
while($brand_search_ob = $brands_search_res->GetNextElement())
{
	$brand_existed = $brand_search_ob->GetFields();
	$brand_existed['PROPERTIES'] = $brand_search_ob->GetProperties();

	$bitrix_brands[ $brand_existed['PROPERTIES']['UID']['VALUE'] ] = $brand_existed['ID'];
	$bitrix_existed_brands[] = $brand_existed['ID'];
}

//кешируем список имеющихся в bitrix моделей
$bitrix_existed_models = [];
$api_existed_models = [];

$models_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_MODELS_USED, ], false, [], [] );
while($model_search_ob = $models_search_res->GetNextElement())
{
	$model_existed = $model_search_ob->GetFields();
	$model_existed['PROPERTIES'] = $model_search_ob->GetProperties();

	$bitrix_models[ $model_existed['PROPERTIES']['UID']['VALUE'] ] = $model_existed['ID'];
	$bitrix_existed_models[] = $model_existed['ID'];
}

//добавляем новые марки из api
foreach($api_data AS $brand_uid => $brand)
{
	$code = CUtil::translit( $brand['name'], "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

	$brand_element = new CIBlockElement;
	$brand_payload = [ "IBLOCK_ID" => IBLOCK_ID_BRANDS_USED, "NAME" => $brand['name'], "CODE" => $code, "PROPERTY_VALUES" => [ "UID" => $brand_uid ], "ACTIVE" => "Y", ];

	print $brand['name']." - ".$brand_uid."\n";
	if($brand_new_id = $brand_element->Add($brand_payload))
	{
		$bitrix_brands[ $brand_uid ] = $brand_new_id;
	}
	else
	{
		//обновляем имеющуюся марку в bitrix восстанавливая из скрытого состояния
		$brands_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_BRANDS_USED, "CODE" => $code ], false, [], [] );
		while($brand_search_ob = $brands_search_res->GetNextElement())
		{
			$brand_existed = $brand_search_ob->GetFields();

			$el = new CIBlockElement;
			$el->Update($brand_existed['ID'], ["ACTIVE" => "Y"]);
		}
	}
	print "\n";

	//добавляем новые модели из api
	foreach($brand['models'] AS $model_uid => $model)
	{
		$code = CUtil::translit( $model['name'], "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

		$model_element = new CIBlockElement;
		$model_payload = [ "IBLOCK_ID" => IBLOCK_ID_MODELS_USED, "NAME" => $model['name'], "CODE" => $code, "PROPERTY_VALUES" => [ "BRAND_UID" => $brand_uid, "UID" => $model_uid ], "ACTIVE" => "Y", ];

		if($model_new_id = $model_element->Add($model_payload))
		{
			$bitrix_models[ $model_uid ] = $model_new_id;
		}
		else
		{
			//обновляем имеющуюся модель в bitrix восстанавливая из скрытого состояния
			$models_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_MODELS_USED, "CODE" => $code ], false, [], [] );
			while($model_search_ob = $models_search_res->GetNextElement())
			{
				$model_existed = $model_search_ob->GetFields();
	
				$el = new CIBlockElement;
				$el->Update($model_existed['ID'], ["ACTIVE" => "Y"]);
			}
		}
		print "\n";
	}
}

function resize_image($image, $filename, $width, $height, $quality)
{
	$tempfile = tmpfile();
	fwrite($tempfile, $image);
	$tempfile_metadata = stream_get_meta_data($tempfile);
	$tempfile_filename = $tempfile_metadata['uri'];

	$mime = mime_content_type($tempfile_metadata['uri']);
	$ext = get_ext_from_mime($mime);

	$resized = imagecreatetruecolor($width, $height);
	$source = imagecreatefromstring($image);

	$original_width = imagesx($source);
	$original_height = imagesy($source);

	$panel_width = $width;
	$panel_height = intval($original_height * floatval($width / $original_width));
	$panel = imagecreatetruecolor($panel_width, $panel_height);
	imagecopyresampled($panel, $source, 0, 0, 0, 0, $panel_width, $panel_height, $original_width, $original_height);
	imagecopyresampled($resized, $panel, 0, 0, 0, intval(($panel_height - $height) / 2), $width, $height, $panel_width, $height);

	imagejpeg($resized, $tempfile_filename, $quality);

	imagedestroy($source);
	imagedestroy($resized);
	imagedestroy($panel);

	$file = CFile::MakeFileArray($tempfile_filename);
	$file['name'] = $filename.".".$ext;
	$saved_file_id = CFile::SaveFile($file, "used");

	fclose($tempfile);

	return $saved_file_id;
}

$c = 0;
foreach($json as $car)
{
	$brand_id = strtolower($car['brand']['id']);
	$model_id = strtolower($car['model']['id']);
	$modification_id = md5($brand_id.$model_id.$car['modification']);

	$name = $car['brand']['name']." ".$car['model']['name']." ".$car['modification']." ".$car['year'];
	$code = $car['article'];

	print $car['modification']." - ".$modification_id." | ".$name."\n";

	array_push($api_existed_brands, $bitrix_brands[ $brand_id ]);
	array_push($api_existed_models, $bitrix_models[ $model_id ]);

	$PROPERTY_VALUES = [
		"CONTRACT" => $car['article'], 

		"VEHICLE_TYPE" => $car['vehicle_type'], 
		"VEHICLE_SUBTYPE" => $car['vehicle_subtype'], 
		"BRAND" => $bitrix_brands[ $brand_id ], 
		"MODEL" => $bitrix_models[ $model_id ], 
		"MODIFICATION" => $car['modification'], 

		"VIN" => $car['vin'], 
		"YEAR" => $car['year'], 
		"MILEAGE" => isset($car['mileage']) && !empty($car['mileage']) ? $car['mileage'] : 0, 
		"ENGINE_HOURS" => isset($car['engine_hours']) && !empty($car['engine_hours']) ? $car['engine_hours'] : 0, 

		"ENGINE_POWER" => $car['engine']['power'], 
		"ENGINE_VOLUME" => $car['engine']['volume'], 
		"ENGINE_FUEL" => mb_strtolower($car['engine']['fuel']), 

		"PARKING_CITY" => $car['parking_city'], 
		"PARKING_REGION" => $car['parking_region'], 

		"PRICE" => isset($car['price']) && !empty($car['price']) ? $car['price'] : 0, 
		"PRICE_WITH_DISCOUNT" => isset($car['price_with_discount']) && !empty($car['price_with_discount']) ? $car['price_with_discount'] : 0,

		"RESERVE_DATE" => $car['reserve_date'], 
		"SPECIAL_OFFER" => $car['special_offer'] ? $flags['SPECIAL_OFFER'] : null, 
		"LEASING_AVAILABLE" => $car['leasing_available'] ? $flags['LEASING_AVAILABLE'] : null, 
		"AFTER_ACCIDENT" => $car['after_accident'] ? $flags['AFTER_ACCIDENT'] : null, 
	];

	$used_car_element = new CIBlockElement;
	$used_car_payload = [ "IBLOCK_SECTION_ID" => false, "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_USED, "NAME" => $name, "CODE" => $code, "DETAIL_TEXT" => $car['description'], "PROPERTY_VALUES" => $PROPERTY_VALUES, "ACTIVE" => "Y", ];

	print $code."\n";
	$api_cars[] = $code;

	if($new_used_car_id = $used_car_element->Add($used_car_payload))
	{
		//добавляем новое предложение в bitrix
		$images = zerof_get_images($code);

		if(count($images) > 0)
		{
			$photo_property_value = null;
			$photos_1080_property_values = [];
			$photos_480_property_values = [];
			$photos_120_property_values = [];

			foreach($images AS $k => $image)
			{
				$saved_file_id_1080 = resize_image($image, $code."_".($k + 1)."_1080", 1440, 1080, 60);
				$saved_file_id_480 = resize_image($image, $code."_".($k + 1)."_480", 640, 480, 60);
				$saved_file_id_120 = resize_image($image, $code."_".($k + 1)."_120", 160, 120, 60);

				$photos_1080_property_values[] = [ "VALUE" => $saved_file_id_1080, ];
				$photos_480_property_values[] = [ "VALUE" => $saved_file_id_480, ];
				$photos_120_property_values[] = [ "VALUE" => $saved_file_id_120, ];

				if($k === 0)
				{
					$photo_property_value = resize_image($image, $code."_".($k + 1)."_500", 500, 300, 60);
				}
			}

			CIBlockElement::SetPropertyValueCode($new_used_car_id, "PHOTO", $photo_property_value);
			CIBlockElement::SetPropertyValueCode($new_used_car_id, "PHOTOS_1080", $photos_1080_property_values);
			CIBlockElement::SetPropertyValueCode($new_used_car_id, "PHOTOS_480", $photos_480_property_values);
			CIBlockElement::SetPropertyValueCode($new_used_car_id, "PHOTOS_120", $photos_120_property_values);
		}

		print "\n";
	}
	else
	{
		//обновляем имеющуюся запись в bitrix восстанавливая из скрытого состояния
		$cars_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => IBLOCK_ID_CATALOG_CARS_USED, "CODE" => $code ], false, [], [] );
		while($car_search_ob = $cars_search_res->GetNextElement())
		{
			$car_existed = $car_search_ob->GetFields();

			$el = new CIBlockElement;
			$el->Update($car_existed['ID'], ["ACTIVE" => "Y", "NAME" => $name, "SORT" => 500]);

			CIBlockElement::SetPropertyValuesEx($car_existed['ID'], IBLOCK_ID_CATALOG_CARS_USED, $PROPERTY_VALUES, []);
		}
	}

	$c++;
}

//скрываем предложения, которые есть в bitrix но которых более нет в api
foreach($bitrix_cars AS $code => $car_id)
{
	print "CAR ".$code." => ".$car_id."\n";
	if(!in_array($code, $api_cars))
	{
		$el = new CIBlockElement;
		$el->Update($car_id, ["ACTIVE" => "N", "SORT" => 1]);
	}
}

//скрываем марки, которые есть в bitrix но которых более нет в api
foreach($bitrix_existed_brands AS $brand_id)
{
	print "BRAND ".$ibrand_idd."\n";
	if(!in_array($brand_id, $api_existed_brands))
	{
		$el = new CIBlockElement;
		$el->Update($brand_id, ["ACTIVE" => "N"]);
	}
}

//скрываем модели, которые есть в bitrix но которых более нет в api
foreach($bitrix_existed_models AS $model_id)
{
	print "MODEL ".$model_id."\n";
	if(!in_array($model_id, $api_existed_models))
	{
		$el = new CIBlockElement;
		$el->Update($model_id, ["ACTIVE" => "N"]);
	}
}