<?php


namespace Shop\Application\Analytics\CreateTransaction;


use Core\Template\Template;
use Core\TwigAwareInterface;
use Core\TwigAwareTrait;
use Shop\Infrastructure\Models\Position\Position;
use Shop\Infrastructure\Repositories\PricePosition\PricePositionCriteria;
use Shop\Infrastructure\Repositories\PricePosition\PricePositionRepository;
use Widgets\Google\AnaliticTransaction\AnaliticTransaction;

class CreateTransactionHandler implements TwigAwareInterface
{
    use TwigAwareTrait;

    protected $template;
    protected $pricePositionRepository;

    public function __construct(Template $template,
                                PricePositionRepository $pricePositionRepository)
    {
        $this->template = $template;
        $this->pricePositionRepository = $pricePositionRepository;
    }

    /**
     * @param CreateTransactionCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \ReflectionException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function handle(CreateTransactionCommand $command): void
    {
        $order = $command->getOrder();

        $analitic = new AnaliticTransaction($this->template,$this->twig);

        /**
         * @var Position $position
         */
        foreach($order->getOrderItems() as $item){

            $positions = $this->pricePositionRepository->findByCriteria(
                PricePositionCriteria::create()->setFilterByRefId($item->getRefId())
            );

            $position = $positions->current();

            if($position){
                $catName = $position->getProduct()->getCategory()->getNameWithParent();
            }
            else{
                $catName = 'без категории';
            }

            $analitic->addItem(
                $order->getId(),
                $item->getName(),
                $item->getArticle(),
                $item->getBrand(),
                $catName,
                $item->getPrice(),
                $item->getDesc(),
                $item->getAmount()
            );
        }

        $analitic->setTransaction(
            $order->getId(),
            $order->getCustomer()->getManager()->getShop()->getTitleWithType(),
            $order->getSumm(),
            0,//доставка
            0//налог
        );

        //в шаблон js скрипт
        $analitic->render();
    }
}