<?php
require_once(dirname(__FILE__) . '/../dashlet-helper.inc.php');

dashlets_data_check();
recent_alerts_dashlet();

function recent_alerts_dashlet() {
    $alerts_per_page = grab_request_var('alerts_per_page', 10);
    $current_page_number = intval(grab_request_var('current_page_number', 1));
    $offset = $alerts_per_page * ($current_page_number-1);

    $server_filter = grab_request_var('server', 0);
    $host_filter = grab_request_var('host', 0);
    if ($host_filter != 0) {
        // we need to speparate the host from the prefixed server identifier -AC
        $host_filter = explode("++", $host_filter)[1];
    }

    $service_filter = grab_request_var('service', 0);
    $state_filter = grab_request_var('state', 0);
    $state_type_filter = grab_request_var('state_type', 0);

    $all_recent_alerts = array();
	$recent_alerts = array();
	$servers = get_servers();
	foreach ($servers as $server) {

		$alert_list = get_server_polled_key($server, 'alert_list');
		$alert_list = array_map('alert_list_to_human_readable', $alert_list);

		if (count($alert_list) > 0) {
			foreach ($alert_list as $index => $alerts) {
				if (isset($alerts['alert_list'])) {
					foreach ($alerts['alert_list'] as $alert) {
                        
                        if ($server_filter != 0 && $server['server_id'] != $server_filter) continue;
                        if ($host_filter != 0 && $alert['host'] != $host_filter) continue;
                        if ($service_filter != 0 && $alert['service'] != $service_filter) continue;
                        if ($state_filter != 0 && $alert['state'] != $state_filter) continue;
                        if ($state_type_filter != 0 && $alert['state_type'] != $state_type_filter) continue;

						if (isset($alert['time'])) {
                            $alert['server_id'] = $server['server_id'];
							$alert['server_name'] = $server['name'];
							$alert['time'] = strtotime($alert['time']);

							$recent_alerts[] = $alert;
						}
					}
				}
			}
		}
	}


	usort($recent_alerts, 'sort_alerts_by_time');
	
    $all_recent_alerts = $recent_alerts;
    
    $max_page_num = ceil(count($all_recent_alerts)/$alerts_per_page);

    if (count($recent_alerts) > $alerts_per_page)
	 	$recent_alerts = array_slice($recent_alerts, $offset, $alerts_per_page);
?>
    <style>
        table.alerts th { cursor: pointer; }
        .content-overflow {
            overflow: auto !important;
        }
    </style>
    <script type="text/javascript">
        $(function() {
            $("table.alerts").tablesorter({ });
        });

        $(document).ready(function() {
            var current_page_number = <?php echo $current_page_number ?>;
            const max_page_num = <?php echo $max_page_num ?>;
            $('.recent_alerts_next_button').on('click', function() {
                if (current_page_number < max_page_num) {
                    var next_page_number = current_page_number + 1;
                    dashlet_load_url($(this).parents('.dashlet'), {current_page_number: next_page_number});
                }
            })
            $('.recent_alerts_prev_button').on('click', function() {
                if ((current_page_number - 1) >= 1) {
                    var prev_page_number = current_page_number - 1;
                    dashlet_load_url($(this).parents('.dashlet'), {current_page_number: prev_page_number});
                }
            })
        });
    </script>
    
    <div style="width: 100%; display: flex; gap: 4px; justify-content: end; align-items: center; margin-bottom: 8px; overflow: auto;">
        <div><?php echo "Page: ".$current_page_number." of ".$max_page_num." (".count($all_recent_alerts)." total alerts)";?></div>
        <button class="button form-control recent_alerts_prev_button" id="recent_alerts_prev_button">Prev</button>
        <button class="button form-control recent_alerts_next_button" id="recent_alerts_next_button">Next</button>
    </div>
    <table class="tactical alerts table table-no-margin table-condensed table-striped table-bordered host_status_summary_dashlet borderless service_status_summary_dashlet borderless infotable">
        <thead>
            <tr>
                <th><?php echo _('Server'); ?></th>
                <th><?php echo _('Time'); ?></th>
                <th><?php echo _('Host'); ?></th>
                <th><?php echo _('Service'); ?></th>
                <th><?php echo _('State'); ?></th>
                <th><?php echo _('State Type'); ?></th>
                <th><?php echo _('Output'); ?></th>
            </tr>
        </thead>
        <tbody id="recent_alerts_table_body">
            <?php
            	if (count($recent_alerts) > 0) {
                    foreach ($recent_alerts as $alert) {
                        recent_alerts_dashlet_build_row($alert);
                    }
                } else {
                    echo '<tr><td colspan="7" style="text-align: center;">' . _('You have no recent alerts!') . '</td></tr>';
                }
            ?>
        </tbody>
    </table>
    <div style="width: 100%; display: flex; gap: 4px; justify-content: end; align-items: center; margin-top: 8px;">
        <div><?php echo "Page: ".$current_page_number." of ".$max_page_num." (".count($all_recent_alerts)." total alerts)";?></div>
        <button class="button form-control recent_alerts_prev_button" id="recent_alerts_prev_button">Prev</button>
        <button class="button form-control recent_alerts_next_button" id="recent_alerts_next_button">Next</button>
    </div>
<?php
    ob_get_contents();
}

function recent_alerts_dashlet_build_row($alert) {

	// we need all this
	if (   !isset($alert['time']) 
        || !isset($alert['server_id'])
		|| !isset($alert['server_name']) 
		|| !isset($alert['host']) 
		|| !isset($alert['state']) 
		|| !isset($alert['state_type']) 
		|| !isset($alert['type'])
		|| !isset($alert['output']))
		return;

	$alert['time'] = date('Y-m-d H:i:s', $alert['time']);

	if (empty($alert['service']))
		$alert['service'] = '';

	$state_class = '';
	switch ($alert['type']) {
        case NSLOG_HOST_UP:
            $state_class = 'havehostup';
            break;

        case NSLOG_HOST_DOWN:
            $state_class = 'havehostdown';
            break;
        
        case NSLOG_HOST_UNREACHABLE:
            $state_class = 'havehostunreachable';
            break;
        
        case NSLOG_SERVICE_OK:
            $state_class = 'haveserviceok';
            break;
        
        case NSLOG_SERVICE_WARNING:
            $state_class = 'haveservicewarning';
            break;
        
        case NSLOG_SERVICE_CRITICAL:
            $state_class = 'haveservicecritical';
            break;
        
        case NSLOG_SERVICE_UNKNOWN:
            $state_class = 'haveserviceunknown';
            break;
    }

    foreach ($alert as $key => $value) {
        $alert[$key] = encode_form_val($value);
    }

    if (!empty($state_class))
    	$state_class = ' class="recent_alerts_state_data ' . $state_class . '"';

    $server_link = get_server_base_url($alert['server_id'], $core_include_cgi = false);
    $server_link = '<a href="' . $server_link . '" target="_blank">' . $alert['server_name'] . '</a>';

    $host_link = get_tactical_link($alert['host'], $alert['server_id'], 
    "includes/components/xicore/status.php?show=hostdetail&host=" . urlencode($alert['host']),
    "extinfo.cgi?type=1&host=" . urlencode($alert['host']));

    $service_link = '';
    if (!empty($alert['service']))
        $service_link = get_tactical_link($alert['service'], $alert['server_id'],
            "includes/components/xicore/status.php?show=servicedetail&dest=auto&host=" . urlencode($alert['host']) . "&service=" . urlencode($alert['service']),
            "extinfo.cgi?type=2&host=" . urlencode($alert['host']) . "&service=" . urlencode($alert['service']));

	echo '
		<tr>
			<td class="recent_alerts_server_link_data">' . $server_link . '</td>
			<td>' . $alert['time'] . '</td>
			<td>' . $host_link . '</td>
			<td>' . $service_link . '</td>
			<td ' . $state_class . '>' . $alert['state'] . '</td>
			<td>' . $alert['state_type'] . '</td>
			<td>' . $alert['output'] . '</td>
		</tr>';
}

function sort_alerts_by_time($a, $b) {

	if (!empty($a['time']) && !empty($b['time']))
		return $a['time'] < $b['time'];

	return false;
}
