<?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
 *
 */

/**
 * format and add debug in CentreonXML
 *
 * @param CentreonXML $xml
 * @param mixed[] $tabs
 * @return int
 */
function printDebug($xml, array $tabs): int
{
    global $pearDB, $ret, $centreon, $nagiosCFGPath;

    $DBRESULT_Servers = $pearDB->query(
        "SELECT `nagios_bin` FROM `nagios_server`
        WHERE `localhost` = '1' ORDER BY ns_activate DESC LIMIT 1"
    );
    $nagios_bin = $DBRESULT_Servers->fetch();
    $DBRESULT_Servers->closeCursor();
    $msg_debug = [];

    $tab_server = [];
    foreach ($tabs as $tab) {
        if (isset($ret['host']) && ($ret['host'] == 0 || in_array($tab['id'], $ret['host']))) {
            $tab_server[$tab['id']] = ['id' => $tab['id'], 'name' => $tab['name'], 'localhost' => $tab['localhost']];
        }
    }

    foreach ($tab_server as $host) {
        $stdout = shell_exec(
            escapeshellarg($nagios_bin['nagios_bin']) . ' -v ' . $nagiosCFGPath
            . escapeshellarg($host['id']) . '/centengine.DEBUG 2>&1'
        );
        $stdout = htmlspecialchars($stdout, ENT_QUOTES, 'UTF-8');
        $msg_debug[$host['id']] = str_replace("\n", '<br />', $stdout);
        $msg_debug[$host['id']] = str_replace(
            'Warning:',
            "<font color='orange'>Warning</font>",
            $msg_debug[$host['id']]
        );
        $msg_debug[$host['id']] = str_replace(
            'warning: ',
            "<font color='orange'>Warning</font> ",
            $msg_debug[$host['id']]
        );
        $msg_debug[$host['id']] = str_replace('Error:', "<font color='red'>Error</font>", $msg_debug[$host['id']]);
        $msg_debug[$host['id']] = str_replace('error:', "<font color='red'>Error</font>", $msg_debug[$host['id']]);
        $msg_debug[$host['id']] = str_replace('reading', 'Reading', $msg_debug[$host['id']]);
        $msg_debug[$host['id']] = str_replace('running', 'Running', $msg_debug[$host['id']]);
        $msg_debug[$host['id']] = str_replace(
            'Total Warnings: 0',
            "<font color='green'>Total Warnings: 0</font>",
            $msg_debug[$host['id']]
        );
        $msg_debug[$host['id']] = str_replace(
            'Total Errors:   0',
            "<font color='green'>Total Errors: 0</font>",
            $msg_debug[$host['id']]
        );
        $msg_debug[$host['id']] = str_replace('<br />License:', ' - License:', $msg_debug[$host['id']]);

        $msg_debug[$host['id']] = preg_replace('/(\[[0-9]+?\]) \[[0-9]+?\]/', '$1', $msg_debug[$host['id']]);
        $msg_debug[$host['id']] = preg_replace(
            '/(\[\d{4}-[0-1]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d.\d{3}\+[0-1]\d:00\]) \[\w+\] \[\w+\]/',
            '$1',
            $msg_debug[$host['id']]
        );
        $lines = preg_split("/\<br\ \/\>/", $msg_debug[$host['id']]);
        $lines = array_map('unifyDateFormats', $lines);
        $lines = array_unique($lines);
        $lines = array_map('removeTimestamp', $lines);

        $msg_debug[$host['id']] = '';
        $i = 0;
        foreach ($lines as $line) {
            if (
                strncmp($line, 'Processing object config file', strlen('Processing object config file'))
                && strncmp($line, 'Website: http://www.nagios.org', strlen('Website: http://www.nagios.org'))
            ) {
                $msg_debug[$host['id']] .= $line . '<br>';
            }
            $i++;
        }
    }

    $xml->startElement('debug');
    $str = '';
    $returnCode = 0;
    foreach ($msg_debug as $pollerId => $message) {
        $show = 'none';
        $toggler = "<label id='togglerp_" . $pollerId . "'>[ + ]</label><label id='togglerm_" . $pollerId
            . "' style='display: none'>[ - ]</label>";
        $pollerNameColor = 'green';
        if (preg_match_all("/Total (Errors|Warnings)\:[ ]+([0-9]+)/", $message, $globalMatches, PREG_SET_ORDER)) {
            foreach ($globalMatches as $matches) {
                if ($matches[2] != '0') {
                    $show = 'block';
                    $toggler = "<label id='togglerp_" . $pollerId
                        . "' style='display: none'>[ + ]</label><label id='togglerm_" . $pollerId . "'>[ - ]</label>";
                    if ($matches[1] == 'Errors') {
                        $pollerNameColor = 'red';
                        $returnCode = 1;
                    } elseif ($matches[1] == 'Warnings') {
                        $pollerNameColor = 'orange';
                    }
                }
            }
        } else {
            $show = 'block';
            $pollerNameColor = 'red';
            $toggler = "<label id='togglerp_" . $pollerId
                . "' style='display: none'>[ + ]</label><label id='togglerm_" . $pollerId . "'>[ - ]</label>";
            $returnCode = 1;
        }
        $str .= "<a href='#' onClick=\"toggleDebug('" . $pollerId . "'); return false;\">";
        $str .= $toggler . '</a> ';
        $str .= "<b><font color='{$pollerNameColor}'>" . $tab_server[$pollerId]['name'] . '</font></b><br/>';
        $str .= "<div style='display: {$show};' id='debug_" . $pollerId . "'>" . htmlentities($message) . '</div><br/>';
    }
    $xml->text($str);
    $xml->endElement();

    return $returnCode;
}

/**
 * @param string $originalLog
 * @return string
 */
function unifyDateFormats(string $originalLog): string
{
    $log = null;
    $dateFormatPattern = '/\[(\d{4}-[0-1]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d.\d{3}\+[0-1]\d:00)\]/';
    if (preg_match($dateFormatPattern, $originalLog, $matches)) {
        $date = new DateTimeImmutable($matches[1]);
        $log = preg_replace(
            $dateFormatPattern,
            '[' . $date->getTimestamp() . ']',
            $originalLog
        );
    }

    return $log ?? $originalLog;
}

/**
 * @param string $log
 * @return string
 */
function removeTimestamp(string $log): string
{
    return preg_replace('/\[[0-9]+?\] /', '', $log) ?? $log;
}
