<?php


namespace Shop\Modules\AdminOrderItems;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Helpers\Form;
use Shop\Application\Shopping\ShoppingService;
use Shop\Models\Order\Order;
use Shop\UseCases\Checkout\Checkout;
use Shop\UseCases\Checkout\Exceptions\CheckoutException;
use Shop\UseCases\Checkout\Exceptions\CreateProviderOrdersException;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CreateProviderOrderCommand implements CommandInterface
{
    protected $tableEngine;
    protected $checkoutUseCase;

    /**
     * CreateProviderOrderCommand constructor.
     * @param DataTableEngine $tableEngine
     * @param Checkout $checkoutUseCase
     */
    public function __construct(DataTableEngine $tableEngine, ShoppingService $checkoutUseCase)
    {
        $this->tableEngine = $tableEngine;
        $this->checkoutUseCase = $checkoutUseCase;
    }

    /**
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function process(): void
    {

        $ids = Form::getIdsFromRequest();

        try {
            $orders = $this->checkoutUseCase->createProviderOrdersFromCustomerOrderItemIds($ids);
        } catch (CreateProviderOrdersException $ex) {

            $orders = $ex->getSuccess();

            $errorsFound = $ex->getErrorFoundsIds();

            $errorsContr = $ex->getErrorContractors();

            $errorStates = $ex->getErrorStates();

            if(count($errorStates)){
                Form::addTableNotice(
                    Form::buildErrorMessage(sprintf('У позиций заказов %s уже есть оформленные заказы поставщику.',implode(',',$errorStates)))
                );
            }

            if(count($errorsFound)){
                Form::addTableNotice(
                    Form::buildErrorMessage(sprintf('Позиций заказов %s не были найдены.',implode(',',$errorsFound)))
                );
            }

            if(count($errorsContr)){
                Form::addTableNotice(
                    Form::buildErrorMessage(sprintf('У позиций заказов %s не указан контрагент поставщика.',implode(',',$errorsContr)))
                );
            }

        } catch (CheckoutException $ex) {
            Form::addTableNotice( Form::buildErrorMessage('Действие создание заказов поставщикам не удалось произвести') );
        }

        $links = [];


        if (isset($orders)) {
            /**
             * @var Order $order
             */
            foreach ($orders as $order) {
                $links [] = anchor(
                    '/admin/shop/customers/provider_orders?filter=1&filter_by_ordercode='.$order->getOrderCode(), 'Заказ поставщику №' . $order->getOrderCode(),[
                        'target'    =>  '_blank'
                    ]
                );
            }

        }

        if(count($links)){
            Form::addTableNotice(Form::buildSuccessMessage(
                sprintf('Создание заказов %s завершилось успешно. ', implode(', ', $links))
            ));
        }

        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }

}