<?php

namespace Diamond\Modules\AdminContentCategories;

use ActiveTable\ColumnTable;
use Core\ModuleController;
use Diamond\Domain\ContentCategory\Contracts\ContentCategoryEntityInterface;
use Diamond\Repositories\ContentCategory;
use Core\Form\ControlBuilder;
use DiamondTable\TableFactory;

/**
 * Description of AdminContentCategories
 *
 * @author Admin
 */
class AdminContentCategories extends ModuleController
{

    public function __construct( private ContentCategory\ContentCategoryRepository $categoryRepo,
                                 private TableFactory $tableFactory, private ControlBuilder $builder)
    {}

    public function process(): string
    {

        $table = $this->tableFactory->buildAdminTable($this->categoryRepo, ContentCategory\ContentCategoryCriteria::create());

        $table
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('code', 'Идентификатор раздела'))
            )
            ->addColumn(
                (new ColumnTable('title', 'Наименование'))
            )
            ->addColumn(
                (new ColumnTable('count', 'Кол-во материалов'))
                    ->setFormat($this, 'formatCount')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActions')
            );

        $table
            ->addField(
                $this->builder->buildInput('code'), true
            )
            ->addField(
                $this->builder->buildInput('code'), true
            )
            ->addField(
                $this->builder->buildInput('title'), true
            );

        return $table->render();
    }

    public function formatActions(ContentCategoryEntityInterface $entity): string
    {
        $actions = [
            anchor(
                admin_path('/diamond/content/content'),
                'Перейти к материалам',
                [],
                [
                    'filter_by_categoryId' => $entity->getId()
                ]
            ),
        ];

        return $this->builder->buildActionMenuAdmin($actions, $entity->getId())->render();
    }

    public function formatCount(ContentCategoryEntityInterface $contentCategory): string
    {
        return (string)$contentCategory->getContents()->count();
    }

    public function formatAction(\Diamond\Infrastructure\Models\ContentCategory\ContentCategory $category): string
    {
        return anchor(admin_path('/diamond/content'), $category->getContents()->count() . ' материалов'
            , array(
                'title' => 'перейти к материалам раздела'
            ), array(
                'category_id' => $category->getId()
            ));
    }

}
