<?php

namespace Lc\ShopBundle\Controller\Backend;

use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Lc\ShopBundle\Context\NewsInterface;
use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Services\MailUtils;
use Lc\ShopBundle\Services\UtilsManager;
use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
use \Mailjet\Resources ;

class NewsController extends AdminController
{
        protected $parameterBag ;

        public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
                                    MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator,
                                    ParameterBagInterface $parameterBag)
        {
                $this->parameterBag = $parameterBag ;
                parent::__construct($security, $userManager, $em, $mailjetTransport, $utilsManager, $translator);
        }

        public function sendTestAction()
        {
                $newsletter = $this->getNewsletter() ;
                $news = $this->getNews() ;

                $merchantCurrent = $this->merchantUtils->getMerchantCurrent() ;
                $merchantConfigEmailContact = $merchantCurrent->getMerchantConfig('email-contact');

                if($merchantConfigEmailContact && strlen($merchantConfigEmailContact)) {
                        $this->mailUtils->send([
                                MailUtils::SUBJECT => $news->getTitle(),
                                MailUtils::TO_EMAIL => $merchantConfigEmailContact,
                                MailUtils::TO_NAME => $this->parameterBag->get('app.site_name'),
                                MailUtils::CONTENT_TEMPLATE => 'mail/news',
                                MailUtils::CONTENT_DATA => [
                                        'news' => $news,
                                        'newsletter' => $newsletter,
                                        'user' => $this->security->getUser()
                                ],
                        ]);

                        $this->addFlash('success', 'Actualité de test envoyée à '.$merchantConfigEmailContact);
                }
                else {
                        throw new \ErrorException("L'email de contact n'est pas défini pour ce Merchant.") ;
                }

                return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;
        }

        public function sendAction()
        {
                ini_set('memory_limit', '-1');
                set_time_limit(0);

                $currentMerchant = $this->merchantUtils->getMerchantCurrent() ;
                $newsletter = $this->getNewsletter() ;
                $news = $this->getNews() ;
                $users = $this->em->getRepository($this->em->getClassMetadata(UserInterface::class)->getName())->findAllByNewsletter($newsletter) ;
                
                $countUsers = count($users) ;

                $packageMessagesArray = [];
                $packageMessageLimit = 50 ;

                $paramsTemplate = [
                        'news' => $news,
                        'newsletter' => $newsletter,
                        'user' => $this->security->getUser()
                ] ;

                $i = 0 ;
                foreach ($users as $user) {
                        if(!isset($packageMessagesArray[$i])) {
                                $packageMessagesArray[$i] = [] ;
                        }

                        if($user->getEmail() && strlen($user->getEmail())) {
                                $packageMessagesArray[$i][] = [
                                        'To' => [
                                                [
                                                        'Email' => $user->getEmail(),
                                                        'Name' => $user->getFirstname().' '.$user->getLastname(),
                                                ]
                                        ],
                                        'From' => [
                                                'Email' => $this->getParameter('app.noreply_email'),
                                                'Name' => $this->getParameter('app.site_name')
                                        ],
                                        'Subject' => $currentMerchant->getMerchantConfig('email-subject-prefix').' '.$news->getTitle(),
                                        'TextPart' => $this->renderView('mail/news-text.html.twig', $paramsTemplate),
                                        'HTMLPart' => $this->renderView('mail/news-html.html.twig', $paramsTemplate),
                                        'CustomCampaign' => $news->getTitle(),
                                        'DeduplicateCampaign' => true
                                ] ;

                                if(count($packageMessagesArray[$i]) >= $packageMessageLimit) {
                                        $i ++ ;
                                }
                        }
                }

                if($countUsers > 0) {
                        $mj = new \Mailjet\Client($this->mailjetTransport->getApiKey(), $this->mailjetTransport->getApiSecret(),true,['version' => 'v3.1']);

                        foreach($packageMessagesArray as $messagesArray) {
                                $body = [
                                        'Messages' => $messagesArray
                                ];
                                $response = $mj->post(Resources::$Email, ['body' => $body]);
                        }

                        if(isset($response) && $response->success()) {
                                $this->addFlash('success', 'Actualité envoyée à '.$countUsers.' utilisateurs.');

                                $news->setIsSent(true) ;
                                $this->em->persist($news);
                                $this->em->flush() ;
                        }
                        else {
                                $this->addFlash('error', "Une erreur est survenue lors de l'envoi de l'actualité.");
                        }
                }
                else {
                        $this->addFlash('error', 'Aucun utilisateur inscrit à la newsletter.');
                }

                return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;
        }

        public function getNewsletter()
        {
                $newsletter = $this->merchantUtils->getMerchantCurrent()->getNewsletter() ;
                if($newsletter) {
                        return $newsletter ;
                }
                else {
                        throw new \ErrorException('Aucune newsletter n\'est liée à ce Merchant.') ;
                }
        }

        public function getNews()
        {
                $idNews = $this->request->get('id') ;
                $news = $this->em->getRepository($this->em->getClassMetadata(NewsInterface::class)->getName())->find($idNews) ;

                if($news) {
                        return $news ;
                }
                else {
                        throw new NotFoundHttpException('Actualité introuvable') ;
                }
        }

}