<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Enum\OperationITDLCType;
use AppBundle\Enum\OperationPEEState;
use AppBundle\Enum\UserType;
use AppBundle\History\ScreenHistory;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

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

    /**
     * @var ScreenHistory
     */
    private $screenHistory;

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

    /**
     * Page d'accueil du Back office
     *
     * @Route(
     *      "/",
     *      name="admin_homepage"
     * )
     */
    public function indexAction()
    {
        $resultsMaxPerPage = $this->getParameter('results.admin.max_per_page');

        // Sélection de tous les utilisateurs "normaux": ceux créé via l'interface d'inscription du site. Les autres sont des utilisateurs administrateurs.
        $queryusers = $this->em
            ->createQuery(
                "SELECT u FROM AppBundle:User u
                    WHERE u.is_active = :active
                        AND u.firstname IS NOT NULL
                        AND u.lastname IS NOT NULL
                        AND SUBSTRING(u.username, 1, 5) != 'admin'
                    ORDER BY
                    u.created DESC,
                    u.id DESC"
            )
            ->setParameter('active', true)
            ->setMaxResults($resultsMaxPerPage);
        $lastUsers = $queryusers->getResult();

        $usersDemandesNb = array(); // Création d'un tableau contenant, pour chaque ID d'utilisateur, le nombre de demandes PEE et ITDLC effectuées (pour les opération ouvertes seulement)
        foreach ($lastUsers as $user) {
            $userId = $user->getId();

            if (UserType::TEACHER === $user->getType()) {
                $reqDemandesItdlcNb = $this->em
                    ->createQuery(
                        "SELECT o FROM AppBundle:OperationITDLC o
                            LEFT JOIN o.prof u
                            WHERE u.id = :user_id
                                AND o.type = :o_type"
                    )
                    ->setParameters(array(
                        'user_id' => $userId,
                        'o_type' => OperationITDLCType::DEMANDE,
                    ));
                $demandes_itdlc_nb = $reqDemandesItdlcNb->getResult();
                $usersDemandesNb[$userId]['itdlc'] = count($demandes_itdlc_nb);

                $reqDemandesPeeNb = $this->em
                    ->createQuery(
                        "SELECT d FROM AppBundle:DemandePEE d
                            LEFT JOIN d.operationpee o
                            LEFT JOIN d.cuser u
                            WHERE u.id = :user_id
                                AND o.state = :o_state"
                    )
                    ->setParameters(array(
                        'user_id' => $user->getId(),
                        'o_state' => OperationPEEState::OPEN,
                    ));
                $demandesPeeNb = $reqDemandesPeeNb->getResult();
                $usersDemandesNb[$userId]['pee'] = count($demandesPeeNb);
            } else { // Ingénieur
                if ($user->getNbContribution() > 0) {
                    $usersDemandesNb[$userId]['itdlc'] = 1;
                } else {
                    $usersDemandesNb[$userId]['itdlc'] = 0;
                }

                $usersDemandesNb[$userId]['pee'] = 0;
            }
        }

        return $this->render('Admin/Default/index.html.twig', array(
            'users' => $lastUsers,
            'users_demandes_nb' => $usersDemandesNb,
        ));
    }


    /**
     * @Route(
     *      "/search/{route}",
     *      name = "admin_search"
     * )
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function searchAction(Request $request)
    {
        return $this->redirectToRoute($request->get('route'), $request->query->all());
    }

    /**
     * @Route(
     *      "/step-back",
     *      name = "step_back"
     * )
     */
    public function stepBackAction()
    {
        $request = $this->screenHistory->pop();

        return $this->redirect($request->getUri());
    }
}
