<?
$_SERVER['DOCUMENT_ROOT'] = '/home/bitrix/www/'; // на один уровень выше, чем /cron/
define('NO_KEEP_STATISTIC', true);
define('NOT_CHECK_PERMISSIONS',true);
define('SITE_ID', 's1');
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
require($DOCUMENT_ROOT.'/bitrix/modules/main/include/prolog_before.php');
?>

<?
$xmlbody = '<?xml version="1.0" encoding="UTF-8"?><data><cars>';
$i = 0;
$today = date("d.m.Y");
CModule::IncludeModule("iblock");

$arFilter = Array("IBLOCK_ID"=>2, "ACTIVE"=>"Y");

$res = CIBlockElement::GetList(Array("SORT"=>"ASC"), $arFilter, false, Array("nPageSize"=>10000));

while ($ob = $res->GetNextElement())
	{
	$arFields = $ob->GetFields();
	$arFields['PROPERTIES'] = $ob->GetProperties();

	$brand = CIBlockElement::GetByID($arFields["PROPERTIES"]["BRAND"]["VALUE"]);
	$ar_brand = $brand->GetNext();

	$model = CIBlockElement::GetByID($arFields["PROPERTIES"]["MODEL"]["VALUE"]);
	$ar_model = $model->GetNext();

	if ($arFields["PROPERTIES"]["PRICE_WITH_DISCOUNT"]["VALUE"]!=0){
		$money = $arFields["PROPERTIES"]["PRICE_WITH_DISCOUNT"]["VALUE"];
	}
	else {
		$money = $arFields["PROPERTIES"]["PRICE"]["VALUE"];
	}

	$arResult['PHOTOS_1080'] = [];
	foreach($arFields['PROPERTIES']['PHOTOS_1080']['VALUE'] AS $photo_id)
	{
		array_push($arResult['PHOTOS_1080'], CFile::GetPath($photo_id));
	}

	if(!empty($arResult["PHOTOS_1080"][0])){
		$xmlbody .= '
				<car>
					<mark_id>'.$ar_brand['NAME'].' в лизинг.</mark_id>
					<folder_id>'.$ar_model['NAME'].'</folder_id>
					<modification_id>'.$arFields["PROPERTIES"]["MODIFICATION"]["VALUE"].'</modification_id>
					<url>https://www.evoleasing.ru/izt/'.$arFields["PROPERTIES"]["CONTRACT"]["VALUE"].'/</url>
					<availability>в наличии</availability>
					<custom>растаможен</custom>
					<run>'.$arFields["PROPERTIES"]["MILEAGE"]["VALUE"].'</run>
					<year>'.$arFields["PROPERTIES"]["YEAR"]["VALUE"].'</year>
					<price>'.$money.'</price>
					<currency>RUR</currency>
					<vin>'.$arFields["PROPERTIES"]["VIN"]["VALUE"].'</vin>
					<unique_id>'.$arFields["PROPERTIES"]["CONTRACT"]["VALUE"].'</unique_id>
					<images>';

		for($im = 0; $im < 5; $im++) {
			if(!empty($arResult["PHOTOS_1080"][$im])){
					$curfoto = $arResult["PHOTOS_1080"][$im];
					$xmlbody .= '<image>https://www.evoleasing.ru'.$curfoto.'</image>';
			}	
		}
			
					
		$xmlbody .= '</images>
					<description>Распродажа изъятого лизингового имущества. Можно в лизинг или за наличные. Скидки!</description>
				</car>';
		$i++;
	}
}

$xmlbody .= '</cars></data>';

$file = $_SERVER["DOCUMENT_ROOT"] . "/upload/docs/usedxml.xml";

$handle = fopen($file, "w+");//Открываем для записи в конец.
if (!$handle) {
  echo "Oшибка: файл не создался-".$text;
} else {
  fputs ($handle, $xmlbody); 
  fclose($handle);
	echo "Ok! Сохранено по <a href='https://www.evoleasing.ru/upload/docs/usedxml.xml'>ссылке!</a> ".$today;
}
?>
<?require($DOCUMENT_ROOT.'/bitrix/modules/main/include/epilog_after.php');?>