use Bitrix\Main\Composite\Engine;
use Bitrix\Main\Composite\Helper;
IncludeModuleLangFile(__FILE__);
class CAdminInformer
{
	private static $items=array();
	public static $alertCounter = 0;
	/**
	 * Adds items to admin informer
	 * @param array (
	 *			string TITLE  - item title (mandatory),
	 *			string HTML - item's body html (mandatory),
	 *			string FOOTER - item footer,
	 *			string LINK - were to go after click ,
	 *			bool ALERT - true || false - increment or not notification counter in the admin panel,
	 *			string COLOR green || blue || gray || custom... For custom you must define right css styles
	 *						 for css class adm-informer-item-custom.
	 *			int SORT - less value higher message. default value 20. if ALERT then SORT = 10
	 *			)
	 * @return mix items count after adding item or false
	 */
	public static function AddItem($arParams)
	{
		if(!isset($arParams["TITLE"]) || empty($arParams["TITLE"]))
			return false;
		if(!isset($arParams["HTML"]) || empty($arParams["HTML"]))
			return false;
		$item = array(
			"TITLE" => $arParams["TITLE"],
			"HTML" => $arParams["HTML"],
			"FOOTER" => $arParams["FOOTER"] ?? false,
			"LINK" => $arParams["LINK"] ?? false,
			"ALERT" => $arParams["ALERT"] ?? false,
			"COLOR" => $arParams["COLOR"] ?? "green",
		);
		if($arParams["ALERT"])
		{
			$item["SORT"] = 10;
			self::$alertCounter++;
		}
		else
			$item["SORT"] = $arParams["SORT"] ?? 20;
		self::$items[] = $item;
		return count(self::$items)-1;
	}
	private static function PrintItemHtml($itemIdx, $bVisible)
	{
		$itemHtml = '
		
';
		return $itemHtml;
	}
	public static function PrintHtmlPublic($visCountParam = 3)
	{
		if(!$GLOBALS["APPLICATION"]->PanelShowed)
			return "";
		return self::PrintHtml($visCountParam);
	}
	public static function PrintHtml($visCountParam = 3)
	{
		sortByColumn(self::$items, "SORT");
		$itemsCount = 0;
		$visibleCount = 0;
		$div = '
	';
		foreach (self::$items as $key => $item)
		{
			if( $itemsCount < $visCountParam || $item["ALERT"])
			{
				$bVisible = true;
				$visibleCount++;
			}
			else
				$bVisible = false;
			$div .= self::PrintItemHtml($key, $bVisible);
			$itemsCount++;
		}
		$div .= '
	
	
';
	return $div;
	}
	private static function CutErrorId($sError)
	{
		return preg_replace('/\[.*\]/', '', $sError);
	}
	private static function IsUpdateSystemNeedUpdate($sError)
	{
		return mb_strpos($sError, 'NEW_UPDATE_SYSTEM');
	}
	public static function InsertMainItems()
	{
		if(defined('BX_PUBLIC_MODE') && BX_PUBLIC_MODE == 1)
			return false;
		global $USER;
		if(!$USER->IsAuthorized())
			return false;
		if ($USER->CanDoOperation("cache_control") && !Helper::isOn() && !Engine::isSelfHostedPortal())
		{
			self::AddItem(array(
				"TITLE" => GetMessage("top_panel_ai_composite_title"),
				"HTML" => GetMessage("top_panel_ai_composite_desc"),
				"COLOR" => "red",
				"FOOTER" => ''.GetMessage("top_panel_ai_composite_switch_on").'',
				"ALERT" => true,
				"SORT" => 1
			));
		}
		//Updates
		if($USER->IsAdmin() || $USER->CanDoOperation('install_updates'))
		{
			$update_res = UpdateTools::GetUpdateResult();
			$updAIParams = array(
				"TITLE" => GetMessage("top_panel_ai_updates"),
				"COLOR" => 'gray',
				"SORT" => 12
			);
			//update_autocheck == true and we have something to show
			if ($update_res['result'] === true && $update_res['tooltip'])
			{
				$updAIParams["HTML"] = $update_res['tooltip'];
				$updAIParams["FOOTER"] = ''.GetMessage("top_panel_ai_upd_instl").'';
				$updAIParams["ALERT"] = true;
			}
			else if ($update_res['error'] <> '') // update error
			{
				$updAIParams["TITLE"] .= " - ".GetMessage("top_panel_ai_title_err");
				$updAIParams["HTML"] = trim(self::CutErrorId($update_res['error']));
				$updAIParams["FOOTER"] = ''.GetMessage("top_panel_ai_upd_chk").'';
				$updAIParams["ALERT"] = true;
			}
			else // update_autocheck == false
			{
				//last update date time
				$updateDate = COption::GetOptionString("main", "update_system_update", false);
				$updAIParams["HTML"] = ''.GetMessage("top_panel_ai_sys_ver").' '.SM_VERSION."
";
				$updAIParams["HTML"] .= $updateDate ? GetMessage("top_panel_ai_upd_last").'
'.$updateDate : GetMessage("top_panel_ai_upd_never");
				$updAIParams["FOOTER"] = ''.GetMessage("top_panel_ai_upd_chk").'';
				$updAIParams["ALERT"] = false;
			}
			self::AddItem($updAIParams);
		}
		//Disk space (quota)
		$maxQuota = (int)COption::GetOptionInt("main", "disk_space", 0)*1048576;
		if ($maxQuota > 0)
		{
			$quota = new CDiskQuota();
			$free = $quota->GetDiskQuota();
			$freeMB = CFile::FormatSize($free,1);
			$free = round($free/($maxQuota)*100);
			$qAIParams = array(
				"TITLE" => GetMessage("top_panel_ai_used_space"),
				"COLOR" => "green",
				"ALERT" => ($free < 10 ? true : false)
				);
			$qAIParams["HTML"] = '
	
		'.GetMessage("top_panel_ai_in_all").' '.CFile::FormatSize($maxQuota,1).'
		'.GetMessage("top_panel_ai_in_aviable").' '.$freeMB.'
	
	
	'.GetMessage("top_panel_ai_in_recomend").' '.GetMessage("top_panel_ai_in_no").'
';
			self::AddItem($qAIParams);
		}
		if($USER->IsAdmin() && in_array(LANGUAGE_ID, array("ru", "ua")))
		{
			$cModules = COption::GetOptionString("main", "mp_modules_date", "");
			$arModules = array();
			if ($cModules <> '')
			{
				$arModules = unserialize($cModules, ['allowed_classes' => false]) ?: [];
			}
			$mCnt = count($arModules);
			if($mCnt > 0)
			{
				foreach($arModules as $id => $module)
				{
					if(isModuleInstalled($module["ID"]))
					{
						if($module["TMS"]+3600*24*14 < time())
						{
							$script = "
							";
							
							$arParams = array(
								'TITLE' => GetMessage("top_panel_ai_marketplace"),
								'COLOR' => 'green',
								'FOOTER' => "".GetMessage("top_panel_ai_marketplace_hide")."".
									"".GetMessage("top_panel_ai_marketplace_add")."",
								'ALERT' => true,
								'HTML' => GetMessage("top_panel_ai_marketplace_descr", array("#NAME#" => $module["NAME"], "#ID#" => $module["ID"])).$script,
							);
							self::AddItem($arParams);
						}
					}
					else
					{
						unset($arModules[$id]);
					}
				}
				if($mCnt != count($arModules))
				{
					COption::SetOptionString("main", "mp_modules_date", serialize($arModules));
				}
			}
		}
		foreach(GetModuleEvents("main", "OnAdminInformerInsertItems", true) as $arHandler)
			ExecuteModuleEventEx($arHandler);
		return count(self::$items);
	}
}