<?php

/**
 * ---------------------------------------------------------------------
 *
 * GLPI - Gestionnaire Libre de Parc Informatique
 *
 * http://glpi-project.org
 *
 * @copyright 2015-2025 Teclib' and contributors.
 * @licence   https://www.gnu.org/licenses/gpl-3.0.html
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * ---------------------------------------------------------------------
 */

namespace Glpi\Form\Destination\CommonITILField;

use Glpi\Application\View\TemplateRenderer;
use Glpi\DBAL\JsonFieldInterface;
use Glpi\Form\AnswersSet;
use Glpi\Form\Destination\AbstractConfigField;
use Glpi\Form\Destination\FormDestination;
use Glpi\Form\Destination\HasFormTags;
use Glpi\Form\Form;
use Glpi\Form\Migration\DestinationFieldConverterInterface;
use Glpi\Form\Migration\FormMigration;
use Glpi\Form\Migration\TagConversionTrait;
use Glpi\Form\Tag\AnswerTagProvider;
use Glpi\Form\Tag\FormTagsManager;
use Glpi\Form\Tag\QuestionTagProvider;
use Glpi\Form\Tag\SectionTagProvider;
use InvalidArgumentException;
use Override;

#[HasFormTags]
final class ContentField extends AbstractConfigField implements DestinationFieldConverterInterface
{
    use TagConversionTrait;

    #[Override]
    public function getLabel(): string
    {
        return __("Content");
    }

    #[Override]
    public function getConfigClass(): string
    {
        return SimpleValueConfig::class;
    }

    #[Override]
    public function renderConfigForm(
        Form $form,
        FormDestination $destination,
        JsonFieldInterface $config,
        string $input_name,
        array $display_options
    ): string {
        if (!$config instanceof SimpleValueConfig) {
            throw new InvalidArgumentException("Unexpected config class");
        }

        $template = <<<TWIG
            {% import 'components/form/fields_macros.html.twig' as fields %}

            {{ fields.textareaField(
                input_name,
                value,
                '',
                options|merge({
                    'field_class'      : '',
                    'no_label'         : true,
                    'enable_richtext'  : true,
                    'enable_images'    : false,
                    'enable_form_tags' : true,
                    'form_tags_form_id': form_id,
                    'content_style'    : 'body { line-height: 2.3; }',
                    'mb'               : '',
                })
            ) }}
TWIG;

        $twig = TemplateRenderer::getInstance();
        return $twig->renderFromStringTemplate($template, [
            'form_id'    => $form->fields['id'],
            'value'      => $config->getValue(),
            'input_name' => $input_name . "[" . SimpleValueConfig::VALUE . "]",
            'options'    => $display_options,
        ]);
    }

    #[Override]
    public function applyConfiguratedValueToInputUsingAnswers(
        JsonFieldInterface $config,
        array $input,
        AnswersSet $answers_set
    ): array {
        if (!$config instanceof SimpleValueConfig) {
            throw new InvalidArgumentException("Unexpected config class");
        }

        $tag_manager = new FormTagsManager();
        $input['content'] = $tag_manager->insertTagsContent(
            $config->getValue(),
            $answers_set
        );

        return $input;
    }

    #[Override]
    public function supportAutoConfiguration(): bool
    {
        return true;
    }

    #[Override]
    public function getAutoGeneratedConfig(Form $form, ?AnswersSet $answers_set = null): SimpleValueConfig
    {
        $section_provider = new SectionTagProvider();
        $question_provider = new QuestionTagProvider();
        $answer_provider = new AnswerTagProvider();

        $html = "";
        $sections = $form->getSections();
        $has_more_than_one_section = count($sections) > 1;

        foreach ($sections as $section) {
            $questions = $section->getQuestions();

            // If we have an answer set, we must remove questions that weren't
            // submitted to avoid polluting the description with empty content.
            if ($answers_set !== null) {
                $questions = array_filter(
                    $questions,
                    fn($q) => $answers_set->hasAnswerForQuestionId($q->getID()),
                );
            }
            if (count($questions) == 0) {
                // Do not display empty sections
                continue;
            }

            if ($has_more_than_one_section) {
                $section_tag = $section_provider->getTagForSection($section);
                $html .= "<h2>$section_tag->html</h2>";
            }

            if (!empty($questions)) {
                $html .= "<p>";
                $i = 1;
                foreach ($questions as $question) {
                    $question_tag  = $question_provider->getTagForQuestion($question);
                    $answer_tag    = $answer_provider->getTagForQuestion($question);

                    $html .= "<b>$i) $question_tag->html</b>: $answer_tag->html<br>";
                    $i++;
                }
                $html .= "</p>";
            }
        }

        return new SimpleValueConfig($html);
    }

    #[Override]
    public function getDefaultConfig(Form $form): SimpleValueConfig
    {
        return new SimpleValueConfig('');
    }

    #[Override]
    public function getWeight(): int
    {
        return 20;
    }

    #[Override]
    public function getCategory(): Category
    {
        return Category::PROPERTIES;
    }

    #[Override]
    public function convertFieldConfig(FormMigration $migration, Form $form, array $rawData): JsonFieldInterface
    {
        if (isset($rawData['content'])) {
            $content = $this->convertLegacyTags($rawData['content'], $migration);
            return new SimpleValueConfig($content);
        }

        return $this->getDefaultConfig($form);
    }
}
