<?php

namespace Diamond\Modules\AdminMailing;


use ActiveTable\ColumnTable;
use Core\Form\ControlBuilder;
use Core\MailingPreparation\MailingCook;
use Diamond\Application\Mailing\MailingRecipientsCollection;
use Diamond\Domain\MailingTemplate\Contracts\MailingTemplateEntityInterface;
use Diamond\Infrastructure\Models\MailingTemplate\MailingTemplate;
use Diamond\Repositories\MailingTemplate\MailingTemplateCriteria;
use Diamond\Repositories\MailingTemplate\MailingTemplateRepository;
use DiamondTable\CommandFactory;
use DiamondTable\TableFactory;
use Twig\Error\LoaderError;

/**
 * Description of AdminMailing
 *
 * @author Diamond Code Generator
 */
class AdminMailing extends \Core\ModuleController
{


    public function __construct(protected MailingTemplateRepository   $mailingTemplateRepository,
                                protected TableFactory                $tableFactory,
                                protected ControlBuilder              $controlBuilder,
                                protected MailingRecipientsCollection $mailingRecipientsCollection,
                                protected MailingCook                 $mailingCook)
    {
    }

    /**
     * @return string
     * @throws \ReflectionException
     */
    public function process(): string
    {

        $table = $this->tableFactory->buildAdminTable($this->mailingTemplateRepository, MailingTemplateCriteria::create());
        $table->getCommandFactory()->addCommand(CommandFactory::FORM_VALIDATE, new ValidateMailingTemplateCommand($table));
        $table
            ->setDefaultSortColumn('id', 'DESC')
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('name', 'Наименование шаблона'))
            )
            ->addColumn(
                (new ColumnTable('subject', 'Тема сообщения'))
            )
            ->addColumn(
                (new ColumnTable('bodyFile', 'Файл шаблона'))->setFormat($this, 'formatFile')
            )
            ->addColumn(
                (new ColumnTable('body', 'Содержимое шаблона'))
                    ->setFormat($this, 'formatBody')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActions')
            );

        $table
            ->addField(
                $this->controlBuilder->buildInput('name'), true
            )
            ->addField(
                $this->controlBuilder->buildInput('subject'), true, null, 'Будет использовать в теме email сообщения'
            )
            ->addField(
                $this->controlBuilder->buildInput('bodyFile'), false, null, '.twig шаблон, например @local/mailing/template.twig'
            )
            ->addField(
                $this->controlBuilder->buildTextEditor('body')
            )
            ->addField(
                $this->controlBuilder->buildTextLabel('variables')->setFn($this, 'formatVariables')
            );

        return $table->render();
    }

    /**
     * @param MailingTemplateEntityInterface|MailingTemplate $mailing
     * @return string
     */
    public function formatFile(MailingTemplateEntityInterface $mailing): string
    {
        if (!empty($mailing->getbodyFile())) {
            try {
                return sprintf('<span style="color: green">%s</span>', $mailing->getbodyFile());
            } catch (LoaderError $ex) {
                return sprintf('<span style="color: red">%s</span>', $mailing->getbodyFile());
            }
        }

        return '';
    }

    public function formatActions(MailingTemplateEntityInterface $mailing): string
    {
        return $this->controlBuilder->buildActionMenuAdmin([], $mailing->getId())->render();
    }

    /**
     * @param MailingTemplateEntityInterface $template
     * @return string
     */
    public function formatBody(MailingTemplateEntityInterface $template): string
    {
        return trim(str_replace(
            array('\r\n', '\n'), '',
            \Diamond\Helpers\Text::characterLimiter(strip_tags($template->getBody()), 80)));
    }

    public function formatVariables(): string
    {
        $variables = [];
        foreach ($this->mailingRecipientsCollection->getHandlers() as $mailingRecipients) {
            $variables[$mailingRecipients->getName()] = $mailingRecipients->getVariables();
        }
        $inGroups = [];
        $inVars = [];
        foreach($variables as $group => $vars){
            foreach($vars as $var => $label){
                $inGroups[$var][]=$group;
                $inVars[$var] = $label;
            }
        }

        $html = '';
        foreach ($inVars as $variable => $label) {
            $html .= sprintf('<strong>{{%s}} - %s</strong> <em>%s</em><br/>', $variable, $label, implode(', ',$inGroups[$variable]));
        }

        return $html;
    }
}