<?php

namespace Shop\Presentation\Modules\AdminOrderItems;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\ControlBuilder;
use Core\ModuleController;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Shop\Infrastructure\Repositories\OrderItem\OrderItemCriteria;
use Shop\Infrastructure\Repositories\OrderItem\OrderItemRepository;
use Shop\Infrastructure\Repositories\Provider\ProviderCriteria;
use Shop\Infrastructure\Repositories\Provider\ProviderRepository;
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;

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

    use FormatColumnsTrait;

    public function __construct(protected OrderItemRepository $repository,
                                protected TableFactory $tableFactory,
                                protected ControlBuilder $controlBuilder,
                                protected ProviderRepository $providerRepository,
                                protected StateRepository $stateRepository,
                                protected Checkout $checkoutUseCase,
                                protected StockRepository $stockRepository)
    {

    }

    /**
     * @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,
                OrderItemCriteria::create()
            )
            ->removeControlAccess(DataTableEngine::CONTROL_ACCESS_ADD)
            ->setDefaultSortColumn('id', 'DESC')
            ->addColumn(
                (new ColumnTable(
                    'id', '№'
                ))
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable(
                    'orderCode', 'Номер заказа'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatOrder')

            )
            ->addColumn(
                (new ColumnTable('datetime', 'Дата заказа'))
                    ->setExported(true)
                    ->setFormat($this, 'formatDate')

            )
            ->addColumn(
                (new ColumnTable(
                    'clientId', 'Клиент'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatClientFull')

            )

            ->addColumn(
                (new ColumnTable(
                    'name', 'Наименование товара'
                ))
                    ->setExported(true)

            )
            ->addColumn(
                (new ColumnTable(
                    'article', 'Артикул'
                ))
                    ->setExported(true)

            )
            ->addColumn(
                (new ColumnTable(
                    'brand', 'Производитель'
                ))
                    ->setExported(true)

            )
//            ->addColumn(
//                (new ColumnTable(
//                    'desc', 'Характеристики'
//                ))
//                    ->setWidth(10, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'price', 'Цена'
                ))
                    ->setExported(true)

            )
            ->addColumn(
                (new ColumnTable(
                    'amount', 'Кол-во'
                ))
                    ->setExported(true)
            )
//            ->addColumn(
//                (new ColumnTable(
//                    'managerComment', 'Коментарий менеджера'
//                ))
//                    ->setWidth(15, true)
//            )
            ->addColumn(
                (new ColumnTable(
                    'stateId', 'Состояние'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatState')

            )
            ->addColumn(
                (new ColumnTable(
                    'contractorId', 'Торговая точка'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatStock')

            )
            ->addColumn(
                (new ColumnTable(
                    'destination', 'Направление'
                ))
                    ->setExported(true)
            )
            ->addColumn(
                (new ColumnTable(
                    'providerId', 'Поставщик'
                ))
                    ->setExported(true)
                    ->setFormat($this, 'formatProvider')

            )
            ->addColumn(
                (new ColumnTable(
                    'actions', ''
                ))
                    ->setFormat($this, 'formatActions')
                    ->setWidth(110)
            );


        $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('providerId', 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('<i class="fa fa-refresh"></i> Сменить на состояние `%s`', $state->getTitle())
                );
        }

        $table
            ->addRowActionCommand(
                'create-provider-order-selected',
                new CreateProviderOrderCommand($table, $this->checkoutUseCase),
                '<i class="fa fa-file-text-o"></i> Создать заказ поставщику'
            );

        return $table->render();
    }




}               