<?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_Contact;
use Centreon_Object_Contact_Group;
use Centreon_Object_Relation_Contact_Group_Contact;
use Exception;
use PDOException;
use Pimple\Container;

require_once 'centreonObject.class.php';
require_once 'centreonACL.class.php';
require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Contact.php';
require_once __DIR__ . '/../../../lib/Centreon/Object/Contact/Group.php';
require_once __DIR__ . '/../../../lib/Centreon/Object/Relation/Contact/Group/Contact.php';

/**
 * Class
 *
 * @class CentreonContactGroup
 * @package CentreonClapi
 * @description Class for managing contact groups
 */
class CentreonContactGroup extends CentreonObject
{
    public const ORDER_UNIQUENAME = 0;
    public const ORDER_ALIAS = 1;

    /** @var string[] */
    public static $aDepends = ['CMD', 'TP', 'CONTACT'];

    /**
     * CentreonContactGroup constructor
     *
     * @param Container $dependencyInjector
     *
     * @throws PDOException
     */
    public function __construct(Container $dependencyInjector)
    {
        parent::__construct($dependencyInjector);
        $this->object = new Centreon_Object_Contact_Group($dependencyInjector);
        $this->params = ['cg_activate' => '1'];
        $this->insertParams = ['cg_name', 'cg_alias'];
        $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]);
        $this->action = 'CG';
        $this->nbOfCompulsoryParams = count($this->insertParams);
        $this->activateField = 'cg_activate';
    }

    /**
     * Magic method for get/set/add/del relations
     *
     * @param string $name
     * @param array $arg
     * @throws CentreonClapiException
     */
    public function __call($name, $arg)
    {
        // Get the method name
        $name = strtolower($name);
        // Get the action and the object
        if (preg_match('/^(get|set|add|del)contact$/', $name, $matches)) {
            $relobj = new Centreon_Object_Relation_Contact_Group_Contact($this->dependencyInjector);
            $obj = new Centreon_Object_Contact($this->dependencyInjector);

            // Parse arguments
            if (! isset($arg[0])) {
                throw new CentreonClapiException(self::MISSINGPARAMETER);
            }
            $args = explode($this->delim, $arg[0]);
            $cgIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]);
            if (! count($cgIds)) {
                throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]);
            }
            $cgId = $cgIds[0];

            if ($matches[1] == 'get') {
                $tab = $relobj->getTargetIdFromSourceId($relobj->getSecondKey(), $relobj->getFirstKey(), $cgIds);
                echo 'id' . $this->delim . 'name' . "\n";
                foreach ($tab as $value) {
                    $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]);
                    echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n";
                }
            } else {
                if (! isset($args[1])) {
                    throw new CentreonClapiException(self::MISSINGPARAMETER);
                }
                $relation = $args[1];
                $relations = explode('|', $relation);
                $relationTable = [];
                foreach ($relations as $rel) {
                    $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]);
                    if (! count($tab)) {
                        throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $rel);
                    }
                    $relationTable[] = $tab[0];
                }
                if ($matches[1] == 'set') {
                    $relobj->delete($cgId);
                }
                $existingRelationIds = $relobj->getTargetIdFromSourceId(
                    $relobj->getSecondKey(),
                    $relobj->getFirstKey(),
                    [$cgId]
                );
                foreach ($relationTable as $relationId) {
                    if ($matches[1] == 'del') {
                        $relobj->delete($cgId, $relationId);
                    } elseif ($matches[1] == 'set' || $matches[1] == 'add') {
                        if (! in_array($relationId, $existingRelationIds)) {
                            $relobj->insert($cgId, $relationId);
                        }
                    }
                }
                $acl = new CentreonACL($this->dependencyInjector);
                $acl->reload(true);
            }
        } else {
            throw new CentreonClapiException(self::UNKNOWN_METHOD);
        }
    }

    /**
     * Get contact group ID
     *
     * @param string|null $contactGroupName
     * @throws CentreonClapiException
     * @return int
     */
    public function getContactGroupID($contactGroupName = null)
    {
        $cgIds = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$contactGroupName]);
        if (count($cgIds) !== 1) {
            throw new CentreonClapiException('Unknown contact group: ' . $contactGroupName);
        }

        return (int) $cgIds[0];
    }

    /**
     * @param null $parameters
     * @param array $filters
     *
     * @throws Exception
     */
    public function show($parameters = null, $filters = []): void
    {
        $filters = [];
        if (isset($parameters)) {
            $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%'];
        }
        $params = ['cg_id', 'cg_name', 'cg_alias'];
        $paramString = str_replace('cg_', '', implode($this->delim, $params));
        echo $paramString . "\n";
        $elements = $this->object->getList($params, -1, 0, null, null, $filters);
        foreach ($elements as $tab) {
            echo implode($this->delim, $tab) . "\n";
        }
    }

    /**
     * @param $parameters
     *
     * @throws CentreonClapiException
     * @throws PDOException
     * @return void
     */
    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]);
        $addParams['cg_alias'] = $params[self::ORDER_ALIAS];
        $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('/^cg_/', $params[1]) && $params[1] !== 'ar_id') {
                $params[1] = 'cg_' . $params[1];
            }
            $updateParams = [$params[1] => $params[2]];
            $updateParams['objectId'] = $objectId;

            return $updateParams;
        }

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

    /**
     * Export
     *
     * @param null $filterName
     *
     * @throws Exception
     * @return false|void
     */
    public function export($filterName = null)
    {
        if (! parent::export($filterName)) {
            return false;
        }

        $relObj = new Centreon_Object_Relation_Contact_Group_Contact($this->dependencyInjector);
        $contactObj = new Centreon_Object_Contact($this->dependencyInjector);
        $cgFieldName = $this->object->getUniqueLabelField();
        $cFieldName = $contactObj->getUniqueLabelField();
        $filters = [];
        if (! is_null($filterName)) {
            $filters[$cgFieldName] = $filterName;
        }
        $elements = $relObj->getMergedParameters(
            [$cgFieldName],
            [$cFieldName, 'contact_id'],
            -1,
            0,
            $cgFieldName . ', contact_alias',
            'ASC',
            $filters,
            'AND'
        );
        foreach ($elements as $element) {
            CentreonContact::getInstance()->export($element[$cFieldName]);
            echo $this->action . $this->delim . 'addcontact'
                . $this->delim . $element[$cgFieldName] . $this->delim . $element[$cFieldName]
                . $this->delim . $element['contact_alias'] . "\n";
        }
    }
}
