<?php

namespace AppBundle\Controller\Module;

use AppBundle\Controller\ModuleController;
use AppBundle\Entity\Module;
use AppBundle\Entity\User;
use AppBundle\Enum\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class LatestUsersController extends ModuleController
{
    /**
     * @param Int $moduleId Défini le module à afficher
     * @param string $force_layout Définit le type de rendu Twig souhaité
     * @param Int $menuId Défini le menu associé, la page actuelle qui demande l'affichage
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function renderModule(Int $moduleId, string $force_layout = null, Int $menuId = null)
    {
        $module = $this->em->getRepository(Module::class)->findOneBy([
            'isActive' => true, 
            'id' => $moduleId
        ]);
        
        if (empty($module)) {
            return new Response('');
        }

        //Force layout
        if (!empty($force_layout)) {
            $module->setLayout($force_layout);
        }
        
        $module->setFormClass($module->getType());
        $layout = $module->getLayoutPath();

        //Check if layout is correct
        if (!empty($force_layout) && strpos($layout, $force_layout) === false) {
            return new Response('');
        }

        $queryuser = $this->em
            ->createQuery(
                "SELECT u FROM AppBundle:User u
                    WHERE u.enabled = :u_enabled AND (u.type = :u_type_prof OR u.type = :u_type_inge)
                    ORDER BY u.created DESC, u.id DESC"
            )
            ->setParameters([
                'u_enabled' => true,
                'u_type_prof' => UserType::TEACHER,
                'u_type_inge' => UserType::ENGINEER,
            ])
            ->setMaxResults(10);
        $latestUsers = $queryuser->getResult();

        if (empty($latestUsers)) {
            return new Response('');
        }

        return $this->render($layout , array(
            'module' => $module, 
            'users' => $latestUsers,
        ));
    }
}
