<?php

namespace Lc\ShopBundle\Controller\Backend;

use App\Form\Backend\Common\AddressType;
use FOS\UserBundle\Doctrine\UserManager;
use FOS\UserBundle\Model\UserManagerInterface ;
use Lc\ShopBundle\Context\AddressInterface;
use Lc\ShopBundle\Model\Address;

class UserController extends AdminController
{

        public function createNewEntity()
        {
                return $this->userManager->createUser();
        }

        public function persistEntity($user)
        {
                $this->userManager->updateUser($user, false);
                parent::persistEntity($user);
        }

        public function updateEntity($user)
        {
                $this->userManager->updateUser($user, false);
                parent::updateEntity($user);
        }

        public function removeEntity($user)
        {
                // désactivation UserMerchant
                if($user->getUserMerchants()) {
                        $merchant = $this->merchantUtils->getMerchantCurrent() ;
                        foreach($user->getUserMerchants() as $userMerchant) {
                                if($userMerchant->getMerchant() == $merchant) {
                                        $userMerchant->setActive(false) ;
                                        $this->em->persist($userMerchant);
                                        $this->em->flush() ;
                                        $this->addFlash('success', 'Utilisateur supprimé du hub');
                                }
                        }
                }
        }

        protected function createUserListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
        {
                $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter) ;

                $queryBuilder->innerJoin('entity.userMerchants', 'um') ;
                $queryBuilder->andWhere('um.merchant = :merchant AND um.active = 1') ;
                $queryBuilder->setParameter('merchant', $this->merchantUtils->getMerchantCurrent()) ;

                return $queryBuilder ;
        }
}
