<?php


namespace Shop\Application\Office\CreateDealer;


use Diamond\Repositories\Site\SiteRepository;
use Diamond\Repositories\User\UserRepository;
use Diamond\Repositories\UserGroup\UserGroupCriteria;
use Diamond\Repositories\UserGroup\UserGroupRepository;
use Shop\Application\Office\OfficeService;
use Shop\Presentation\Config\Main;
use Shop\Infrastructure\Repositories\Customer\CustomerRepository;
use Shop\Infrastructure\Repositories\Manager\ManagerRepository;
use Shop\Infrastructure\Repositories\Stock\StockRepository;

class CreateDealerHandler
{
    protected $userGroupRepository;
    protected $siteRepository;
    protected $stockRepository;
    protected $customerRepository;
    protected $mainConf;
    protected $managerRepository;

    /**
     * @var UserRepository
     */
    protected $userRepository;

    protected $officeService;

    /**
     * CreateDealerHandler constructor.
     * @param UserGroupRepository $userGroupRepository
     * @param StockRepository $stockRepository
     * @param CustomerRepository $customerRepository
     * @param Main $mainConf
     * @param UserRepository $userRepository
     * @param ManagerRepository $managerRepository
     * @param SiteRepository $siteRepository
     */
    public function __construct(UserGroupRepository $userGroupRepository,
                                StockRepository $stockRepository,
                                CustomerRepository $customerRepository,
                                Main $mainConf,
                                UserRepository $userRepository,
                                ManagerRepository $managerRepository,
                                OfficeService  $officeService,
                                SiteRepository $siteRepository)
    {
        $this->userGroupRepository = $userGroupRepository;
        $this->siteRepository = $siteRepository;
        $this->stockRepository = $stockRepository;
        $this->customerRepository = $customerRepository;
        $this->managerRepository = $managerRepository;
        $this->mainConf = $mainConf;
        $this->userRepository = $userRepository;
        $this->officeService = $officeService;
    }

    /**
     * @param CreateDealerCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function handle(CreateDealerCommand $command): void
    {

        $dealerComplex = $command->getRequest();

        $group = $this->userGroupRepository->findByCriteria(
            UserGroupCriteria::create()->setFilterByCode('admin')
        )->current();

        $mainStock = $this->officeService->getMainStock();

        if (!$group) {
            throw new CreateDealerException('admin group not found');
        }

        $domain =
            $this->siteRepository->buildEntityFromArray([])
                ->setName($dealerComplex->getDomainName())
                ->setLang($dealerComplex->getDomainLang())
                ->setDomain(
                //уберем точку если вдруг стоит и добавим самостоятельно
                    rtrim($dealerComplex->getDomainDomain(), '.') . '.'
                );

        $address
            = (new \Shop\Infrastructure\Models\Address\Address())
            ->setCityId($dealerComplex->getStockCityId())
            ->setStreet($dealerComplex->getStockStreet())
            ->setHouse($dealerComplex->getStockHouse())
            ->setRoom($dealerComplex->getStockRoom());

        /**
         * @var Shop $shop
         */
        $shop
            = $this->stockRepository->buildEntityFromArray([]);

        /**
         * @var Customer $contractor
         */
        $contractor = $this->customerRepository
            ->buildEntityFromArray([]);


        $contractor
            ->setCityId($dealerComplex->getStockCityId())
            ->setGroupId($this->mainConf->getDefaultContractorGroup())
            ->setName($dealerComplex->getStockName())
            ->setManager($this->officeService->getFirstManagerByStockId($mainStock->getId()))
            ->setEmail($dealerComplex->getEmail())
            ->setPhone($dealerComplex->getPhone());


        $shop
            ->setContractor($contractor)
            ->setType('dealer')
            ->setTitle($dealerComplex->getStockName())
            ->setAddress($address)
            ->setDomain($domain);

        $manager
            = $this->managerRepository->buildEntityFromArray([])
            ->setName($dealerComplex->getUserName())
            ->setEmail($dealerComplex->getUserEmail())
            ->setShop($shop);


        $user = $this->userRepository->buildEntityFromArray([])
            ->setName($dealerComplex->getStockName())
            ->setPassword(md5($dealerComplex->getUserPassword()))
            ->setEmail($dealerComplex->getUserEmail())
            ->setUserGroup($group);

        //save
        $manager->save();
        $user->save();

        return;


        //копирование страниц
        //@todo пока не используется ибо геммор
        if ($dealerComplex->getCopyPages() === true) {
            $pages
                = \Diamond\Models\Page\PageQuery::create()
                ->filterByActive("Y")
                ->filterByUrl("/personal%", \Propel\Runtime\ActiveQuery\Criteria::NOT_LIKE)
                ->useDomainQuery()
                ->filterByDomain(".*")
                ->endUse()
                ->filterBySystem("N")
                ->find();

            foreach ($pages as $page) {
                $pageDealer = $page->copy();
                $pageDealer->setDomain($domain);
                $pageDealer->save();
            }
        }

        //копирование меню
        //@todo пока не используется ибо геммор
        if ($dealerComplex->getCopyMenu() === true) {
            $menu
                = \Diamond\Models\Menu\MenuQuery::create()
                ->filterByName("main")
                ->find();

            foreach ($menu as $item) {
                $itemDealer = $item->copy();
                $itemDealer->setDomain($domain);
                $itemDealer->save();
            }
        }

        //копирование промоблоков
        if ($dealerComplex->getCopyPromoblocks() === true) {

            $promoblocks = \Diamond\Models\Promoblock\PromoblockQuery::create()
                ->useDomainQuery()
                ->filterByDomain(".*")
                ->endUse()
                ->find();

            foreach ($promoblocks as $promoblock) {
                $promoblockDealer = $promoblock->copy();
                $promoblockDealer->setDomain($domain);
                $promoblockDealer->save();
            }
        }
        //dump($promoblocks);
        //копирование контента

        //копирование шаблонов

    }

}