<?php

/*
 * Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * For more information : contact@centreon.com
 *
 */

require_once realpath(__DIR__ . '/../../../../../config/centreon.config.php');
require_once realpath(__DIR__ . '/../../../../../bootstrap.php');
require_once _CENTREON_PATH_ . 'www/class/centreonXMLBGRequest.class.php';

CentreonSession::start();
$sid = session_id();
if (! isset($sid) || ! isset($_GET['refresh_rate'])) {
    exit;
}

$refreshRate = (int) $_GET['refresh_rate'] / 1000;
$refreshRate += ($refreshRate / 2);

$obj = new CentreonXMLBGRequest($dependencyInjector, $sid, 1, 1, 0, 1);

$centreon = $_SESSION['centreon'] ?? null;

if (! isset($_SESSION['centreon'])) {
    exit;
}
if (! isset($obj->session_id) || ! CentreonSession::checkSession($sid, $obj->DB)) {
    exit;
}

if (! isset($_SESSION['centreon_notification_preferences'])) {
    $userId = $centreon->user->get_id();
    $resPref = $obj->DB->prepare("SELECT cp_key, cp_value
        FROM contact_param
        WHERE cp_key LIKE 'monitoring%notification%'
        AND cp_contact_id = :cp_contact_id");
    $resPref->bindValue(':cp_contact_id', (int) $userId, PDO::PARAM_INT);
    $resPref->execute();
    $notificationPreferences = [];
    while ($rowPref = $resPref->fetch()) {
        $notificationPreferences[$rowPref['cp_key']] = $rowPref['cp_value'];
    }
    $_SESSION['centreon_notification_preferences'] = $notificationPreferences;
} else {
    $notificationPreferences = $_SESSION['centreon_notification_preferences'];
}
$notificationEnabled = false;
foreach ($notificationPreferences as $key => $value) {
    if (preg_match('/monitoring_(host|svc)_notification_/', $key) && ! is_null($value) && $value == 1) {
        $notificationEnabled = true;
        break;
    }
}

if ($notificationEnabled === false) {
    $obj->XML->startElement('data');
    $obj->XML->endElement();
    $obj->header();
    $obj->XML->output();

    return;
}

$serviceStateLabel = [0 => 'OK', 1 => 'Warning', 2 => 'Critical', 3 => 'Unknown'];
$serviceClassLabel = [0 => 'success', 1 => 'warning', 2 => 'error', 3 => 'alert'];
$hostStateLabel = [0 => 'Up', 1 => 'Down', 2 => 'Unreachable'];
$hostClassLabel = [0 => 'success', 1 => 'error', 2 => 'alert'];

$sql = "SELECT name, description, s.state
        FROM services s, hosts h %s
        WHERE h.host_id = s.host_id
        AND h.name NOT LIKE '\_Module\_%%'
        AND (description NOT LIKE 'meta\_%%' AND description NOT LIKE 'ba\_%%')
        AND s.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ")
        AND s.scheduled_downtime_depth=0
        AND s.acknowledged=0
        %s
        UNION
        SELECT 'Meta Service', s.display_name, s.state
        FROM services s, hosts h %s
        WHERE h.host_id = s.host_id
        AND h.name LIKE '\_Module\_Meta%%'
        AND description LIKE 'meta\_%%'
        AND s.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ")
        AND s.scheduled_downtime_depth=0
        AND s.acknowledged=0
        %s
        UNION
        SELECT 'Business Activity', s.display_name, s.state
        FROM services s, hosts h %s
        WHERE h.host_id = s.host_id
        AND h.name LIKE '\_Module\_BAM%%'
        AND description LIKE 'ba\_%%'
        AND s.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ")
        AND s.scheduled_downtime_depth=0
        AND s.acknowledged=0
        %s
        UNION
        SELECT name, NULL, h.state
        FROM hosts h %s
        WHERE name NOT LIKE '\_Module\_%%'
        AND h.last_hard_state_change > (UNIX_TIMESTAMP(NOW()) - " . (int) $refreshRate . ')
        AND h.scheduled_downtime_depth=0
        AND h.acknowledged=0
        %s';
if ($obj->is_admin) {
    $sql = sprintf($sql, '', '', '', '', '', '', '', '');
} else {
    $sql = sprintf(
        $sql,
        ', centreon_acl acl',
        'AND acl.service_id = s.service_id AND acl.host_id = h.host_id '
        . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr),
        ', centreon_acl acl',
        'AND acl.service_id = s.service_id AND acl.host_id = h.host_id '
        . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr),
        ', centreon_acl acl',
        'AND acl.service_id = s.service_id AND acl.host_id = h.host_id '
        . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr),
        ', centreon_acl acl',
        'AND acl.host_id = h.host_id' . $obj->access->queryBuilder('AND', 'acl.group_id', $obj->grouplistStr)
    );
}
$res = $obj->DBC->query($sql);
$obj->XML->startElement('data');
while ($row = $res->fetch()) {
    $obj->XML->startElement('message');
    if ($row['description']) {
        if (isset($notificationPreferences['monitoring_svc_notification_' . $row['state']])) {
            $obj->XML->writeAttribute(
                'output',
                sprintf(
                    '%s / %s is %s',
                    $row['name'],
                    $row['description'],
                    $serviceStateLabel[$row['state']]
                )
            );
            $obj->XML->writeAttribute(
                'class',
                $serviceClassLabel[$row['state']]
            );
        }
        if (
            ! isset($_SESSION['disable_sound'])
            && isset($notificationPreferences['monitoring_sound_svc_notification_' . $row['state']])
            && $notificationPreferences['monitoring_sound_svc_notification_' . $row['state']]
        ) {
            $obj->XML->writeAttribute(
                'sound',
                $notificationPreferences['monitoring_sound_svc_notification_' . $row['state']]
            );
        }
    } else {
        if (isset($notificationPreferences['monitoring_host_notification_' . $row['state']])) {
            $obj->XML->writeAttribute(
                'output',
                sprintf(
                    '%s is %s',
                    $row['name'],
                    $hostStateLabel[$row['state']]
                )
            );
            $obj->XML->writeAttribute(
                'class',
                $hostClassLabel[$row['state']]
            );
        }
        if (
            ! isset($_SESSION['disable_sound'])
            && isset($notificationPreferences['monitoring_sound_host_notification_' . $row['state']])
            && $notificationPreferences['monitoring_sound_host_notification_' . $row['state']]
        ) {
            $obj->XML->writeAttribute(
                'sound',
                $notificationPreferences['monitoring_sound_host_notification_' . $row['state']]
            );
        }
    }
    $obj->XML->endElement();
}
$obj->XML->endElement();

$obj->header();
$obj->XML->output();
