<?php
// Initialization

function add_dashlet_to_smart_dashboard($boardid = 0, $name = '', $title = '', $args = null)
{
    
    global $db_tables;
    unset($args['nsp']);
    $options = json_encode(array(
        'dargs' => json_encode($args),
        'dashlet_name' => $name,
        'autoscale' => true
    ));

    // Insert dashlet
    $sql = "INSERT INTO " . $db_tables[DB_NAGIOSXI]["dashlets"] . " (id, name, title, dashboard_id, dashlet_id, options, height, width, x, y) VALUES (" .
        "NULL, " .                                                  // id
        "'Dashlet', " .                                             // name
        "'" . escape_sql_param($title, DB_NAGIOSXI) . "', " .       // title
        "'" . escape_sql_param($boardid, DB_NAGIOSXI) . "', " .     // dashboard_id
        "'" . substr(uniqid(),7,12) . "', " .                       // dashlet_id 
        "'" . escape_sql_param($options, DB_NAGIOSXI) . "'," .      // options
        "8, " .                                                     // height
        "14, " .                                                     // width
        "0, " .                                                     // x
        "0" .                                                       // y
        ");";
    exec_sql_query(DB_NAGIOSXI, $sql);
}

function create_smart_dashboard($name, $global=0, $dashboard_id='') {
    global $db_tables;
    if (empty($name)) {
        throw new Exception(_("No name specified!"), 500);
    }
    $global_dashboard_access = get_user_meta(0, 'global_dashboard_access', 1);
    $is_global = 0;
    if ($global_dashboard_access == 3 || is_admin()) {
        $is_global = $global;
    }

    if (strlen($dashboard_id) == 0) {
        $dashboard_id = random_string(6);
    }
    $user_id = $_SESSION['user_id'];

    $sql = "INSERT INTO " . $db_tables[DB_NAGIOSXI]["dashboards"] . " (dashboard_id, name, user_id, is_global) VALUES ('" . escape_sql_param($dashboard_id, DB_NAGIOSXI) . "', '" . escape_sql_param($name, DB_NAGIOSXI) . "', '" . escape_sql_param($user_id, DB_NAGIOSXI) . "', " . escape_sql_param($is_global, DB_NAGIOSXI) . ")";
    exec_sql_query(DB_NAGIOSXI, $sql);

    return [
        "message" => _("Successfully added dashboard"),
        "dashboard_id" => $dashboard_id,
    ];
}

function add_smart_dashlet_to_smart_dashboard($dashlet) {
    global $db_tables;
    $dashboard_id = escape_sql_param($dashlet["dashboard_id"], DB_NAGIOSXI);
    $title = escape_sql_param($dashlet["title"], DB_NAGIOSXI);
    $name = escape_sql_param($dashlet["name"], DB_NAGIOSXI);
    $options = escape_sql_param($dashlet["options"], DB_NAGIOSXI);
    $height = escape_sql_param($dashlet["height"], DB_NAGIOSXI);
    $width = escape_sql_param($dashlet["width"], DB_NAGIOSXI);
    $x = escape_sql_param($dashlet["x"], DB_NAGIOSXI);
    $y = escape_sql_param($dashlet["y"], DB_NAGIOSXI);
    $dashlet_id = '';
    if (array_key_exists("dashlet_id", $dashlet)) {
        $dashlet_id = escape_sql_param($dashlet["dashlet_id"], DB_NAGIOSXI); 
    }
    if (!$dashlet_id || strlen($dashlet_id) == 0) {
        $dashlet_id = random_string(6);
    }

    $user_id = $_SESSION['user_id'];
        $global_dashboard_access = get_user_meta(0, 'global_dashboard_access', 1);
        $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . "
            WHERE dashboard_id = '" . $dashboard_id . "';";
        $dashboard = exec_sql_query(DB_NAGIOSXI, $sql);
        $board_user_id = $dashboard -> fields["user_id"];
        $board_is_global = $dashboard -> fields["is_global"];

        $sql = "INSERT INTO " . $db_tables[DB_NAGIOSXI]["dashlets"] . " 
          (title, dashboard_id, name, options, height, width, x, y, dashlet_id) 
          VALUES (
              '" . $title . "', 
              '" . $dashboard_id . "', 
              '" . $name . "', 
              '" . $options . "', 
              " . $height . ", 
              " . $width . ", 
              " . $x . ", 
              " . $y . ", 
              '" . $dashlet_id . "'
          )";

        if (is_admin() || $board_user_id == $user_id || ($global_dashboard_access >= 2 && $board_is_global)) {
            exec_sql_query(DB_NAGIOSXI, $sql);
        }

        return ["message" => _("Successfully added dashlet")];
}

function get_host_dashlets($dashboard_id, $host_id, $has_services) {
    if ($has_services) {
        return ([
            [
                'name' => 'PieChart',
                'title' => 'Host Status',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'total',
                    'datatype' => 'host',
                    'host' => $host_id,
                    'group_by' => 'service_status',
                    'ok_enabled' => 'true',
                    'warning_enabled' => 'true',
                    'critical_enabled' => 'true',
                    'unknown_enabled' => 'true',
                ]),
                'height' => 8,
                'width' => 11,
                'x' => 0,
                'y' => 0,
            ],
            [
                'name' => 'Treemap',
                'title' => 'Status Treemap',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'datatype' => 'host',
                    'host' => $host_id,
                    'group_by' => 'service_status',
                    'split_into' => 'service',
                ]),
                'height' => 8,
                'width' => 11,
                'x' => 11,
                'y' => 0,
            ],
            [
                'name' => 'Statistic',
                'title' => 'OK',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'OK',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'service_status',
                    'step_2_option' => 'service_status_host',
                    'step_3_option' => 'service_status_host',
                    'final_step_option' => 'service_status_host_ok',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 22,
                'y' => 0,
            ],
            [
                'name' => 'Statistic',
                'title' => 'Warning',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'Warning',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'service_status',
                    'step_2_option' => 'service_status_host',
                    'step_3_option' => 'service_status_host',
                    'final_step_option' => 'service_status_host_warning',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 30,
                'y' => 0,
            ],
            [
                'name' => 'Statistic',
                'title' => 'Critical',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'Critical',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'service_status',
                    'step_2_option' => 'service_status_host',
                    'step_3_option' => 'service_status_host',
                    'final_step_option' => 'service_status_host_critical',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 38,
                'y' => 0,
            ],
            [
                'name' => 'Statistic',
                'title' => 'Unknown',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'Unknown',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'service_status',
                    'step_2_option' => 'service_status_host',
                    'step_3_option' => 'service_status_host',
                    'final_step_option' => 'service_status_host_unknown',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 22,
                'y' => 4,
            ],
            [
                'name' => 'Statistic',
                'title' => 'Problems',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'Problems',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'service_status',
                    'step_2_option' => 'service_status_host',
                    'step_3_option' => 'service_status_host',
                    'final_step_option' => 'service_status_host_problems',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 30,
                'y' => 4,
            ],
            [
                'name' => 'Statistic',
                'title' => 'Unhandled',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'Unhandled',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'service_status',
                    'step_2_option' => 'service_status_host',
                    'step_3_option' => 'service_status_host',
                    'final_step_option' => 'service_status_host_unhandled',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 38,
                'y' => 4,
            ],
        ]);
    } else {
        return ([
            [
                'name' => 'Statistic',
                'title' => 'Host Status',
                'dashboard_id' => $dashboard_id,
                'options' => json_encode([
                    'label' => 'Host Status',
                    'host_id' => $host_id,
                    'font_size' => '36',
                    'step_1_option' => 'host_status',
                    'step_2_option' => 'host_status_single_host',
                    'final_step_option' => 'host_status_single_host',
                    'match_bg_color' => 'true',
                ]),
                'height' => 4,
                'width' => 8,
                'x' => 0,
                'y' => 0,
            ],
        ]);
    }
}

/** 
 * Generates a dashboard according to the host template in the Smart Dashboard Wizard. 
 * Designed to be used with Configuration Wizards.
 */
function generate_host_dashboard($hostname) {

    if (!is_valid_host_name($hostname)) {
        http_response_code(400);
        return;
    }

    $dashboard_id = random_string(6);
    create_smart_dashboard($hostname, 0, $dashboard_id);
    
    $args = array();
    $args["host_name"] = $hostname;
    $xml_hoststatus = get_xml_host_status($args);
    $host_id = (string) $xml_hoststatus->hoststatus->host_id[0];
    $xml_servicestatus = get_xml_service_objects($args);
    $host_dashlets = get_host_dashlets($dashboard_id, $host_id, count($xml_servicestatus) > 1);
    foreach($host_dashlets as $dashlet) {
        add_smart_dashlet_to_smart_dashboard($dashlet);
    }
    $count = 0;
    foreach ($xml_servicestatus as $service) {
        // Exclude services that do not collect historical data
        $exclusions = [
            'Abnormal Behavior',
        ];
        if ($service->service_description == '' ||
        !$service->service_description ||
        in_array($service->service_description, $exclusions) ||
        strval($host_id) == '' ||
        !strval($host_id) ||
        strval($service['id']) == '' ||
        !strval($service['id'])) {
            continue;
        }
        $dashlet = [
            'name' => 'Graph',
            'title' => $service->service_description,
            'dashboard_id' => $dashboard_id,
            'options' => json_encode([
                'host_id' => strval($host_id),
                'service_id' => strval($service['id']),
                'data_source' => '',
                'time_period' => '',
            ]),
            'height' => 5,
            'width' => 20,
            'x' => $count % 2 == 0 ? 0 : 20,
            'y' => 8,
        ];
        add_smart_dashlet_to_smart_dashboard($dashlet);
        $count +=1;
    }
}
?>