<?

namespace Shop\Services;

use Shop\Exceptions\ManagerNotSetException;
use Shop\Exceptions\ShopNotFound;
use Shop\Models\Shop\Shop as ShopModel;

/**
 * Магазин
 *
 * @author Admin
 */
class Shop
{

    protected $shopRepo;
    protected $session;
    protected $request;
    protected $authService;

    private $cacheActiveStock;

    public function __construct(\Shop\Repositories\Shop $shopRepo,
                                \Symfony\Component\HttpFoundation\Session\Session $session, 
                                \Symfony\Component\HttpFoundation\Request $request, 
                                \Shop\Services\Auth $authService
            )
    {
        $this->shopRepo = $shopRepo;
        $this->session = $session;
        $this->request = $request;
        $this->authService = $authService;
    }

    /**
     * @return ShopModel
     * @throws ShopNotFound
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function getCurrentOrDefaultShop(): \Shop\Models\Shop\Shop
    {
        $shop = $this->getCurrentShop();

        if($shop->getManagers()->count()==0){
            $shop = $this->shopRepo->findOneMain();
        }

        if(!$shop){
            throw new ShopNotFound();
        }

        return $shop;
    }
    
    
    public function getShopTypes()
    {
        return [
            "main"     => ShopModel::MSG_SHOP_MAIN,
            "dealer"   => ShopModel::MSG_SHOP_DEALER,
            "stock"    => ShopModel::MSG_SHOP_STOCK,
            "provider" => ShopModel::MSG_SHOP_PROVIDER
        ];
    }

    /**
     * 
     * @param \Shop\Models\City\City $city
     * @return type
     */
    public function getShopByCity(\Shop\Models\City\City $city)
    {
        $shop = \Shop\Models\Shop\ShopQuery::create()
                ->useAddressQuery()
                ->filterByCity($city)
                ->endUse()
                ->findOne();

        if ( ! $shop) {
            $shop = \Shop\Models\Shop\ShopQuery::create()
                    ->useAddressQuery()
                    ->useCityQuery()
                    ->filterByRegionId($city->getRegionId())
                    ->endUse()
                    ->endUse()
                    ->findOne();
        }

        if ( ! $shop) {
            $shop = $this->shopRepo->findOneMain();
        }

        return $shop;
    }

    /**
     * @return ShopModel|null
     */
    protected function getActiveStock(): ?\Shop\Models\Shop\Shop
    {
//        $activeStock = input_get("select-stock") ?: $this->session->get("active_stock");
//
//        if ( ! $this->session->get("active_stock") && $activeStock > 0) {
//            $this->session->set("active_stock", $activeStock);
//        }

        if(! $activeStock = input_get("select-stock")){
            return null;
        }

        return $this->shopRepo->setSelectFilter(function(\Shop\Models\Shop\ShopQuery $q){
            return $q->useManagerQuery()
                        ->filterById(0, \Propel\Runtime\ActiveQuery\Criteria::GREATER_THAN)
                    ->endUse();
        })->findById($activeStock);
    }

    /**
     * Получение корректного магазина
     * @return \Shop\Models\Shop\Shop
     */
    public function getCurrentShop(): ShopModel
    {

        if($this->cacheActiveStock){
            return $this->cacheActiveStock;
        }

        $activeStock = $this->getActiveStock();

        if ( ! $activeStock) {

            $shops = \Shop\Models\Shop\ShopQuery::create()
                    ->useManagerQuery()
                        ->filterById(0, \Propel\Runtime\ActiveQuery\Criteria::GREATER_THAN)
                    ->endUse()
                    ->useDomainQuery()
                    ->orderById(\Propel\Runtime\ActiveQuery\Criteria::DESC)
                    ->filterByDomain(
                            sprintf("'%s' REGEXP `domain`", $this->request->getHost()),
                                    \Propel\Runtime\ActiveQuery\Criteria::CUSTOM)
                    ->endUse()
                    ->filterByActive("Y")
                    ->filterByType(["main","dealer"])
                    ->find();



            if ($shops->count() > 0) {
                $activeStock = $shops->getFirst();
            } else {
                $activeStock = $this->shopRepo->findOneMain();
            }
        }
        
        if(!$activeStock){
            $activeStock = $this->shopRepo->findOne()   ;
        }

        $this->cacheActiveStock = $activeStock;

        return $activeStock;
    }
    
    /**
     * 
     * @param \Shop\DTO\DealerComplex $dealerComplex
     */
    public function createDealerComplex(\Shop\DTO\DealerComplex $dealerComplex)
    {
        
        if(!$group = \Diamond\Models\UserGroup\UserGroupQuery::create()->findOneByGrpCode("admin")){
            
           throw new \Shop\Exceptions\UserGroupNotFoundException("group admin not found"); 
        }
        
        $domain = (new \Diamond\Models\Domain\Domain())
                ->setName($dealerComplex->getDomainName())
                ->setLang($dealerComplex->getDomainLang())
                ->setDomain($dealerComplex->getDomainDomain())
                ;
        
        $domain->save();
       

        $address 
                = (new \Shop\Models\Address\Address)
                ->setCityId($dealerComplex->getStockCityId())
                ->setStreet($dealerComplex->getStockStreet())
                ->setHouse($dealerComplex->getStockHouse())
                ->setRoom($dealerComplex->getStockRoom())
                ;
        
        $shop 
                = (new ShopModel)
                ->setType("dealer")
                ->setTitle($dealerComplex->getStockName())
                ->setAddress($address)
                ->setDomainId($domain->getId())
                ;
        
        $manager 
                = (new \Shop\Models\Manager\Manager)
                ->setName($dealerComplex->getUserName())
                ->setEmail($dealerComplex->getUserEmail())
                ->setShop($shop)
                ;
        $manager->save();
        
        $user = (new \Diamond\Models\User\User)
                ->setName($dealerComplex->getUserName())
                ->setPassword(md5($dealerComplex->getUserPassword()))
                ->setEmail($dealerComplex->getUserEmail())
                ->setUserGroup($group)
                ;
        
        $user->save();
        
        //копирование страниц
        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();
            }
        }
        
        //копирование меню
        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);
        //копирование контента
        
        //копирование шаблонов        
        
    }

}