<?
//$_SERVER["DOCUMENT_ROOT"] = __DIR__;
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');

print "\n\n";
print $_SERVER['DOCUMENT_ROOT'];
print "\n\n";

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

$content = file_get_contents(API_HOST."/site/Vehicle/GetModifications", false, stream_context_create($arrContextOptions));
$json = json_decode($content, true);
$brands_and_models = [];

//print "---------------\n\n";
//print_r();
//print "---------------\n\n";

$c = 0;
foreach($json AS $entry)
{
	if(!isset($brands_and_models[ $entry['brand']['id'] ]))
	{
		$brands_and_models[ $entry['brand']['id'] ] = [
			"name" => $entry['brand']['name'], 
			"models" => [ 
				$entry['model']['id'] => [
					"name" => $entry['model']['name'], 
					"modifications" => [ $entry['modification'] ], 
				]
			],
		];
	}
	else
	{
		if(!isset($brands_and_models[ $entry['brand']['id'] ][ 'models' ][ $entry['model']['id'] ]))
		{
			$brands_and_models[ $entry['brand']['id'] ][ 'models' ][ $entry['model']['id'] ] = [
				"name" => $entry['model']['name'], 
				"modifications" => [ $entry['modification'] ], 
			];
		}

		if(!in_array($entry['modification'], $brands_and_models[ $entry['brand']['id'] ][ 'models' ][ $entry['model']['id'] ][ 'modifications' ]))
		{
			array_push($brands_and_models[ $entry['brand']['id'] ][ 'models' ][ $entry['model']['id'] ][ 'modifications' ], $entry['modification']);
		}
	}

	if($c === 0)
	{
		print_r($entry);
	}
	$c++;
}

//print_r($brands_and_models);
//die();
$c = 0;

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

foreach($brands_and_models AS $brand_uid => $brand)
{
	//print $uid." - ".$brand['name']."\n";

	//if($c < 2)
	//{
		$brand_existed = null;
		$brand_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => 8, "PROPERTY_UID" => $brand_uid ], false, ["nPageSize" => 1], ["ID"] );
		while($brand_search_ob = $brand_search_res->GetNextElement())
		{
			$brand_existed = $brand_search_ob->GetFields();
			$bitrix_brands[$brand_uid] = $brand_existed['ID'];
		}

		$code = CUtil::translit( $brand['name'], "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );
		if($brand_existed !== null)
		{
			$brand_update_element = new CIBlockElement;
			$brand_update_payload = [ "IBLOCK_SECTION" => false, "PROPERTY_VALUES" => [ "UID" => $brand_uid ], "NAME" => $brand['name'], "CODE" => $code, "ACTIVE" => "Y", ];
			$brand_update_result = $brand_update_element->Update($brand_existed['ID'], $brand_update_payload);

			$result = models_check($bitrix_models, $bitrix_modifications, $brand_uid, $brand);

			$bitrix_models = $result['bitrix_models'];
			$bitrix_modifications = $result['bitrix_modifications'];
		}
		else
		{
			$brand_element = new CIBlockElement;
			$brand_payload = [ "IBLOCK_SECTION_ID"	=> false, "IBLOCK_ID" => 8, "PROPERTY_VALUES" => [ "UID" => $brand_uid ], "NAME" => $brand['name'], "CODE" => $code, "ACTIVE" => "Y", ];

			if($new_brand_id = $brand_element->Add($brand_payload))
			{
				$bitrix_brands[$brand_uid] = $new_brand_id;
				//echo "new_brand_id: ".$new_brand_id;
			}
			else
			{
				echo "brand error: ".$brand_element->LAST_ERROR;
			}

			$result = models_check($bitrix_models, $bitrix_modifications, $brand_uid, $brand);

			$bitrix_models = $result['bitrix_models'];
			$bitrix_modifications = $result['bitrix_modifications'];
		}

		//print "\n------------------------------\n";
	//}

	$c++;
}

//require_once("../bitrix/modules/main/include/prolog_before.php");
//require_once("../bitrix/modules/main/include/prolog_before.php");
//require_once("../bitrix/modules/main/include/prolog.php");
//require_once('../bitrix/modules/main/cli/bitrix.php');

function models_check($bitrix_models, $bitrix_modifications, $brand_uid, $brand)
{
	foreach($brand['models'] AS $model_uid => $model)
	{
		$model_name = $model['name'];

		$model_existed = null;
		$model_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => 9, "PROPERTY_UID" => $model_uid ], false, ["nPageSize" => 1], ["ID"] );
		while($model_search_ob = $model_search_res->GetNextElement())
		{
			$model_existed = $model_search_ob->GetFields();
			$bitrix_models[$model_uid] = $model_existed['ID'];
		}

		$code = CUtil::translit( $model_name, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

		if($model_existed !== null)
		{
			//print "MODEL ".$model_uid." EXISTED";

			$model_update_element = new CIBlockElement;
			$model_update_payload = [ "IBLOCK_SECTION" => false, "PROPERTY_VALUES" => [ "BRAND_UID" => $brand_uid, "UID" => $model_uid, ], "NAME" => $model_name, "CODE" => $code, "ACTIVE" => "Y", ];
			$model_update_result = $model_update_element->Update($model_existed['ID'], $model_update_payload);
		}
		else
		{
			$model_element = new CIBlockElement;
			$model_payload = [ "IBLOCK_SECTION_ID" => false, "IBLOCK_ID" => 9, "PROPERTY_VALUES" => [ "BRAND_UID" => $brand_uid, "UID" => $model_uid, ], "NAME" => $model_name, "CODE" => $code, "ACTIVE" => "Y", ];

			if($new_model_id = $model_element->Add($model_payload))
			{
				$bitrix_models[$model_uid] = $new_model_id;
				//echo "new_model_id: ".$new_model_id;
			}
			else
			{
				echo "model error: ".$model_element->LAST_ERROR;
			}
		}

		foreach($model['modifications'] AS $modification)
		{
			print "MOD ".$modification."\n";
			$modification_existed = null;

			$NAME = $brand['name']." ".$model_name." ".$modification;
			$CODE = CUtil::translit( $NAME, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

			//"ID"
			$modification_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => 10, "CODE" => $CODE ], false, ["nPageSize" => 1], [] );
			while($modification_search_ob = $modification_search_res->GetNextElement())
			{
				$m_res = $modification_search_ob->GetFields();
				if(isset($m_res['ID']))
				{
					$modification_existed = $m_res['ID'];
					$bitrix_modifications[md5($brand_uid.$model_uid.$modification)] = $m_res['ID'];
				}
			}

			if($modification_existed === null)
			{
				$modification_element = new CIBlockElement;
				$modification_payload = [ "IBLOCK_SECTION_ID" => false, "IBLOCK_ID" => 10, "PROPERTY_VALUES" => [ "MODEL_UID" => $model_uid, "TITLE" => $modification ], "NAME" => $NAME, "CODE" => $CODE, "ACTIVE" => "Y", ];

				if($new_modification_id = $modification_element->Add($modification_payload))
				{
					$bitrix_modifications[md5($brand_uid.$model_uid.$modification)] = $new_modification_id;
				}
				else
				{
					echo "modification error: ".$modification_element->LAST_ERROR;
				}
			}
		}
	}

	return ["bitrix_models" => $bitrix_models, "bitrix_modifications" => $bitrix_modifications];
}

print "bitrix brands\n\n";
print_r($bitrix_brands);

print "bitrix models\n\n";
print_r($bitrix_models);

print "bitrix modifications\n\n";
print_r($bitrix_modifications);

$c = 0;
foreach($json AS $car)
{
	$modification_content = file_get_contents("https://web-api.evoleasing.ru:8443/site/Vehicle/GetCatalog?id=". $car['uid'] ."", false, stream_context_create($arrContextOptions));
	$modification_json = json_decode($modification_content, true);

	$name = "".$car['brand']['name']." ".$car['model']['name']." ".$car['modification']."";
	$code = CUtil::translit( $name, "ru", [ "max_len" => 255, "change_case" => "L", "replace_space" => "-", "replace_other" => "-", ] );

	$PROPERTY_VALUES = [
		"UID" => $car['uid'], 
		"BRAND" => $bitrix_brands[ $car['brand']['id'] ], 
		"MODEL" => $bitrix_models[ $car['model']['id'] ], 
		"MODIFICATION" => $bitrix_modifications[ md5($car['brand']['id'].$car['model']['id'].$car['modification']) ], 
		"MODIFICATION_YEAR" => $car['modificationYear'], 
		"GEAR" => $car['gear'], 
		"DRIVE" => $car['drive'], 
		"BODY" => $car['body'], 
		"ENGINE_POWER" => $car['engine']['power'], 
		"ENGINE_VOLUME" => $car['engine']['volume'], 
		"ENGINE_FUEL" => $car['engine']['fuel'], 
		"PRICE" => $car['price'], 
		"IMAGE_URL" => $car['url'], 
		"COMPLECTATION_BODY" => json_encode($modification_json['body']), 
		"COMPLECTATION_INTERIOR" => json_encode($modification_json['interior']), 
		"COMPLECTATION_SECURITY" => json_encode($modification_json['security']), 
		"COMPLECTATION_GUARANTEE" => json_encode($modification_json['guarantee']), 
		"COMPLECTATION_TECHNICAL_DESCRIPTION" => json_encode($modification_json['technicalDescription']), 
		"COMPLECTATION_FUNCTIONAL_EQUIPMENT" => json_encode($modification_json['functionalEquipment']), 
		"COMPLECTATION_TOTAL_INFORMATION" => json_encode($modification_json['totalInformation']), 
		"LEASING_PROGRAMS" => $car['programms'], 
	];

	//"ID"
	$car_existed = null;
	$car_search_res = CIBlockElement::GetList( [], [ "IBLOCK_ID" => 1, "PROPERTY_UID" => $car['uid'] ], false, ["nPageSize" => 1], [] );

	while($car_search_ob = $car_search_res->GetNextElement())
	{
		$car_existed = $car_search_ob->GetFields();
		//print "CAR FOUND\n\n";
		//print_r($car_existed);
	}

	if($car_existed !== null)
	{
		$car_update_element = new CIBlockElement;
		$car_update_payload = [ "IBLOCK_SECTION" => false, "NAME" => $name, "CODE" => $code, "PROPERTY_VALUES" => $PROPERTY_VALUES, "ACTIVE" => "Y", ];
		$car_update_result = $car_update_element->Update($car_existed['ID'], $car_update_payload);
	}
	else
	{
		//if($c === 0)
		//{
			$car_element = new CIBlockElement;
			$car_payload = [ "IBLOCK_SECTION_ID" => false, "IBLOCK_ID" => 1, "NAME" => $name, "CODE" => $code, "PROPERTY_VALUES" => $PROPERTY_VALUES, "ACTIVE" => "Y", ];

			if($new_car_id = $car_element->Add($car_payload))
			{
				//$bitrix_brands[$brand_uid] = $new_brand_id;
				//echo "new car id: ".$new_car_id;
			}
			else
			{
				echo "brand error: ".$car_element->LAST_ERROR;
			}
		//}
	}

	$c++;
}
print "\n\n".$c."\n\n";

die();


?>