<?php

namespace AppBundle\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use AppBundle\Entity\Contact;
use AppBundle\Entity\Content;
use AppBundle\Entity\Menu;
use AppBundle\Entity\Testimonial;
use AppBundle\Enum\MediaType;
use AppBundle\Enum\TypeTemplateTitle;
use AppBundle\Form\Type\Front\ContactFormType;
use AppBundle\Helper\MenuHelper;
use AppBundle\Mail\ContactMailer;
use AppBundle\Translation\ConstTranslator;
use AppBundle\Security\GRecaptchaHandler;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\TranslatorInterface;

class TemplatesController extends Controller
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var ConstTranslator
     */
    private $utils;

    /**
     * @var GRecaptchaHandler
     */
    private $recaptcha;
    
    public function __construct(EntityManagerInterface $em, TranslatorInterface $translator, ConstTranslator $utils, GRecaptchaHandler $recaptcha)
    {
        $this->em = $em;
        $this->translator = $translator;
        $this->utils = $utils;
        $this->recaptcha = $recaptcha;
    }

    /**
     * Affiche les pages possédant un template
     *
     * @Route(
     *      "/{id}-{title}",
     *      requirements = {"id": "\d+"},
     *      name = "template"
     * )
     * @Route(
     *      "/{idlevel1}-{titlelevel1}/{id}-{title}",
     *      requirements = {
     *          "idlevel1": "\d+",
     *          "id": "\d+"
     *      },
     *      name = "template_level2"
     * )
     * @Route(
     *      "/{idlevel1}-{titlelevel1}/{idlevel2}-{titlelevel2}/{id}-{title}",
     *      requirements = {
     *          "idlevel1": "\d+",
     *          "idlevel2": "\d+",
     *          "id": "\d+"
     *      },
     *      name = "template_level3"
     * )
     * @ParamConverter(
     *      "menu", class="AppBundle:Menu"
     * )
     *
     * @param Menu $menu
     * @param Request $Request
     * @param ContactMailer $contactMailer
     * @return null|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Menu $menu, Request $request, ContactMailer $contactMailer)
    {
        $tplTitle = $menu->getTypeTemplate()->getTitle();
        $return = null;

        // MAIN
        $mainContent = $this->em->getRepository('AppBundle:Content')->findOneBy(
            array(
                'is_main' => true,
                'menu' => $menu,
            ),
            array(
                'position' => 'ASC',
                'id' => 'ASC',
            )
        );

        if (TypeTemplateTitle::SIMPLE === $tplTitle) {
            $return = $this->render('Front/Templates/simple.html.twig', array(
                'maincontent' => $mainContent,
                'menu' => $menu,
            ));
        } elseif (TypeTemplateTitle::LIST === $tplTitle) {
            $contents = $this->em->getRepository('AppBundle:Content')->findBy(
                array(
                    'is_active' => true,
                    'is_main' => false,
                    'is_module' => false,
                    'menu' => $menu,
                ),
                array(
                    'position' => 'ASC',
                    'id' => 'ASC',
                )
            );

            $layout = MenuHelper::getLayoutPath($menu);
            
            if (empty($layout)) {
                // No break legacy
                $layout = 'Front/Templates/Liste/default.html.twig';
            }

            $return = $this->render($layout, array(
                'maincontent' => $mainContent,
                'contents' => $contents,
                'menu' => $menu,
            ));
        } elseif (TypeTemplateTitle::PRESENTATION === $tplTitle) {
            $contents = $this->em->getRepository('AppBundle:Content')->findWithMenu($menu->getId(), false, [
                'is_active' => true,
                'is_main' => false,
                'is_module' => false,
            ]);

            // $pictures = $this->em->getRepository('AppBundle:Media')->findByMenu(
            //     $menu->getId(),
            //     array(
            //         'is_active' => true,
            //         'type' => MediaType::PICTURE,
            //     )
            // );
            // $videos = $this->em->getRepository('AppBundle:Media')->findByMenu(
            //     $menu->getId(),
            //     array(
            //         'is_active' => true,
            //         'type' => MediaType::VIDEO,
            //     )
            // );

            // Liste des opérations PEE ouvertes pour la page Actions > Opérations Professeurs en Entreprise
            // $operationsPEE = array();
            // if (84 === $menu->getId()) {
            //     $operationsPEE = $this->em->getRepository('AppBundle:OperationPEE')->findAllWithDemandesPEEInscrits();
            // }

            $return = $this->render('Front/Templates/presentation.html.twig', array(
                'maincontent' => $mainContent,
                'contents' => $contents,
                'menu' => $menu,
                // 'operationsPEE' => $operationsPEE,
                // 'pictures' => $pictures,
                // 'videos' => $videos,
            ));
        } elseif (TypeTemplateTitle::LIST_CHILD === $tplTitle) {
            $menuChildren = $menu->getChildren();

            if (TypeTemplateTitle::MEDIA === $menuChildren[0]->getTypeTemplate()->getTitle()) {
                $return = $this->redirectToRoute('list_media', array(
                    'catid' => 0,
                    'catslug' => 'All',
                    'id' => $menu->getId(),
                    'slug' => $menu->getSlug(),
                ));
            } elseif (TypeTemplateTitle::NEWS === $menuChildren[0]->getTypeTemplate()->getTitle()) {
                $return = $this->redirectToRoute('list_actu', array(
                    'catid' => 0,
                    'catslug' => 'All',
                    'id' => $menu->getId(),
                    'slug' => $menu->getSlug(),
                ));
            }
            else {
                $layout = MenuHelper::getLayoutPath($menu);
            
                if (empty($layout)) {
                    // No break legacy
                    $layout = 'Front/Templates/ListChild/default.html.twig';
                }

                $return = $this->render($layout, array(
                    'maincontent' => $mainContent,
                    'children' => $menuChildren,
                    'menu' => $menu
                ));
            }
        } elseif (TypeTemplateTitle::CONTACT === $tplTitle) {
            // Formulaire de contact 
            $contact = new Contact;

            $form = $this->createForm(ContactFormType::class, $contact, [
                'google_recaptcha_public_key' => $this->getParameter("google.recaptcha.public_key")
            ]);
            $form->handleRequest($request);

            if ($form->isSubmitted()) {
                if ($form->isValid()) {

                    $result = $this->recaptcha->validateGRecaptchaResponse($request);

                    if (is_array($result) && count($result) > 0) {
                        foreach ($result as $error) {
                            $this->addFlash('contact_form_error', 'Erreur: ' . $error);
                        }
                    } elseif ($result === true) {

                        $contact->setCreated(new \DateTime);

                        $this->em->persist($contact);
                        $this->em->flush();

                        $user = $this->getUser();
                        $responses = $contactMailer->sendContactData($contact, $user);
                        $this->addFlash('contact_form_success', 'Message envoyé');

                        //Redirect to same page
                        //return $this->redirectToRoute($request->attributes->get('_route'), $request->attributes->get('_route_params'));
                        $return = $this->render('Front/Default/index.html.twig', array());
                    }
                } else {
                    $this->addFlash('contact_form_error', 'Erreur. Veuillez vérifier les champs.');
                }
            }

            $return = $this->render('Front/Templates/contact.html.twig', array(
                'maincontent' => $mainContent,
                'menu' => $menu,
                'form' => $form->createView(),
            ));
        }

        if (null === $return) {
            return $this->redirectToRoute('_welcome');
        }

        return $return;
    }

    /**
     * Affiche une page de type Media
     *
     * @Route(
     *      "/media/{id}-{slug}/{catid}-{catslug}/{page}",
     *      name = "list_media"
     * )
     *
     * @param $id
     * @param string $slug
     * @param string $catid
     * @param string $catslug
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function mediaAction($id, $slug, $catid, $catslug, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.max_per_page');
        $firstresult = ($page - 1) * $resultsMaxPerPage;
        
        $contents = $this->em->getRepository('AppBundle:Content')->findWithMenu($id, false, ['is_main' => true]);
        $content = $contents[0];

        if ('All' == $catslug) {
            /*
            $queryvideos = $this->em
                ->createQuery(
                    "SELECT m,n FROM AppBundle:Media m
                        LEFT JOIN m.menu n
                        WHERE m.type = :typepicture
                            AND m.is_active = :isactive
                            AND n.id in (SELECT mm.id FROM AppBundle:Menu mm WHERE mm.parent=:menuid)
                        ORDER BY m.position ASC, m.id ASC"
                )
                ->setParameters(array(
                    'isactive' => true,
                    'typepicture' => MediaType::VIDEO,
                    'menuid' => $content->getMenu()->getId(),
                ));
                */
                $queryvideos = $this->em
                ->createQuery(
                    "SELECT m,n FROM AppBundle:Media m
                        LEFT JOIN m.menu n
                        WHERE m.type = :typepicture
                            AND m.is_active = :isactive
                            AND n.id in (SELECT mm.id FROM AppBundle:Menu mm WHERE mm.parent=:menuid)
                        ORDER BY m.created DESC"
                )
                ->setParameters(array(
                    'isactive' => true,
                    'typepicture' => MediaType::VIDEO,
                    'menuid' => $content->getMenu()->getId(),
                ));
        } else {
            /*
            $queryvideos = $this->em
                ->createQuery(
                    "SELECT m,n FROM AppBundle:Media m
                        LEFT JOIN m.menu n
                        WHERE m.type = :typepicture
                            AND m.is_active = :isactive
                            AND n.id = :menuid
                        ORDER BY m.position ASC, m.id ASC"
                )
                ->setParameters(array(
                    'isactive' => true,
                    'typepicture' => MediaType::VIDEO,
                    'menuid' => $catid,
                ));
                */

                $queryvideos = $this->em
                ->createQuery(
                    "SELECT m,n FROM AppBundle:Media m
                        LEFT JOIN m.menu n
                        WHERE m.type = :typepicture
                            AND m.is_active = :isactive
                            AND n.id = :menuid
                        ORDER BY m.created DESC"
                )
                ->setParameters(array(
                    'isactive' => true,
                    'typepicture' => MediaType::VIDEO,
                    'menuid' => $catid,
                ));
        }

        $queryvideos->setFirstResult($firstresult)
                   ->setMaxResults($resultsMaxPerPage);

        $videos = new Paginator($queryvideos);

        $nbPage = ceil(count($videos) / $resultsMaxPerPage);

        if ($nbPage > 0) {
            // Constructeur pagination
            $pagination = range(1, $nbPage);
        }
        else {
            $pagination = array(1);
        }

        return $this->render('Front/Templates/media.html.twig', array(
            'videos' => $videos,
            'selected_catid' => $catid,
            'selected_catslug' => $catslug,
            'content' => $content,
            'pagination' => $pagination,
        ));
    }

    /**
     * Affiche les actualités, éventuellement filtrées par type
     *
     * @Route(
     *      "/actualites/{id}-{slug}/{catid}-{catslug}/{page}",
     *      requirements = {"id": "\d+", "page": "\d+"},
     *      name = "list_actu"
     * )
     * @param int $id
     * @param $slug
     * @param $catid
     * @param $catslug
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listActuAction(int $id, $slug, $catid, $catslug, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.max_per_page');
        $firstresult = ($page - 1) * $resultsMaxPerPage;
        
        $contents = $this->em->getRepository('AppBundle:Content')->findWithMenu($id, true, ['is_main' => true]);
        $content = $contents[0];

        if ('All' == $catslug) {
            $queryactus = $this->em
                ->createQuery(
                    "SELECT m FROM AppBundle:Content m
                        WHERE m.menu in (SELECT mm.id FROM AppBundle:Menu mm WHERE mm.parent=:menuid)
                            AND m.is_actu = :isactu
                            AND m.is_active = :isactive
                            AND (m.publish < :today OR m.publish IS NULL)
                            AND (m.unpublish > :today OR m.unpublish IS NULL)
                        ORDER BY m.position ASC, m.created DESC, m.id DESC"
                )
                ->setParameters(array(
                    'menuid' => $content->getMenu()->getId(),
                    'isactu' => true,
                    'isactive' => true,
                    'today' => new \DateTime(),
                ));
        } else {
            $queryactus = $this->em
                ->createQuery(
                    "SELECT m FROM AppBundle:Content m
                    WHERE m.menu = :menuid
                        AND m.is_active = :isactive
                        AND m.is_actu = :isactu
                        AND (m.publish < :today OR m.publish IS NULL)
                        AND (m.unpublish > :today OR m.unpublish IS NULL)
                    ORDER BY m.position ASC, m.created DESC, m.id DESC"
                )
                ->setParameters(array(
                    'menuid' => $catid,
                    'isactu' => true,
                    'isactive' => true,
                    'today' => new \DateTime(),
                ));
        }

        $queryactus->setFirstResult($firstresult)
                   ->setMaxResults($resultsMaxPerPage);

        $actus = new Paginator($queryactus);

        $nbPage = ceil(count($actus) / $resultsMaxPerPage);

        if ($nbPage > 0) {
            // Constructeur pagination
            $pagination = range(1, $nbPage);
        }
        else {
            $pagination = array(1);
        }

        return $this->render('Front/Templates/listactu.html.twig', array(
            'actus' => $actus,
            'selected_catid' => $catid,
            'selected_catslug' => $catslug,
            'content' => $content,
            'pagination' => $pagination,
        ));
    }

    /**
     * Affiche une actualité
     *
     * @Route(
     *      "/actualites/{idlevel1}-{titlelevel1}/{idlevel2}-{titlelevel2}/{id}-{title}",
     *      requirements = {
     *          "idlevel1": "\d+",
     *          "idlevel2": "\d+",
     *          "id": "\d+"
     *      },
     *      name = "single_actu"
     * )
     * @ParamConverter("menulist", class = "AppBundle:Menu", options = {"id" = "idlevel1"})
     * @ParamConverter("category", class = "AppBundle:Menu", options = {"id" = "idlevel2"})
     * @ParamConverter("actu", class = "AppBundle:Content")
     * @param Menu $menulist
     * @param Menu $category
     * @param Content $actu
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function actuAction(Menu $menulist, Menu $category, Content $actu)
    {
        if ($menulist->getIsActive() && $category->getIsActive() && $actu->getIsActive() && $actu->getIsActu()) {
            return $this->render('Front/Templates/actu.html.twig', array(
                'actu' => $actu,
                'parent' => $menulist,
                'category' => $category,
            ));
        }

        return $this->redirectToRoute('_welcome');
    }


    /**
     * Affiche une page de type Témoignages
     *
     * @Route(
     *      "/temoignages/{id}-{slug}/{page}",
     *      requirements = {"id": "\d+", "page": "\d+"},
     *      name = "list_testimonials"
     * )
     *
     * @param $id
     * @param string $slug
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listTestimonialsAction($id, $slug, int $page = 1)
    {
        $resultsMaxPerPage = $this->getParameter('results.max_per_page');
        $firstresult = ($page - 1) * $resultsMaxPerPage;
        
        $contents = $this->em->getRepository('AppBundle:Content')->findWithMenu($id, false, ['is_main' => true]);
        $content = $contents[0];

        $testimonials = $this->em->getRepository('AppBundle:Testimonial')->findBy(
            ['isActive' => true],
            ['created' => 'DESC'],
            $resultsMaxPerPage,
            $firstresult
        );

        $nbPage = ceil(count($testimonials) / $resultsMaxPerPage);

        if ($nbPage > 0) {
            // Constructeur pagination
            $pagination = range(1, $nbPage);
        }
        else {
            $pagination = array(1);
        }

        return $this->render('Front/Templates/listtestimonials.html.twig', array(
            'content' => $content,
            'testimonials' => $testimonials,
            'pagination' => $pagination,
        ));
    }

    /**
     * Affiche une page de type Partenaires
     *
     * @Route(
     *      "/partenaires/{id}-{slug}/{page}",
     *      name = "list_partners"
     * )
     *
     * @param $id
     * @param string $slug
     * @param int $page
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listPartnersAction($id, $slug, int $page = 1)
    {
        $resultsMaxPerPage = 1000; // List All
        $firstresult = ($page - 1) * $resultsMaxPerPage;
        
        $contents = $this->em->getRepository('AppBundle:Content')->findWithMenu($id, false, ['is_main' => true]);
        $content = $contents[0];

        $activeMenu = $this->em->getRepository('AppBundle:Menu')->findOneById($id);

        $filters = [ 'partnerCategory' => $activeMenu->getParams()->filter_category, 'displayInFront' => true ];

        if ($activeMenu->getParams()->filter_support == 'support_them') {
            $filters['supportThem'] = true;
        } else {
            $filters['supportUs'] = true;
        }

        $partners = $this->em->getRepository('AppBundle:Partner')->findBy(
            $filters,
            ['position' => 'ASC', 'name' => 'ASC', 'id' => 'ASC'],
            $resultsMaxPerPage,
            $firstresult
        );

        $nbPage = ceil(count($partners) / $resultsMaxPerPage);

        if ($nbPage > 0) {
            // Constructeur pagination
            $pagination = range(1, $nbPage);
        }
        else {
            $pagination = array(1);
        }

        $pageHeaderNav = array();

        $qbMenus = $this->em->createQueryBuilder();
        $qbMenus
            ->select('m2, m2tt, m3, m3tt')
            ->from('AppBundle:Menu', 'm2')
            ->leftJoin('m2.typeTemplate', 'm2tt')
            ->leftJoin('m2.children', 'm3')
            ->leftJoin('m3.typeTemplate', 'm3tt')
            ->leftJoin('m2.children', 'm1')
            ->where('m1.id=:menu_id')
            ->orderBy('m2.position', 'asc')
            ->addOrderBy('m2.id', 'asc')
            ->addOrderBy('m3.position', 'asc')
            ->addOrderBy('m3.id', 'asc')
            ->setParameters(array(
                'menu_id' => $id
            ));
        $menu = $qbMenus->getQuery()->getSingleResult();

        if ( !empty($menu) && !empty($menu->getChildren()) ) {
            foreach ($menu->getChildren() as $m) {
                if ($m->getIsActive() === true) {
                    $pageHeaderNav[] = array(
                        "id" => $m->getParams()->filter_category,
                        "link" => $this->generateUrl('list_partners', [ 'id' => $m->getId(), 'slug' => ( ($m->getParams()->filter_support == 'support_them') ? 'nous-les-soutenons-' : 'ils-nous-soutiennent-' ) . $m->getSlug() ]), // @TODO get good id please
                        "text" => $m->getTitle(),
                    );
                }
            }
        }

        return $this->render('Front/Templates/listpartners.html.twig', array(
            'content' => $content,
            'pageHeaderNav' => $pageHeaderNav,
            'pageHeaderActiveMenu' => $activeMenu->getParams()->filter_category,
            'partners' => $partners,
            'pagination' => $pagination,
        ));
    }

    /**
     * DEPRECATED 
     * 
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function modulesAction(Request $request)
    {
        if ('default' != $request->get('menu')) {
            $querymodules = $this->em
                ->createQuery("SELECT m FROM AppBundle:Content m WHERE m.is_module=:ismodule AND m.menu=:menu ORDER BY m.position ASC, m.id ASC")
                ->setParameters(array(
                    'ismodule' => true,
                    'menu' => $request->get('menu'),
                ));
            $modules = $querymodules->getResult();

            return $this->render('Front/Render/Legacy/modules.html.twig', array(
                'modules' => $modules,
            ));
        }

        return $this->render('Front/Render/Legacy/modules.html.twig');
    }

     /**
     * Affichage d'un témoignage
     *
     * @Route(
     *      "/temoignages/{idlevel1}-{titlelevel1}/{id}-{title}",
     *      requirements = {
     *          "idlevel1": "\d+",
     *          "id": "\d+"
     *      },
     *      name = "single_testimonial"
     * )
     * @ParamConverter("menulist", class = "AppBundle:Menu", options = {"id" = "idlevel1"})
     * @ParamConverter("testimonial", class = "AppBundle:Testimonial")
     * @param Menu $menulist
     * @param Testimonial $testimonial
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function testimonialAction(Menu $menulist, Testimonial $testimonial)
    {
        if ($menulist->getIsActive() && $testimonial->getIsActive()) {
            $contents = $this->em->getRepository('AppBundle:Content')->findWithMenu($menulist->getId(), false, ['is_main' => true]);
            $content = $contents[0];
            
            return $this->render('Front/Templates/testimonial.html.twig', array(
                'testimonial' => $testimonial,
                'parent' => $menulist,
                'maincontent' => $content
            ));
        }

        return $this->redirectToRoute('_welcome');
        
        
    }
}
