<?php


namespace Shop\Application\Shopping\CreateCustomerOrder;


use Shop\Application\Office\OfficeService;
use Shop\Config\Main;
use Shop\Repositories\CustomerOrder\CustomerOrderRepository;

class CreateCustomerOrderHandler
{
    protected $mainConf;
    protected $customerOrderRepository;
    protected $officeService;

    use BuildOrderPositionTrait;

    /**
     * CreateCustomerOrderHandler constructor.
     * @param Main $mainConf
     * @param CustomerOrderRepository $customerOrderRepository
     * @param OfficeService $officeService
     */
    public function __construct(Main $mainConf, CustomerOrderRepository $customerOrderRepository,
                                OfficeService $officeService)
    {
        $this->mainConf = $mainConf;
        $this->customerOrderRepository = $customerOrderRepository;
        $this->officeService = $officeService;
    }

    /**
     * @param CreateCustomerOrderCommand $command
     */
    public function handle(CreateCustomerOrderCommand $command): void
    {
        $orderRequest = $command->getOrderRequest();

        $customer = $this->officeService->getCustomerById($orderRequest->getClientId());


        $order = CustomerOrderRepository::createEntity()
            ->setCustomerId($customer->getId())
            ->setContractorId($customer->getManager()->getShop()->getContractorId())
            //------------
            ->setPaymentId($orderRequest->getPaymentId())
            ->setComment($orderRequest->getComment())
            ->setDeliveryAddress($orderRequest->getDeliveryAddress())
            ->setStateId($this->mainConf->getStateDefault())
            ->setDiscountSumm($orderRequest->getDiscount());

        foreach ($orderRequest->getItems() as $item) {
            $orderItem = $this->buildOrderItem($item);
            $orderItem->setStateId($this->mainConf->getStateDefault());
            $order->addOrderItem($orderItem);
        }

        $this->customerOrderRepository->save($order);

        $command->getOrderResult()->setOrder($order);
    }
}