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

namespace CentreonClapi;

use Centreon_Object_Command;
use Centreon_Object_Graph_Template;
use Exception;
use PDOException;
use Pimple\Container;

require_once 'centreonObject.class.php';
require_once 'centreonUtils.class.php';
require_once 'Centreon/Object/Command/Command.php';
require_once 'Centreon/Object/Graph/Template/Template.php';

/**
 * Class
 *
 * @class CentreonCommand
 * @package CentreonClapi
 * @author jmathis
 */
class CentreonCommand extends CentreonObject
{
    public const ORDER_UNIQUENAME = 0;
    public const ORDER_TYPE = 1;
    public const ORDER_COMMAND = 2;
    public const UNKNOWN_CMD_TYPE = 'Unknown command type';

    /** @var array[] */
    public $aTypeCommand = ['host' => ['key' => '$_HOST', 'preg' => '/\$_HOST(\w+)\$/'], 'service' => ['key' => '$_SERVICE', 'preg' => '/\$_SERVICE(\w+)\$/']];

    /** @var int[] */
    protected $typeConversion = ['notif' => 1, 'check' => 2, 'misc' => 3, 'discovery' => 4, 1 => 'notif', 2 => 'check', 3 => 'misc', 4 => 'discovery'];

    /**
     * CentreonCommand constructor
     *
     * @param Container $dependencyInjector
     *
     * @throws PDOException
     */
    public function __construct(Container $dependencyInjector)
    {
        parent::__construct($dependencyInjector);
        $this->object = new Centreon_Object_Command($dependencyInjector);
        $this->params = [];
        $this->insertParams = ['command_name', 'command_type', 'command_line'];
        $this->exportExcludedParams = array_merge(
            $this->insertParams,
            [$this->object->getPrimaryKey(), 'graph_id', 'cmd_cat_id']
        );
        $this->action = 'CMD';
        $this->nbOfCompulsoryParams = count($this->insertParams);
    }

    /**
     * @param null $parameters
     * @param array $filters
     *
     * @throws Exception
     */
    public function show($parameters = null, $filters = []): void
    {
        if (isset($parameters)) {
            $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%'];
        }
        $params = ['command_id', 'command_name', 'command_type', 'command_line'];
        $paramString = str_replace('command_', '', implode($this->delim, $params));
        echo $paramString . "\n";
        $elements = $this->object->getList($params, -1, 0, null, null, $filters);
        foreach ($elements as $tab) {
            $tab['command_line'] = CentreonUtils::convertSpecialPattern(html_entity_decode($tab['command_line']));
            $tab['command_line'] = CentreonUtils::convertLineBreak($tab['command_line']);
            $tab['command_type'] = $this->typeConversion[$tab['command_type']];
            echo implode($this->delim, $tab) . "\n";
        }
    }

    /**
     * @param $parameters
     *
     * @throws CentreonClapiException
     * @throws PDOException
     */
    public function initInsertParameters($parameters): void
    {
        $params = explode($this->delim, $parameters);

        if (count($params) < $this->nbOfCompulsoryParams) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }

        $addParams = [];
        $addParams[$this->object->getUniqueLabelField()] = $this->checkIllegalChar($params[self::ORDER_UNIQUENAME]);
        if (! isset($this->typeConversion[$params[self::ORDER_TYPE]])) {
            throw new CentreonClapiException(self::UNKNOWN_CMD_TYPE . ':' . $params[self::ORDER_TYPE]);
        }
        $addParams['command_type']
            = is_numeric($params[self::ORDER_TYPE])
                ? $params[self::ORDER_TYPE]
                : $this->typeConversion[$params[self::ORDER_TYPE]];
        $addParams['command_line'] = $params[self::ORDER_COMMAND];
        $this->params = array_merge($this->params, $addParams);
        $this->checkParameters();
    }

    /**
     * @param $parameters
     * @throws CentreonClapiException
     * @return array
     */
    public function initUpdateParameters($parameters)
    {
        $params = explode($this->delim, $parameters);
        if (count($params) < self::NB_UPDATE_PARAMS) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }
        $objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME]);

        if ($objectId != 0) {
            if (! preg_match('/^command_/', $params[1])) {
                if (! in_array($params[1], ['graph', 'enable_shell', 'connector_id'])) {
                    $params[1] = 'command_' . $params[1];
                } elseif ($params[1] == 'graph') {
                    $params[1] = 'graph_id';
                }
            }
            if ($params[1] == 'command_type') {
                if (! isset($this->typeConversion[$params[2]])) {
                    throw new CentreonClapiException(self::UNKNOWN_CMD_TYPE . ':' . $params[2]);
                }
                if (! is_numeric($params[2])) {
                    $params[2] = $this->typeConversion[$params[2]];
                }
            } elseif ($params[1] == 'graph_id') {
                $graphObject = new Centreon_Object_Graph_Template($this->dependencyInjector);
                $tmp = $graphObject->getIdByParameter($graphObject->getUniqueLabelField(), $params[2]);
                if (! count($tmp)) {
                    throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[2]);
                }
                $params[2] = $tmp[0];
            }
            $updateParams = [$params[1] => $params[2]];
            $updateParams['objectId'] = $objectId;

            return $updateParams;
        }

        throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]);
    }

    /**
     * Get a parameter
     *
     * @param null $parameters
     * @throws CentreonClapiException
     */
    public function getparam($parameters = null): void
    {
        $params = explode($this->delim, $parameters);
        if (count($params) < 2) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }
        $authorizeParam = ['name', 'line', 'type', 'graph', 'example', 'comment', 'activate', 'enable_shell'];
        $unknownParam = [];

        if (($objectId = $this->getObjectId($params[self::ORDER_UNIQUENAME])) != 0) {
            $listParam = explode('|', $params[1]);
            $exportedFields = [];
            $resultString = '';
            foreach ($listParam as $paramSearch) {
                $paramString = ! $paramString ? $paramSearch : $paramString . $this->delim . $paramSearch;
                $field = $paramSearch;
                if (! in_array($field, $authorizeParam)) {
                    $unknownParam[] = $field;
                } else {
                    switch ($paramSearch) {
                        case 'graph':
                            $field = 'graph_id';
                            break;
                        case 'enable_shell':
                            break;
                        default:
                            if (! preg_match('/^command_/', $paramSearch)) {
                                $field = 'command_' . $paramSearch;
                            }
                            break;
                    }

                    $ret = $this->object->getParameters($objectId, $field);
                    $ret = $ret[$field];

                    switch ($paramSearch) {
                        case 'graph':
                            $graphObj = new Centreon_Object_Graph_Template($this->dependencyInjector);
                            $field = $graphObj->getUniqueLabelField();
                            $ret = $graphObj->getParameters($ret, $field);
                            $ret = $ret[$field];
                            break;
                    }

                    if (! isset($exportedFields[$paramSearch])) {
                        $resultString .= $this->csvEscape($ret) . $this->delim;
                        $exportedFields[$paramSearch] = 1;
                    }
                }
            }
        } else {
            throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[self::ORDER_UNIQUENAME]);
        }

        if ($unknownParam !== []) {
            throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . implode('|', $unknownParam));
        }
        echo implode(';', array_unique(explode(';', $paramString))) . "\n";
        echo substr($resultString, 0, -1) . "\n";
    }

    /**
     * Get command arguments descriptions
     *
     * @param string $objUniqueName
     *
     * @throws CentreonClapiException
     * @throws PDOException
     */
    public function getargumentdesc($objUniqueName): void
    {
        if ($objUniqueName != '' && ($objectId = $this->getObjectId($objUniqueName)) != 0) {
            $sql = 'SELECT macro_name, macro_description FROM command_arg_description WHERE cmd_id = ?';
            $res = $this->db->query($sql, [$objectId]);

            echo 'name' . $this->delim . 'description' . "\n";
            foreach ($res as $param) {
                echo $param['macro_name'] . $this->delim . $param['macro_description'] . "\n";
            }
        } else {
            throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objUniqueName);
        }
    }

    /**
     * Set command arguments descriptions
     *
     * @param string $descriptions
     *
     * @throws CentreonClapiException
     * @throws PDOException
     */
    public function setargumentdescr($descriptions): void
    {
        $data = explode($this->delim, trim($descriptions, $this->delim));
        if (count($data) < 1) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }
        $objUniqueName = array_shift($data);
        if (($objectId = $this->getObjectId($objUniqueName)) != 0) {
            $sql = 'DELETE FROM command_arg_description WHERE cmd_id = ?';
            $this->db->query($sql, [$objectId]);

            foreach ($data as $description) {
                [$arg, $desc] = explode(':', $description, 2);
                $sql = 'INSERT INTO command_arg_description (cmd_id, macro_name, macro_description) VALUES (?,?,?)';
                $this->db->query($sql, [$objectId, $arg, $desc]);
            }
        } else {
            throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objUniqueName);
        }
    }

    /**
     * Returns command id
     *
     * @param string $commandName
     * @throws CentreonClapiException
     * @return int
     */
    public function getId($commandName)
    {
        $obj = new Centreon_Object_Command($this->dependencyInjector);
        $tmp = $obj->getIdByParameter($obj->getUniqueLabelField(), $commandName);
        if (count($tmp)) {
            $id = $tmp[0];
        } else {
            throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $commandName);
        }

        return $id;
    }

    /**
     * @param null $filterName
     * @throws CentreonClapiException
     * @return bool|void
     */
    public function export($filterName = null)
    {
        if (! $this->canBeExported($filterName)) {
            return false;
        }

        $labelField = $this->object->getUniqueLabelField();
        $filters = [];
        if (! is_null($filterName)) {
            $filters[$labelField] = $filterName;
        }
        $elements = $this->object->getList(
            '*',
            -1,
            0,
            $labelField,
            'ASC',
            $filters
        );
        foreach ($elements as $element) {
            $addStr = $this->action . $this->delim . 'ADD';
            foreach ($this->insertParams as $param) {
                $addStr .= $this->delim;
                if ($param === 'command_line') {
                    $decodedHtmlParam = CentreonUtils::convertSpecialPattern(html_entity_decode($element[$param]));
                    $decodedHtmlParam = CentreonUtils::convertLineBreak($decodedHtmlParam);
                    $addStr .= $decodedHtmlParam;
                } else {
                    $addStr .= $element[$param];
                }
            }
            $addStr .= "\n";
            echo $addStr;

            foreach ($element as $parameter => $value) {
                if (! in_array($parameter, $this->exportExcludedParams)) {
                    if (! is_null($value) && $value != '') {
                        $value = CentreonUtils::convertLineBreak($value);
                        echo $this->action . $this->delim
                            . 'setparam' . $this->delim
                            . $element[$this->object->getUniqueLabelField()] . $this->delim
                            . $parameter . $this->delim
                            . $value . "\n";
                    }
                }
                if ($parameter == 'graph_id' && ! empty($value)) {
                    $graphObject = new Centreon_Object_Graph_Template($this->dependencyInjector);
                    $tmp = $graphObject->getParameters($value, [$graphObject->getUniqueLabelField()]);

                    if (! count($tmp)) {
                        throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $value);
                    }

                    $v = $tmp[$graphObject->getUniqueLabelField()];
                    $v = CentreonUtils::convertLineBreak($v);

                    echo $this->action . $this->delim
                        . 'setparam' . $this->delim
                        . $element[$this->object->getUniqueLabelField()] . $this->delim
                        . $this->getClapiActionName($parameter) . $this->delim
                        . $v . "\n";
                }
            }

            $argDescriptions = $this->getArgsDescriptions($element['command_id']);
            if (sizeof($argDescriptions) > 0) {
                echo $this->action . $this->delim
                    . 'setargumentdescr' . $this->delim
                    . $element[$this->object->getUniqueLabelField()] . $this->delim
                    . implode(';', $argDescriptions) . "\n";
            }
        }
    }

    /**
     * This method gat the list of command containt a specific macro
     *
     * @param int $iIdCommand
     * @param string $sType
     * @param int $iWithFormatData
     *
     * @throws PDOException
     * @return array
     */
    public function getMacroByIdAndType($iIdCommand, $sType, $iWithFormatData = 1)
    {
        $inputName = $sType;
        if ($sType == 'service') {
            $inputName = 'svc';
        }
        $macroToFilter = ['SNMPVERSION', 'SNMPCOMMUNITY'];

        if (empty($iIdCommand) || ! array_key_exists($sType, $this->aTypeCommand)) {
            return [];
        }

        $aDescription = $this->getMacroDescription($iIdCommand);

        $sql = "SELECT command_id, command_name, command_line
            FROM command
            WHERE command_type = 2
            AND command_id = ?
            AND command_line like '%" . $this->aTypeCommand[$sType]['key'] . "%'
            ORDER BY command_name";

        $res = $this->db->query($sql, [$iIdCommand]);
        $arr = [];
        $i = 0;

        if ($iWithFormatData == 1) {
            while ($row = $res->fetch()) {
                preg_match_all($this->aTypeCommand[$sType]['preg'], $row['command_line'], $matches, PREG_SET_ORDER);
                foreach ($matches as $match) {
                    if (! in_array($match[1], $macroToFilter)) {
                        $sName = $match[1];
                        $sDesc = $aDescription[$sName]['description'] ?? '';
                        $arr[$i][$inputName . '_macro_name'] = $sName;
                        $arr[$i][$inputName . '_macro_value'] = '';
                        $arr[$i]['is_password'] = null;
                        $arr[$i]['macroDescription'] = $sDesc;
                        $i++;
                    }
                }
            }
        } else {
            while ($row = $res->fetch()) {
                $arr[$row['command_id']] = $row['command_name'];
            }
        }

        return $arr;
    }

    /**
     * @param $iIdCmd
     *
     * @throws PDOException
     * @return array
     */
    public function getMacroDescription($iIdCmd)
    {
        $aReturn = [];
        $sSql = 'SELECT * FROM `on_demand_macro_command` WHERE `command_command_id` = ' . (int) $iIdCmd;

        $DBRESULT = $this->db->query($sSql);
        while ($row = $DBRESULT->fetch()) {
            $arr['id'] = $row['command_macro_id'];
            $arr['name'] = $row['command_macro_name'];
            $arr['description'] = $row['command_macro_desciption'];
            $arr['type'] = $row['command_macro_type'];

            $aReturn[$row['command_macro_name']] = $arr;
        }

        return $aReturn;
    }

    /**
     * Get clapi action name from db column name
     *
     * @param string $columnName
     * @return string
     */
    protected function getClapiActionName($columnName)
    {
        static $table;

        if (! isset($table)) {
            $table = ['graph_id' => 'graph'];
        }

        return $table[$columnName] ?? $columnName;
    }

    /**
     * Export command_arg_description
     *
     * @param int $command_id
     *
     * @throws PDOException
     * @return array
     */
    protected function getArgsDescriptions($command_id)
    {
        $sql = 'SELECT macro_name, macro_description
        		FROM command_arg_description
        		WHERE cmd_id = ?
        		ORDER BY macro_name';
        $res = $this->db->query($sql, [$command_id]);

        $args_desc = [];
        while ($row = $res->fetch()) {
            $args_desc[] = $row['macro_name'] . ':' . trim($row['macro_description']);
        }
        unset($res);

        return $args_desc;
    }
}
