<?php

namespace Shop\Modules\AdminProviderOrders;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\ControlBuilder;
use Core\Helpers\Text;
use Core\ModuleController;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Shop\Config\Main;
use Shop\Domain\ProviderOrder\Contracts\ProviderOrderEntityInterface;
use Shop\Modules\AdminOrders\FormatTrait;
use Shop\Modules\Traits\FormatterTrait;
use Shop\Repositories\ProviderOrder\ProviderOrderCriteria;
use Shop\Repositories\ProviderOrder\ProviderOrderRepository;
use Shop\Repositories\State\StateCriteria;
use Shop\Repositories\State\StateRepository;
use Shop\UseCases\Checkout\Checkout;

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

    use FormatTrait;
    use FormatterTrait;

    protected $tableFactory;
    protected $providerOrderRepository;
    protected $mainConfig;
    protected $stateRepository;
    protected $checkout;

    public function __construct(TableFactory $tableFactory, ProviderOrderRepository $providerOrderRepository,
                                ControlBuilder $controlBuilder, Main $mainConfig, StateRepository $stateRepository,
                                Checkout $checkout)
    {
        $this->tableFactory = $tableFactory;
        $this->providerOrderRepository = $providerOrderRepository;
        $this->controlBuilder = $controlBuilder;
        $this->mainConfig = $mainConfig;
        $this->stateRepository = $stateRepository;
        $this->checkout = $checkout;
    }


    /**
     * @return string
     * @throws \ReflectionException
     */
    public function process(): string
    {
        $table = $this->tableFactory->buildAdminTable($this->providerOrderRepository, ProviderOrderCriteria::create());
        $table->removeControlAccess(DataTableEngine::CONTROL_ACCESS_ADD);
        $table->removeControlAccess(DataTableEngine::CONTROL_ACCESS_DELETE);
        $table->setDefaultSortColumn('id', 'DESC');
        $currency = $this->mainConfig->getCurencyDisplay();
        $states = $this->stateRepository->findByCriteria(
            StateCriteria::create()
        );


        $table
            ->addRowActionCommand(
                'merge-orders-selected',
                new MergeProviderOrdersCommand($this->checkout),
                'Объеденить заказы'
            );
        $table
            ->addRowActionCommand(
                'send-orders-selected',
                new SendProviderOrderCommand($this->checkout, $this->mainConfig, $this->stateRepository),
                'Отправить поставщику на email'
            );

        $table
            ->addColumn(
                (new ColumnTable('ordercode', 'Код заказа'))
                    ->setFormat($this, 'formatCode')
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('datetime', 'Дата заказа'))
                    ->setFormat($this, 'formatDate')
            )
            ->addColumn(
                (new ColumnTable('customerId', 'Торговая точка'))
                    ->setFormat($this, 'formatStock')
            )
            ->addColumn(
                (new ColumnTable('paymentId', 'Способ оплаты'))
                    ->setFormat($this, 'formatPayment')
            )
            ->addColumn(
                (new ColumnTable('comment', 'Комментарий'))
                    ->setFormat($this, 'formatComment')
            )
            ->addColumn(
                (new ColumnTable('contractor', 'Поставщик'))
                    ->setFormat($this, 'formatProvider')
            )
            ->addColumn(
                (new ColumnTable('itemsCount', 'Товаров в заказе'))
                    ->setFormat($this, 'formatItemsCount')
                    ->setWidth(5, true)
            )
            ->addColumn(
                (new ColumnTable('sum', 'Сумма итого, ' . $currency))
                    ->setFormat($this, 'formatSumm')
            )
            ->addColumn(
                (new ColumnTable('stateId', 'Состояние'))
                    ->setFormat($this, 'formatStates')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this, 'formatProviderActions')
                    ->setWidth(120)
            );

        $table
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('ordercode')
                    ->setFn($this, 'formatCode')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('datetime')
                    ->setFn($this, 'formatDate')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('sumOrder')
                    ->setFn($this, 'formatSummOrder'),
                false, 'Сумма заказа, ' . $currency
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('discount')
                    ->setFn($this, 'formatDiscount'),false,'Скидка'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('sum')
                    ->setFn($this, 'formatSumm')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildFormHeader('Информация о торговой точке', 'client')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('customerId')
                    ->setFn($this, 'formatStockContractor')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('customerСontacts')
                    ->setFn($this, 'formatClientContacts'),
                false,
                'Контакты'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('deliveryAddress')
                , false, 'Адрес доставки'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('paymentId')
                    ->setFn($this, 'formatPayment')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildFormHeader('Информация о поставщике', 'stockHeader')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('contractor')
                    ->setFn($this, 'formatProvider'),
                false
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextLabel('providerContacts')
                    ->setFn($this, 'formatProviderContacts'),
                false,
                'Контакты поставщика'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildFormHeader('Данные заказа', 'orderInfo')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildTextArea('comment')
                , false, 'Комментарий к заказу'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownUniform('stateId', Form::prepareDropdown($states))
                , true, 'Состояние заказа'
            );


        $table
            ->addFilter(
                $this->controlBuilder->buildInput('filter_by_ordercode')
            )
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_stateId',Form::prepareDropdown($states))
            )
        ;

        return $table->render();
    }


    public function formatStockContractor(ProviderOrderEntityInterface $order): string
    {
        return $order->getCustomer()->getName();
    }

    /**
     * @param ProviderOrderEntityInterface $order
     * @return string
     */
    public function formatComment(ProviderOrderEntityInterface $order): string
    {
        if (!$order->getComment()) {
            return '';
        }
        return Text::characterLimiter($order->getComment(), 130);
    }

    /**
     * @param ProviderOrderEntityInterface $order
     * @return string
     */
    public function formatStock(ProviderOrderEntityInterface $order): string
    {
        return $order->getCustomer()->getname();
    }

    /**
     * @param ProviderOrderEntityInterface $order
     * @return string
     */
    public function formatProvider(ProviderOrderEntityInterface $order): string
    {
        return $order->getContractor()->getName();
    }

    /**
     * @param ProviderOrderEntityInterface $order
     * @return string
     */
    public function formatProviderContacts(ProviderOrderEntityInterface $order): string
    {
        return sprintf('email: %s,<br/>телефон: %s',
            $order->getContractor()->getEmail(),
            $order->getContractor()->getPhone()
        );
    }

    /**
     * @param ProviderOrderEntityInterface $order
     * @return string
     */
    public function formatProviderActions(ProviderOrderEntityInterface $order): string
    {

        $popup = sprintf(
            "window.open('/admin/shop/customers/order_print?id=%s&type=provider_order', 'test','right=100,width=600,height=400,left=100,menubar=no,location=no,status=no')",
            $order->getId()
        );

        return $this->controlBuilder->buildActionMenuAdmin([
            anchor(
                '/admin/shop/customers/provider_order_items?filter_by_orderCode=' . $order->getId(),
                Form::buildIconText('book_white', 'Содержимое')
            ),
            '<a onclick="' . $popup . '" href="javascript:void(0)">' . Form::buildIconText('print_white', 'Печать документа') . '</a>',


            anchor('javascript:void(0);', Form::buildIconText('message_white', 'Отправить поставщику'), [
                'onclick' => "action_row({$order->getId()},'send-orders-selected','Отправить письмо с заказом поставщику на email?')"
            ])

        ], $order->getId())->render();
    }
}               