<?php

namespace AppBundle\Menu\Admin;

use AppBundle\Enum\OperationITDLCState;
use AppBundle\Enum\OperationITDLCType;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\TranslatorInterface;

class ActionStatBuilder
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * @var null|\Symfony\Component\HttpFoundation\Request
     */
    private $request;

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

    public function __construct(
        EntityManagerInterface $em,
        FactoryInterface $factory,
        RequestStack $requestStack,
        TranslatorInterface $translator
    )
    {
        $this->em = $em;
        $this->factory = $factory;
        $this->request = $requestStack->getCurrentRequest();
        $this->translator = $translator;
    }

    /**
     * @return ItemInterface
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function user(): ItemInterface
    {
        $menu = $this->factory->createItem('root');
        $routeParams = $this->request->get('_route_params');

        // Number of users that will be exported
        $usersQty = $this->em->getRepository('AppBundle:User')->findFromRequest($this->request, true, true);
        $menulabel = $this->translator->transchoice('action.export.' . $routeParams['type'], $usersQty, ['%count%' => $usersQty], 'action');

        $menu->setChildrenAttribute('class', 'menuCatalogue');
        $menu
            ->addChild('export', [
                'label' => $menulabel,
                'route' => 'admin_statistics_user_export',
                'routeParameters' => array_merge($routeParams, $this->request->query->all()),
            ])
            ->setLinkAttribute('class', 'btn btn-export')
        ;

        return $menu;
    }

    /**
     * @return ItemInterface
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function operationITDLC(): ItemInterface
    {
        if ($datemin = $this->request->get('datemin')) {
            $datemin = \DateTime::createFromFormat('d/m/Y', $datemin);
        }
        if ($datemax = $this->request->get('datemax')) {
            $datemax = \DateTime::createFromFormat('d/m/Y', $datemax);
        }
        $menu = $this->factory->createItem('root');
        $menu->setChildrenAttribute('class', 'menuCatalogue');

        // Create query
        $qb = $this->em->createQueryBuilder();
        $qb->select('COUNT(o)')
            ->from('AppBundle:OperationITDLC', 'o')
            ->leftJoin('o.availability', 'a')
            ->where('o.type = :o_type');
        $qb->setParameters([
            'o_type' => OperationITDLCType::OPERATION
        ]);
        if ($datemin) {
            $qb->andWhere('a.dateVisite >= :a_datemin');
            $qb->setParameter('a_datemin', $datemin);
        }
        if ($datemax) {
            $qb->andWhere('a.dateVisite <= :a_datemax');
            $qb->setParameter('a_datemax', $datemax);
        }
        $ope_state = $this->request->get('state');

        if ($ope_state !== 'all') {
            if (!empty($ope_state)) {
                $qb->andWhere('o.state IN (:o_state)');
                $qb->andWhere('o.state IN (:o_state)')
                   ->setParameter('o_state', $ope_state);
            }
            else {
                // Default
                $qb->andWhere('o.state = :o_state')
                   ->setParameter('o_state', OperationITDLCState::CLOSED);
            }
        }

        $operationsITDLCCount = $qb->getQuery()->getSingleScalarResult();

        $menu
            ->addChild('export', [
                'label' => $this->translator->transchoice(
                    'action.export.operationITDLC',
                    $operationsITDLCCount,
                    ['%count%' => $operationsITDLCCount],
                    'action'
                ),
                'route' => 'admin_statistics_itdlc_operation_export',
                'routeParameters' => $this->request->query->all(),
            ])
            ->setLinkAttribute('class', 'btn btn-export')
        ;

        return $menu;
    }

    /**
     * @return ItemInterface
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function demandePEE(): ItemInterface
    {
        $menu = $this->factory->createItem('root');
        $menu->setChildrenAttribute('class', 'menuCatalogue');

        $userName = $this->request->get('user_name');
        $userAcademy = $this->request->get('user_academy');
        $demandeState = $this->request->get('demande_state');
        if ($opeDatemin = $this->request->get('ope_datemin') ) {
            $opeDatemin = \DateTime::createFromFormat('d/m/Y', $opeDatemin);
        }
        if ($opeDatemax = $this->request->get('ope_datemax') ) {
            $opeDatemax = \DateTime::createFromFormat('d/m/Y', $opeDatemax);
        }
        $opeCompany = $this->request->get('ope_company');
        $opeState = $this->request->get('ope_state');

        $qb = $this->em->createQueryBuilder();
        $qb->select('COUNT(d)')
            ->from('AppBundle:DemandePEE', 'd')
            ->leftJoin('d.cuser', 'u')
            ->leftJoin('d.operationpee', 'o');
        if (!empty($userName)) {
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->like(
                    $qb->expr()->upper('u.firstname'),
                    $qb->expr()->upper(':u_firstname')
                ),
                $qb->expr()->like(
                    $qb->expr()->upper('u.lastname'),
                    $qb->expr()->upper(':u_lastname')
                )
            ))
            ->setParameter('u_firstname', "%".$userName."%")
            ->setParameter('u_lastname', "%".$userName."%");
        }
        if (!empty($userAcademy)) {
            $qb
                ->andWhere('u.academy = :u_academy')
                ->setParameter('u_academy', $userAcademy);
        }
        if (!empty($demandeState)) {
            $qb
                ->andWhere('d.state = :d_state')
                ->setParameter('d_state', $demandeState);
        }
        if (!empty($opeDatemin)) {
            $qb
                ->andWhere('o.dateVisite >= :o_datemin')
                ->setParameter('o_datemin', $opeDatemin);
        }
        if (!empty($opeDatemax)) {
            $qb
                ->andWhere('o.dateVisite <= :o_datemax')
                ->setParameter('o_datemax', $opeDatemax);
        }
        if (!empty($opeCompany)) {
            $qb->andWhere($qb->expr()->orX(
                $qb->expr()->like(
                    $qb->expr()->upper('o.company'),
                    $qb->expr()->upper(':o_company')
                ),
                $qb->expr()->like(
                    $qb->expr()->upper('o.site'),
                    $qb->expr()->upper(':o_site')
                )
            ))
            ->setParameter('o_company', "%".$opeCompany."%")
            ->setParameter('o_site', "%".$opeCompany."%");
        }
        if (!empty($opeState)) {
            $qb
                ->andWhere('o.state = :o_state')
                ->setParameter('o_state', $opeState);
        }

        $demandesPEECount = $qb->getQuery()->getSingleScalarResult();

        $menu
            ->addChild('export', [
                'label' => $this->translator->transchoice(
                    'action.export.demandePEE',
                    $demandesPEECount,
                    ['%count%' => $demandesPEECount],
                    'action'
                ),
                'route' => 'admin_statistics_pee_demande_export',
                'routeParameters' => $this->request->query->all(),
            ])
            ->setLinkAttribute('title', 'Les demandes seront groupées par professeur')
            ->setLinkAttribute('class', 'btn btn-export')
        ;

        return $menu;
    }

    /**
     * @return ItemInterface
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function operationPEE(): ItemInterface
    {
        $menu = $this->factory->createItem('root');
        $menu->setChildrenAttribute('class', 'menuCatalogue');

        // Retrieve variables from the query string
        if ($opeDatemin = $this->request->get('ope_datemin') ) {
            $opeDatemin = \DateTime::createFromFormat('d/m/Y', $opeDatemin);
        }
        if ($opeDatemax = $this->request->get('ope_datemax') ) {
            $opeDatemax = \DateTime::createFromFormat('d/m/Y', $opeDatemax);
        }
        $opeCompany = $this->request->get('ope_company');
        $opeAcademy = $this->request->get('ope_academy');
        $opeState = $this->request->get('ope_state');

        $qb = $this->em->createQueryBuilder();
        $qb
            ->select('COUNT(o)')
            ->from('AppBundle:OperationPEE', 'o');
        if ($opeDatemin) {
            $qb
                ->andWhere('o.dateVisite >= :ope_datemin')
                ->setParameter('ope_datemin', $opeDatemin);
        }
        if ($opeDatemax) {
            $qb
                ->andWhere('o.dateVisite <= :ope_datemax')
                ->setParameter('ope_datemax', $opeDatemax);
        }
        if (!empty($opeCompany)) {
            $qb
                ->leftJoin('o.company', 'c')
                ->andWhere(
                    $qb->expr()->orX(
                        $qb->expr()->like(
                            $qb->expr()->upper('c.name'),
                            $qb->expr()->upper(':c_name')
                        ),
                        $qb->expr()->like(
                            $qb->expr()->upper('o.site'),
                            $qb->expr()->upper(':ope_site')
                        )
                    )
                )
            ->setParameter('c_name', "%".$opeCompany."%")
            ->setParameter('ope_site', "%".$opeCompany."%");
        }
        if (!empty($opeState)) {
            $qb
                ->andWhere('o.state = :ope_state')
                ->setParameter('ope_state', $opeState);
        }
        if (!empty($opeAcademy)) {
            $qb
                ->andWhere('o.academy = :ope_academy')
                ->setParameter('ope_academy', $opeAcademy);
        }

        $operationsPEECount = $qb->getQuery()->getSingleScalarResult();

        $menu
            ->addChild('export', [
                'label' => $this->translator->transchoice(
                    'action.export.operationPEE',
                    $operationsPEECount,
                    ['%count%' => $operationsPEECount],
                    'action'
                ),
                'route' => 'admin_statistics_pee_operation_export',
                'routeParameters' => $this->request->query->all(),
            ])
            ->setLinkAttribute('class', 'btn btn-export')
        ;

        return $menu;
    }
}
