<?php declare(strict_types=1);

namespace Diamond\Modules\AdminMailRequest;

use ActiveTable\ColumnTable;
use Core\AdminModuleController;
use Core\Form\Control\Button;
use Core\Form\Control\MenuItemAction;
use Core\Form\Control\MenuItemEdit;
use Core\Form\ControlBuilder;
use Core\Helpers\Text;
use Diamond\Helpers\Date;
use Diamond\Helpers\Form;
use Diamond\Infrastructure\Models\MessageRequest\MessageRequest;
use Diamond\Repositories\ErrorLog\ErrorLogEntity;
use Diamond\Repositories\MessageRequest\MessageRequestCriteria;
use Diamond\Repositories\MessageRequest\MessageRequestRepository;
use DiamondTable\TableFactory;

class AdminMailRequest extends AdminModuleController
{


    public function __construct(protected MessageRequestRepository $messageRequestRepository,
                                protected TableFactory             $tableFactory,
                                protected ControlBuilder           $controlBuilder
    )
    {
    }

    public function process(): string
    {
        if (input_get('id')) {

            $back = (new Button('back', '<< Вернуться назад'))
                ->setClass('btn btn-warning mar-btm')
                ->setOnClick('location.href=\'' . admin_path('/diamond/system/email_requests') . '\'')
                ->render();

            if (!$request = $this->messageRequestRepository->findById((int)input_get('id'))) {
                return Form::buildErrorMessage('Письмо не найдено по id ' . input_get('id')) . $back;
            }

            return $this->render([
                'request' => $request->toArray(),
                'message' => $request->getBody(),
                'back' => $back
            ]);
        }


        $table = $this->tableFactory->buildAdminTable($this->messageRequestRepository, MessageRequestCriteria::create());

        $table
            ->setDefaultSortColumn('id', 'DESC')
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('createdAt', 'Дата создания'))->setFormat($this, 'formatDateTime')
            )
            ->addColumn(
                (new ColumnTable('emailTo', 'Получатель'))->setFormat($this, 'formatEmailTo')
            )
            ->addColumn(
                (new ColumnTable('emailFrom', 'Отправитель'))->setFormat($this, 'formatEmailFrom')
            )
            ->addColumn(
                (new ColumnTable('subject', 'Тема'))
            )
            ->addColumn(
                (new ColumnTable('body', 'Содержимое'))->setFormat($this, 'formatBody')
            )
            ->addColumn(
                (new ColumnTable('attachments', 'Вложения'))
            )
            ->addColumn(
                (new ColumnTable('status', 'Статус'))
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActionsMod')
            );

        $table
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_emailTo')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_emailFrom')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_subject')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_status')
            )
        ;

        return $table->render();
    }

    public function formatActionsMod(MessageRequest $request): string
    {

        return $this->controlBuilder->buildActionMenu([
            (new MenuItemEdit(1, adaptive_url(['id' => $request->getId()])))->setClassIcon('demo-pli-magnifi-glass')
        ])->render();
    }

    public function formatBody(MessageRequest $request): string
    {
        return trim(str_replace(
            array('\r\n', '\n'), '',
            \Diamond\Helpers\Text::characterLimiter(strip_tags($request->getBody()), 80)));
    }

    public function formatEmailTo(MessageRequest $request): string
    {
        $to = json_decode($request->getEmailTo(), true);
        $html = '';
        foreach ($to as $email => $name) {
            $html .= $email . ($name > '' ? ' [' . $name . '] ' : '');
        }
        return $html;
    }

    public function formatEmailFrom(MessageRequest $request): string
    {
        if(!$to = json_decode($request->getEmailFrom(), true)){
            return '';
        }
        $html = '';
        foreach ($to as $email => $name) {
            $html .= $email . ($name > '' ? ' [' . $name . '] ' : '');
        }
        return $html;
    }

    /**
     * @param MessageRequest|MessageRequest $request
     * @return string
     */
    public function formatDateTime(MessageRequest $request): string
    {
        return $request->getCreatedAt() ? $request->getCreatedAt()->format(Date::formatDisplay()) : '';
    }
}