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

if (! isset($centreon)) {
    exit();
}

include_once _CENTREON_PATH_ . 'www/class/centreonGMT.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonDB.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonService.class.php';
include_once _CENTREON_PATH_ . 'www/class/centreonHost.class.php';

// Init GMT class
$centreonGMT = new CentreonGMT();
$centreonGMT->getMyGMTFromSession(session_id());
$hostStr = $centreon->user->access->getHostsString('ID', $pearDBO);

$hObj = new CentreonHost($pearDB);
$serviceObj = new CentreonService($pearDB);

if (! $centreon->user->access->checkAction('service_comment')) {
    require_once '../errors/alt_error.php';
} else {
    // Init
    $debug = 0;
    $attrsTextI = ['size' => '3'];
    $attrsText = ['size' => '30'];
    $attrsTextarea = ['rows' => '7', 'cols' => '80'];

    // Form begin
    $form = new HTML_QuickFormCustom('Form', 'POST', '?p=' . $p);

    // Indicator basic information
    $redirect = $form->addElement('hidden', 'o');
    $redirect->setValue($o);

    if (isset($_GET['host_id']) && ! isset($_GET['service_id'])) {
        $host_name = $hObj->getHostName($_GET['host_id']);
    } elseif (isset($_GET['host_id'], $_GET['service_id'])) {
        $serviceParameters = $serviceObj->getParameters($_GET['service_id'], ['service_description']);
        $serviceDisplayName = $serviceParameters['service_description'];
        $host_name = $hObj->getHostName($_GET['host_id']);
    }
    if (! isset($_GET['host_id'])) {
        $dtType[] = $form->createElement(
            'radio',
            'commentType',
            null,
            _('Host'),
            '1',
            ['id' => 'host', 'onclick' => "toggleParams('host');"]
        );
        $dtType[] = $form->createElement(
            'radio',
            'commentType',
            null,
            _('Services'),
            '2',
            ['id' => 'service', 'onclick' => "toggleParams('service');"]
        );
        $form->addGroup($dtType, 'commentType', _('Comment type'), '&nbsp;');

        // ----- Hosts -----
        $attrHosts = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_host&action=list', 'multiple' => true, 'linkedObject' => 'centreonHost'];
        $form->addElement('select2', 'host_id', _('Hosts'), [], $attrHosts);

        if (! isset($_GET['service_id'])) {
            // ----- Services -----
            $attrServices = ['datasourceOrigin' => 'ajax', 'availableDatasetRoute' => './api/internal.php?object=centreon_configuration_service&action=list&e=enable', 'multiple' => true, 'linkedObject' => 'centreonService'];
            $form->addElement('select2', 'service_id', _('Services'), [], $attrServices);
        }
    }

    $persistant = $form->addElement('checkbox', 'persistant', _('Persistent'));
    $persistant->setValue('1');

    $form->addElement('textarea', 'comment', _('Comments'), $attrsTextarea);
    $form->addRule('comment', _('Required Field'), 'required');

    $data = [];
    if (isset($_GET['host_id']) && ! isset($_GET['service_id'])) {
        $data['host_id'] = $_GET['host_id'];
        $data['commentType'] = 1;
        $focus = 'host';
        $form->addElement('hidden', 'host_id', $_GET['host_id']);
        $form->addElement('hidden', 'commentType[commentType]', $data['commentType']);
    } elseif (isset($_GET['host_id'], $_GET['service_id'])) {
        $data['service_id'] = $_GET['host_id'] . '-' . $_GET['service_id'];
        $data['commentType'] = 2;
        $focus = 'service';
        $form->addElement('hidden', 'service_id', $data['service_id']);
        $form->addElement('hidden', 'commentType[commentType]', $data['commentType']);
    } else {
        $data['commentType'] = 1;
        $focus = 'host';
    }

    $form->setDefaults($data);
    $subA = $form->addElement('submit', 'submitA', _('Save'), ['class' => 'btc bt_success']);
    $res = $form->addElement('reset', 'reset', _('Reset'), ['class' => 'btc bt_default']);

    // Push the comment
    if ((isset($_POST['submitA']) && $_POST['submitA']) && $form->validate()) {
        $values = $form->getSubmitValues();

        if (! isset($_POST['persistant']) || ! in_array($_POST['persistant'], ['0', '1'])) {
            $_POST['persistant'] = '0';
        }

        $_POST['comment'] = str_replace("'", ' ', $_POST['comment']);

        if ($values['commentType']['commentType'] == 1) {
            // Set a comment for only host

            // catch fix input host_id
            if (isset($_POST['host_id'])) {
                if (! is_array($_POST['host_id'])) {
                    $_POST['host_id'] = [$_POST['host_id']];
                }

                foreach ($_POST['host_id'] as $host_id) {
                    AddHostComment($host_id, $_POST['comment'], $_POST['persistant']);
                }
            }
            $valid = true;
            require_once $path . 'listComment.php';
        } elseif ($values['commentType']['commentType'] == 2) {
            // Set a comment for a service list

            // catch fix input service_id
            if (! is_array($_POST['service_id'])) {
                $_POST['service_id'] = [$_POST['service_id']];
            }

            // global services comment
            if (! isset($_POST['host_id'])) {
                foreach ($_POST['service_id'] as $value) {
                    $info = explode('-', $value);
                    AddSvcComment(
                        $info[0],
                        $info[1],
                        $_POST['comment'],
                        $_POST['persistant']
                    );
                }
            } else {
                // specific service comment
                AddSvcComment($_POST['host_id'], $_POST['service_id'], $_POST['comment'], $_POST['persistant']);
            }

            $valid = true;
            require_once $path . 'listComment.php';
        }
    } else {

        // Smarty template initialization
        $tpl = SmartyBC::createSmartyTemplate($path, 'template/');

        // Apply a template definition
        $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
        $renderer->setRequiredTemplate('{$label}&nbsp;<font color="red" size="1">*</font>');
        $renderer->setErrorTemplate('<font color="red">{$error}</font><br />{$html}');
        $form->accept($renderer);
        $tpl->assign('form', $renderer->toArray());

        if (isset($service_id, $host_id)) {
            $tpl->assign('host_name', $host_name);
            $tpl->assign('service_description', $svc_description);
        } elseif (isset($host_id)) {
            $tpl->assign('host_name', $host_name);
        }

        $tpl->assign('form', $renderer->toArray());
        $tpl->assign('o', $o);
        $tpl->assign('focus', $focus);
        $tpl->display('AddComment.html');
    }
}
