<?php

namespace Lc\ShopBundle\Services ;

use App\Entity\UserMerchant;
use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\UserMerchantInterface;
use Symfony\Component\Security\Core\Security;

class MerchantUtils
{

        protected $security ;
        protected $em ;

        public function __construct(Security $security, EntityManagerInterface $em)
        {
                $this->security = $security ;
                $this->em = $em ;
        }

        public function initUserMerchant($params = [])
        {
                $classUserMerchant = $this->em->getClassMetadata(UserMerchantInterface::class)->getName() ;
                $userMerchantRepository = $this->em->getRepository($classUserMerchant) ;

                $user = isset($params['user']) ? $params['user'] : null ;
                $merchant = isset($params['merchant']) ? $params['merchant'] : null ;
                $active = isset($params['active']) ? $params['active'] : true ;
                $flush = isset($params['flush']) ? $params['flush'] : true ;
                $persist = isset($params['persist']) ? $params['persist'] : true ;

                $userMerchant = $userMerchantRepository->findOneBy([
                        'user' => $user,
                        'merchant' => $merchant
                ]) ;

                if(!$userMerchant) {
                        $userMerchant = new $classUserMerchant ;
                        $userMerchant->setUser($user) ;
                        $userMerchant->setMerchant($merchant) ;
                        $userMerchant->setCreditActive(false);
                }

                $userMerchant->setActive($active) ;

                if(isset($params['credit_active'])) {
                        $userMerchant->setCreditActive($params['credit_active']) ;
                }

                if(isset($params['credit'])) {
                        $userMerchant->setCredit($params['credit']) ;
                }

                if($persist) {
                        $this->em->persist($userMerchant);
                }

                if($flush) {
                        $this->em->flush() ;
                }

                return $userMerchant ;
        }

}
