<?php
class NagiosIncidentIntegrationPlugIn implements iApplicationUIExtension
{
	protected static $m_bIsModified = false;

	public function OnDisplayProperties($oObject, WebPage $oPage, $bEditMode = false)
	{
	}


	public function OnDisplayRelations($oObject, WebPage $oPage, $bEditMode = false)
	{
    	if ($bEditMode || !($oObject instanceof Incident)) {
        	return;
    	}

    	$aTargetClasses = MetaModel::GetModuleSetting('itop-nagios-incident-integration', 'target_classes', array());
    	$bIsTarget = false;
    	foreach ($aTargetClasses as $sTargetClass) {
        	if ($oObject instanceof $sTargetClass) { $bIsTarget = true; break; }
    	}
    	if (!$bIsTarget) return;

    	// --- Find a CI linked to the Incident ---
    	// This relation class name varies by iTop configuration/version.
    	// Commonly: lnkFunctionalCIToTicket or lnkFunctionalCIToIncident.
    	$oLinks = new DBObjectSet(DBObjectSearch::FromOQL(
        	"SELECT lnkFunctionalCIToTicket WHERE ticket_id = :ticket_id"
    	), array(), array('ticket_id' => $oObject->GetKey()));

    	$sNagiosHost = '';
    	if ($oLinks->Count() > 0) {
        	$oLink = $oLinks->Fetch();
        	$oCI = MetaModel::GetObject('FunctionalCI', $oLink->Get('functionalci_id'), false);
        	if ($oCI) {
            	// Use whatever attribute matches your Nagios host naming scheme
            	$sNagiosHost = $oCI->Get('name'); // or 'hostname', 'fqdn', etc.
        	}
    	}

    	$oPage->SetCurrentTab(Dict::S('UI:MonitoringTab'));

    	if ($sNagiosHost === '') {
        	$oPage->add("<div class='warning'>No CI linked, cannot determine Nagios host.</div>");
        	return;
    	}

    	// Build URL (example Nagios classic CGI)
    	$sBase = MetaModel::GetModuleSetting('itop-nagios-incident-integration', 'nagios_url', '');
    	// e.g. nagios_url = "https://nagios.example.com/cgi-bin/status.cgi?host=%s"
    	$sUrl = sprintf($sBase, rawurlencode($sNagiosHost));

    	$sUrl = htmlspecialchars($sUrl, ENT_QUOTES, 'UTF-8');
    	$oPage->add("<iframe width='100%' height='700' src='$sUrl'></iframe>");
	}

	public function OnFormSubmit($oObject, $sFormPrefix = '')
	{
	}

	public function OnFormCancel($sTempId)
	{
	}

	public function EnumUsedAttributes($oObject)
	{
		return array();
	}

	public function GetIcon($oObject)
	{
		return '';
	}

	public function GetHilightClass($oObject)
	{
		// Possible return values are:
		// HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
		return HILIGHT_CLASS_NONE;
	}

	public function EnumAllowedActions(DBObjectSet $oSet)
	{
		// No action
		return array();
	}
}
