<?php
namespace Shop\Modules\AdminOrders;

use ActiveTable\Contracts\CommandInterface;
use Shop\Application\Shopping\Exceptions\ShoppingException;
use Shop\Application\Shopping\SendCustomerOrders\SendCustomerOrdersException;
use Shop\Application\Shopping\ShoppingService;
use Shop\Domain\State\Contracts\StateEntityInterface;
use Shop\Helpers\Form;
use Shop\Models\Order\Order;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SendNotificationCommand implements CommandInterface
{

    protected $checkoutUseCase;
    protected $forManager;

    /**
     * SendNotificationCommand constructor.
     * @param Checkout $checkoutUseCase
     * @param bool $forManager
     */
    public function __construct(ShoppingService $checkoutUseCase, bool $forManager = false)
    {
        $this->checkoutUseCase = $checkoutUseCase;
        $this->forManager = $forManager;
    }

    /**
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): void
    {
        //получаем id заказов
        $ids = Form::getIdsFromRequest();

        //вызываем метод отправки заказов на email
        try {
            $orders = $this->checkoutUseCase->sendCustomerOrdersByIds($ids,$this->forManager===false,$this->forManager===true);

        } catch (SendCustomerOrdersException $exception) {
            Form::addTableNotice(Form::buildErrorMessage('Некоторые заказы не были отправлены.'));
            $orders = $exception->getSuccess();
        } catch (ShoppingException $exception) {
            Form::addTableNotice(Form::buildErrorMessage('Отправку заказов поставщикам не удалось произвести'));
        }

        /**
         * @var Order $order
         * @var StateEntityInterface $state
         */
        if (isset($orders)) {
            $links = [];

            foreach ($orders as $order) {
                $links [] = $order->getOrderCode();
            }
            Form::addTableNotice(Form::buildSuccessMessage(
                sprintf('Отправка заказов %s %s успешно произведена.',
                    implode(', ', $links),
                    ($this->forManager===true?'менеджерам':'клиентам')
                )
            ));
        }

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

}