<?php

namespace Shop\Presentation\Modules\AdminProviderOrderItems;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\ControlBuilder;
use Core\ModuleController;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Shop\Domain\ProviderOrderItem\Contracts\ProviderOrderItemEntityInterface;
use Shop\Presentation\Modules\AdminOrderItems\FormatColumnsTrait;
use Shop\Infrastructure\Repositories\Provider\ProviderCriteria;
use Shop\Infrastructure\Repositories\Provider\ProviderRepository;
use Shop\Infrastructure\Repositories\ProviderOrderItem\ProviderOrderItemCriteria;
use Shop\Infrastructure\Repositories\ProviderOrderItem\ProviderOrderItemRepository;
use Shop\Infrastructure\Repositories\State\StateCriteria;
use Shop\Infrastructure\Repositories\State\StateRepository;
use Shop\Infrastructure\Repositories\Stock\StockCriteria;
use Shop\Infrastructure\Repositories\Stock\StockRepository;
use Shop\Presentation\UseCases\Checkout\Checkout;
use Shop\Presentation\Modules\AdminOrderItems\ChangeStateCommand;


/**
 * Description of AdminOrderItems
 *
 * @author Diamond Code Generator
 */
class AdminProviderOrderItems extends ModuleController
{

    use FormatColumnsTrait;
    protected $repository;
    protected $tableFactory;
    protected $controlBuilder;
    protected $providerRepository;
    protected $stateRepository;
    protected $checkoutUseCase;
    protected $stockRepository;

    public function __construct(ProviderOrderItemRepository $repository, TableFactory $tableFactory,
                                ControlBuilder $controlBuilder, ProviderRepository $providerRepository,
                                StateRepository $stateRepository, Checkout $checkoutUseCase,
                                StockRepository $stockRepository)
    {
        $this->repository = $repository;
        $this->tableFactory = $tableFactory;
        $this->controlBuilder = $controlBuilder;
        $this->providerRepository = $providerRepository;
        $this->stateRepository = $stateRepository;
        $this->stockRepository = $stockRepository;
        $this->checkoutUseCase = $checkoutUseCase;
    }

    /**
     * @return string
     * @throws \ReflectionException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): string
    {

        $stocks = $this->stockRepository->findByCriteria(
            StockCriteria::create()
        );

        $providers = $this->providerRepository->findByCriteria(
            ProviderCriteria::create()
        );

        $states = $this->stateRepository->findByCriteria(
            StateCriteria::create()
        );

        $table = $this->tableFactory->buildAdminTable($this->repository, ProviderOrderItemCriteria::create());
        $table->removeControlAccess(DataTableEngine::CONTROL_ACCESS_ADD);
        $table->setDefaultSortColumn('id', 'DESC');
        $table
//            ->addColumn(
//                (new ColumnTable(
//                    'id', '№'
//                ))
//                    ->setWidth(5, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'orderCode', 'Номер заказа'
                ))
                    ->setFormat($this, 'formatOrder')
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable(
                    'contractorId', 'Торговая точка'
                ))
                    ->setFormat($this, 'formatStockContractor')

            )
            ->addColumn(
                (new ColumnTable(
                    'name', 'Наименование товара'
                ))
            )
            ->addColumn(
                (new ColumnTable(
                    'article', 'Артикул'
                ))
            )
            ->addColumn(
                (new ColumnTable(
                    'brand', 'Производитель'
                ))
            )
//            ->addColumn(
//                (new ColumnTable(
//                    'desc', 'Характеристики'
//                ))
//                    ->setWidth(10, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'price', 'Цена'
                ))
            )
            ->addColumn(
                (new ColumnTable(
                    'amount', 'Кол-во'
                ))
            )
//            ->addColumn(
//                (new ColumnTable(
//                    'managerComment', 'Коментарий менеджера'
//                ))
//                    ->setWidth(15, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'stateId', 'Состояние'
                ))
                    ->setFormat($this, 'formatState')
            )
            ->addColumn(
                (new ColumnTable(
                    'contractorId', 'Поставщик'
                ))
                    ->setFormat($this, 'formatStock')
            )
            ->addColumn(
                (new ColumnTable(
                    'actions', ''
                ))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(120)
            );


        $table
            ->addFilter(
                $this->controlBuilder->buildInput('filter_by_orderCode')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_name')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_article')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_brand')
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_contractorId', Form::prepareDropdown($stocks))
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_providerId', Form::prepareDropdown($providers))
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_stateId', Form::prepareDropdown($states))
            );

        $table
            ->addField(
                $this->controlBuilder
                    ->buildTextLabel('orderCode')
                    ->setFn($this, 'formatOrder')
            )
            ->addField(
                $this->controlBuilder->buildInput('name'), true
            )
            ->addField(
                $this->controlBuilder->buildInput('article')
            )
            ->addField(
                $this->controlBuilder->buildInput('brand')
            )
            ->addField(
                $this->controlBuilder->buildInput('price'), true
            )
            ->addField(
                $this->controlBuilder->buildInput('amount'), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('stateId', Form::prepareDropdown($states)), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('contractorId', Form::prepareDropdown($providers)), true
            )
            ->addField(
                $this->controlBuilder->buildTextArea('managerComment'), false, 'Коментарий менеджера'
            )
            ->addField(
                $this->controlBuilder->buildTextArea('desc'), false, 'Характеристики'
            )
            ->addField(
                $this->controlBuilder->buildInput('destination'), false, 'Направление'
            );


        foreach ($states as $state) {
            $table
                ->addRowActionCommand(
                    'change-state-selected-' . $state->getId(),
                    new ChangeStateCommand($table, $state, $this->checkoutUseCase),
                    sprintf('Сменить на состояние `%s`', $state->getTitle())
                );
        }


        return $table->render();
    }

    public function formatStockContractor(ProviderOrderItemEntityInterface $item): string
    {
        return $item->getOrder()->getCustomer()->getName();
    }

}