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

if(CModule::IncludeModule('iblock'))
{
	$filter = [ 'IBLOCK_ID' => IBLOCK_ID_CLIENTS, ];
	//$filter['<ID'] = 103891;

	$existed_client_as_user_res = CIBlockElement::GetList([ 'ID' => 'ASC' ], $filter, false, []);

	while ($existed_client_as_user_element = $existed_client_as_user_res->GetNextElement())
	{
		$existed_client_as_user_record = $existed_client_as_user_element->GetFields();
		$existed_client_as_user_record['PROPERTIES'] = $existed_client_as_user_element->GetProperties();

		print $existed_client_as_user_record['ID']." - ".$existed_client_as_user_record['CODE']."\n";

		$fixed_admins = [];
		$fixed_users = [];
		$fix = false;
		$wrong_ids = [ 124, 5077, 3899, 5141 ];

		foreach($existed_client_as_user_record['PROPERTIES']['ADMINS']['VALUE'] AS $k => $v)
		{
			print $v."\n";
			if(!in_array($v, $wrong_ids))
			{
				array_push($fixed_admins, $v);
			}
			else
			{
				$fix = true;
			}
		}

		foreach($existed_client_as_user_record['PROPERTIES']['USERS']['VALUE'] AS $k => $v)
		{
			print $v."\n";
			if(!in_array($v, $wrong_ids))
			{
				array_push($fixed_users, $v);
			}
			else
			{
				$fix = true;
			}
		}

		if($fix)
		{
			print_r($fixed_admins)."\n";
			print_r($fixed_users)."\n";
	
			print "--------------\n";
	
			print "UPDATE!";
			CIBlockElement::SetPropertyValuesEx($existed_client_as_user_record['ID'], IBLOCK_ID_CLIENTS, [ "ADMINS" => $fixed_admins, "USERS" => $fixed_users, ], []);
		}
		else
		{
			print "ALL GOOD";
		}
	}
}

die();