<?php

namespace Diamond\Modules\AdminReports;

use ActiveTable\ColumnTable;
use Core\Form\Control\MenuItemDelete;
use Core\Form\Control\MenuItemEdit;
use Core\Form\Control\Switchery;
use Core\Form\ControlBuilder;
use Core\Form\NiftyControlBuilder;
use Core\ModuleController;
use Diamond\Domain\Report\Contracts\ReportEntityInterface;
use Diamond\Repositories\Report;
use Diamond\Helpers\Formatter;
use DiamondTable\TableFactory;

/**
 * Description of AdminReports
 * @todo Проверка уникальности code при его сохранении
 * @author Admin
 */
class AdminReports extends ModuleController
{

    public function __construct(private Report\ReportRepository $repo,
                                private  TableFactory $tableFactory,
                                private  NiftyControlBuilder $controlBuilder)
    {}

    public function process(): string
    {
        $table = $this->tableFactory->buildAdminTable($this->repo, Report\ReportCriteria::create(),'Добавить шаблон');

        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('code', 'Идентификатор'))
            )
            ->addColumn(
                (new ColumnTable('title', 'Наименование'))
            )
            ->addColumn(
                (new ColumnTable('template', 'Шаблон'))
            )

            ->addColumn(
                (new ColumnTable('content', 'Содержимое'))
                    ->setFormat($this, 'formatContent')

            )
            ->addColumn(
                (new ColumnTable('rptSystem', 'Системный'))
                    ->setFormat($this, 'formatSystem')

            )
            ->addColumn(
                (new ColumnTable('action', ''))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(120)
            )
            ;

        $table
            ->addField(
                $this->controlBuilder->buildInput('code'), true,null,'должен быть уникальным'
            )
            ->addField(
                $this->controlBuilder->buildInput('title'), true,null,'в email как Тема письма'
            )
            ->addField(
                $this->controlBuilder->buildInput('template'), false,null,'название twig шаблона'
            )
            ->addField(
                $this->controlBuilder->buildNiftySimpleSwitchery('rptSystem','Y','N'), true
            )
            ->addField(
                $this->controlBuilder
                    ->buildTextEditor('content')
                    ->setMini(true)
                    ->setHeight(400)
                    ->setWidthPercent(100)
                , false,null, 'текст с сниппетами,как альтернатива twig шаблону'
            )
        ;

        return $table->render();
    }

    public function formatActions(ReportEntityInterface $entity): string
    {
        $items = [
            new MenuItemEdit($entity->getId())
        ];
        

        if ($entity->getRptSystem() === 'N') {
            $items [] = new MenuItemDelete($entity->getId());
        }

        return $this->controlBuilder->buildActionMenu($items)->render();
    }

    public function formatContent(\Diamond\Infrastructure\Models\Report\Report $report): string
    {
        return !$report->getContent() ? '' : Formatter::formatLongText($report->getContent());
    }

    public function formatSystem(\Diamond\Infrastructure\Models\Report\Report $report): string
    {
        $data = [
            'class' => self::class,
            'id' => $report->getId(),
            'fn' => 'changeSystem'
        ];
        return (new Switchery($data, $report->getRptSystem() === 'Y'))->render();
    }

    public function changeSystem(int $id, bool $checked): void
    {
        $item = $this->repo->findById($id);
        $item->setRptSystem($checked === true ? "Y" : 'N');
        $this->repo->save($item);
    }
}