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

recent_alerts();
function recent_alerts() {
	$title = _('Recent Alerts');
	child_page($title, 'home');

    $alerts_per_page = grab_request_var('alerts_per_page', 10);
    $server_filter = grab_request_var('server', 0);
    $host_filter = grab_request_var('host', 0);
    $service_filter = grab_request_var('service', 0);
    $state_filter = grab_request_var('state', 0);
    $state_type_filter = grab_request_var('state_type', 0);

    global $dashlets;
	$recent_alerts_dashlet = empty($dashlets['recent_alerts']) ? false : $dashlets['recent_alerts'];

	if (!$recent_alerts_dashlet)
		exit();

    $dashlet = $recent_alerts_dashlet;
    $dashlet[DASHLET_PARAMS] = array();
    $dashlet[DASHLET_ID] = "recent_alerts_inline";
    $dashlet[DASHLET_PARAMS_VAR] = "recent_alerts_inline_params";
    $dashlet[DASHLET_PARAMS] = recent_alert_dashlet_params();

    $dashlet[DASHLET_PARAMS]['server']['val'] = intval($server_filter);
    $dashlet[DASHLET_PARAMS]['alerts_per_page']['val'] = intval($alerts_per_page);
    $dashlet[DASHLET_PARAMS]['host']['val'] = $host_filter;
    $dashlet[DASHLET_PARAMS]['service']['val'] = $service_filter;
    $dashlet[DASHLET_PARAMS]['state']['val'] = $state_filter;
    $dashlet[DASHLET_PARAMS]['state_type']['val'] = $state_type_filter;
?>

	<div class="well top" style="display: flex;">
		<h1 style="width: min-content; text-wrap: nowrap;"><?php echo _('Recent Alerts'); ?></h1>
        <form action="" id="recent_alerts_filter_form" style="width: 100%; display: flex; flex-wrap: wrap; align-items: end; justify-content: end; margin: 0;">
            <?php echo build_filter_form($dashlet); ?>

            <div style="display: flex; flex-direction: column; padding-left: 4px">
                <a hidden id="reset_recent_alerts_filters" href="recent_alerts.php" target="">
                    Reset Filters
                </a>            
                <button type="submit" class="button form-control">Apply Filters</button>
            </div>
        </form>
	</div>

    <script>
        $(document).ready(function(){
            if(!location.href.endsWith('recent_alerts.php'))
                $('#reset_recent_alerts_filters').show()

            function hide_filter(filter_id) {
                $("#"+filter_id).value = 0
                $("#"+filter_id+"-container").css('width', '0px')
                $("#"+filter_id+"-container").css('padding-left', '0px')
                $("#"+filter_id+"-container").css('visibility', 'hidden')
            }

            function show_filter(filter_id) {
                $("#"+filter_id+"-container").css('width', '120px')
                $("#"+filter_id+"-container").css('padding-left', '4px')
                $("#"+filter_id+"-container").css('visibility', 'visible')
            }

            if ($("#server").val() == 0) {
                hide_filter("host")
            }
            if ($("#host").val() == 0) {
                hide_filter("service")
            }
            
            $("#server-container").on('change', function(event) {
                let server_container_val = event.target.value

                if (server_container_val != 0) {
                    show_filter("host")
                } else {
                    hide_filter("host")
                    hide_filter("service")
                }
            })
            $("#host-container").on('change', function(event) {
                let host_container_val = event.target.value

                if (host_container_val != 0) {
                    show_filter("service")
                } else {
                    hide_filter("service")
                }
            })
        })
    </script>

    <?php
    echo '<div style="margin: 30px 20px;">';
	echo get_inline_dashlet_html($dashlet, true, true);
	echo '</div>';
}


function build_filter_form($dashlet = array()) {

    if (empty($dashlet[DASHLET_PARAMS])|| empty($dashlet[DASHLET_PARAMS_VAR])) {
        return false;
    }

    $html = '';

    // now we need to start a tad bit of javascript to accompany the form
    $params_var = $dashlet[DASHLET_PARAMS_VAR];
    $javascript = "\nvar {$params_var} = {\n";
    $dependent_javascript = '';

    if (isset($dashlet[DASHLET_PARAMS])) {
        $dashlet[DASHLET_PARAMS] = get_dashlet_params($dashlet[DASHLET_PARAMS]);
        if ($dashlet[DASHLET_PARAMS] === false) {
            return false;
        }
    }
    // loop through the dashlet_vars and build a javascript params_var for this dashlet
    // while building the table itself
    foreach ($dashlet[DASHLET_PARAMS] as $param => $data) {
        // some defaults
        $orig_param = $param;
        $param = encode_html($param);
        $id = $param;
        $name = $param;
        $val = '';
        $options = array();

        // update the javascript params list with this id correlated to this param
        $javascript .= "\t\"$param\" : \"$id\",\n";

        // now get the real variable data if it exists
        if (!empty($data['name']))
            $name = encode_html($data['name']);
        if (isset($data['val']))
            $val = encode_html($data['val']);
        if (!empty($data['options']) && is_array($data['options']) && count($data['options']) > 0)
            $options = $data['options'];

        // sort the options
        if (!empty($options)) {
            foreach ($options as $opts_index => $opts_val) {
                if (is_array($opts_val)) {
                    asort($options[$opts_index]);
                }
            }
        }

        // was a dependent field mentioned?
        // if so, the select needs to be blank until the dependent field has chosen a value
        // we need to create the javascript for such an occasion
        if (isset($data['dependent'])) {
            $dependent = $data['dependent'];
            $dependent_id = encode_html($dependent);

            // the javascript for when the dependent field changes
            $dependent_javascript .= "
                $(function() { 
                    $('#{$dependent_id}').change(function() {

                        var {$dependent_id}_var = " . json_encode($options) . "

                        // does this element exist in the var
                        if (typeof {$dependent_id}_var[$(this).val()] !== 'undefined') {

                            $('#{$id}').find('option').remove();

                            for (var el in {$dependent_id}_var[$(this).val()]) {
                                var el_val = {$dependent_id}_var[$(this).val()][el];
                                $('#{$id}').append('<option value=\"' + el + '\">' + el_val + '</option>');
                            }
                        }
                    });
                });\n";


            if (isset($dashlet[DASHLET_PARAMS][$dependent]['val']) && isset($options[$dashlet[DASHLET_PARAMS][$dependent]['val']]))
                $options = $options[$dashlet[DASHLET_PARAMS][$dependent]['val']];
            else {
                $options = array('' => '');

            // make sure we force it to change if there isn't any data already
            $dependent_javascript .= "
                $(function() { 
                    $('#{$dependent_id}').change();
                });\n";
            }
        }

        $html .= '<div id="'. $id .'-container" style="display: flex; flex-direction: column; padding-left: 4px;">';
        $html .= '<label for="' . $id . '">' . $name . '</label>' . "\n";

        // easy peazy. just a text box
        if (empty($options)) {

            $html .= 
                '<input type="text" id="' . $id . '" data-default="' . $val . '" value="' . $val . '" class="form-control textfield" />';

        // this will be a select box with populated options
        } else {
            $html .=
                '<select style="width: 120px;" name="' . $param .'" id="' . $id . '" data-default="' . $val . '" class="dropdown form-control">';

            // options
            foreach ($options as $option_val => $option_name) {

                $html .= '<option value="' . encode_html($option_val) . '"';

                if ((string) $option_val == $val)
                    $html .= ' selected="selected"';

                $html .= '>' . encode_html($option_name) . '</option>';
            }

            $html .= '</select>';
        }
        $html .= '</div>';
    }

    // trim the trailing newline and comma from js_params and close it off
    $javascript = rtrim($javascript, ",\n") . "\n}\n";

    // add all the javascript
    $html .= '<script type="text/javascript">' . $javascript . "\n" . $dependent_javascript . '</script>';

    return $html;
}