<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Availability;
use AppBundle\Entity\OperationITDLC;
use AppBundle\Entity\User;
use AppBundle\Entity\MerITDLC;
use AppBundle\Entity\MerHistoryITDLC;
use AppBundle\Entity\Company;
use AppBundle\Enum\OperationITDLCState;
use AppBundle\Enum\OperationITDLCType;
use AppBundle\Enum\UserType;
use AppBundle\Form\Type\AvailabilityHebdoType;
use AppBundle\Form\Type\AvailabilityPrecisType;
use AppBundle\Form\Type\Front\ITDLC\IngeDemandeITDLCStep1Type;
use AppBundle\Form\Type\Front\ITDLC\IngeDemandeITDLCStep2Type;
use AppBundle\Form\Type\Front\ITDLC\IngeDemandeITDLCStep3Type;
use AppBundle\Form\Type\Front\ITDLC\ProfDemandeITDLCStep1Type;
use AppBundle\Form\Type\Front\ITDLC\ProfDemandeITDLCStep2Type;
use AppBundle\Form\Type\Front\ITDLC\ProfDemandeITDLCStep3Type;
use AppBundle\Form\Type\MerITDLCType;
use AppBundle\Mail\ItdlcMailer;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;


class OperationItdlcController extends Controller
{
    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher;
    
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var ItdlcMailer
     */
    private $itdlcMailer;

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

    /**
     * @var UserManagerInterface
     */
    private $userManager;

    /**
     * @var SessionInterface
     */
    private $session;

    /**
     * @var ValidatorInterface
     */
    private $validator;

    
    public function __construct(
        EventDispatcherInterface $dispatcher, 
        EntityManagerInterface $em, 
        ItdlcMailer $itdlcMailer,
        TranslatorInterface $translator,
        UserManagerInterface $userManager,
        SessionInterface $session,
        ValidatorInterface $validator
    )
    {
        $this->dispatcher = $dispatcher;
        $this->em = $em;
        $this->itdlcMailer = $itdlcMailer;
        $this->translator = $translator;
        $this->userManager = $userManager;
        $this->session = $session;
        $this->validator = $validator;
    }

    /**
     * Ajout d'une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/espace-perso/demande-itdlc-p/add",
     *      name = "espace_perso_prof_itdlc_add"
     * )
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function addProfITDLCAction(Request $request)
    {
        // Récupération des variables $formStep de l'URL
        $formStep = $request->query->getInt('step', 1);
        
        $user = $this->getUser();
        
        // Stock return path in session and redirect to login if user is anonymous
        if (!is_object($user) || !$user instanceof UserInterface) {
            $this->session->set('_return', base64_encode($this->generateUrl($request->get('_route'), $request->get('_route_params'), UrlGeneratorInterface::ABSOLUTE_URL)));

            return $this->redirectToRoute('fos_user_security_login');
        }
        
        if (UserType::TEACHER !== $user->getType()) {
            //throw $this->createAccessDeniedException();

            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return $this->redirectToRoute('espace_perso');
        }

        $ope = new OperationITDLC;

        //Valid Prev step data
       // if ($request->getMethod() == Request::METHOD_GET) {
        if ($formStep < 4) {
            $prevStepValid = $this->validPrevStep($request, $ope);
            if ($prevStepValid !== true) {
                return $prevStepValid;
            }
        }

        // Get Step Form
        $form = $this->getITDLCForm($formStep, $ope);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($formStep == 1 || $formStep == 2) {
                $event = new FormEvent($form, $request);
                $this->dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                $this->userManager->updateUser($user);

                return $this->redirectToRoute('espace_perso_prof_itdlc_add', array(
                    'step'=>++$formStep
                ));
           
                $event = new FormEvent($form, $request);
                $this->dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                $this->userManager->updateUser($user);

                return $this->redirectToRoute('espace_perso_prof_itdlc_add', array(
                    'step'=>++$formStep
                ));
            } elseif ($formStep == 3) {
                // On enregistre le contenu de la demande
                $ope->setType(OperationITDLCType::DEMANDE);
                $ope->setState(OperationITDLCState::NEW);
                $ope->setProf($user);

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

                $this->itdlcMailer->confirmDemande($user);

                $this->addFlash('success', 'Demande enregistrée');

                // redirect to Espace perso !
                // return $this->redirectToRoute('espace_perso_prof_itdlc_edit', array(
                //     'ope'=>$ope->getId()
                // ));
               // return $this->redirectToRoute('espace_perso');

                return $this->redirectToRoute('espace_perso_prof_itdlc_edit', array(
                    'step' => ++$formStep,
                    'ope' => $ope->getId()
                ));
            } elseif ($formStep == 4) {
                $this->itdlcMailer->confirmDemande($user);

                $this->addFlash('success', 'Demande enregistrée');

                // redirect to Espace perso !
                // return $this->redirectToRoute('espace_perso_prof_itdlc_edit', array(
                //     'ope'=>$ope->getId()
                // ));
                return $this->redirectToRoute('espace_perso');
            }
        } elseif ($form->isSubmitted()) {
             // Form submitted but not valid
            $this->addFlash('error', "Votre demande n'a pu être effectuée car certaines informations ont été mal renseignées. Veuillez les vérifier, puis enregistrez à nouveau votre demande.");
        }

        return $this->render('Front/Demande/ITDLC/form.html.twig', array(
            'form' => $form->createView(),
            'type'=> 'ITDLC',
            'mode'=> 'add',
            'step'=> $formStep
        ));
    }

    /**
     * Modification d'une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/espace-perso/demande-itdlc-p/edit/{ope}",
     *      name = "espace_perso_prof_itdlc_edit"
     * )
     * @ParamConverter("ope", class = "AppBundle:OperationITDLC", options = {
     *      "repository_method" = "findAllWithAvailabilities",
     *      "mapping": {"ope": "operationId"},
     *      "map_method_signature" = true
     * })
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editProfITDLCAction(Request $request, OperationITDLC $ope)
    {
        // Récupération des variables $formStep de l'URL
        $formStep = $request->query->getInt('step', 1);
        
        
        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType() || $user->getId() !== $ope->getProf()->getId()) {
            //throw $this->createAccessDeniedException();
            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return $this->redirectToRoute('espace_perso');
        }

        if (OperationITDLCType::OPERATION === $ope->getType() || $ope->getState() == OperationITDLCState::ONGOING) {
            //throw $this->createAccessDeniedException('Vous ne pouvez pas éditer une opération');
            $this->addFlash('error', $this->translator->trans(
                'notice.demandeITDLC.error.operation.cant_edit',
                [],
                'notice'
            ));
            return $this->redirectToRoute('espace_perso');
        }

        $othersUsers = null;
        $nomainjs = null;
        $form = $this->getITDLCForm($formStep, $ope);
        $form->handleRequest($request);

        if ($formStep < 4) {
           
            
            $prevStepValid = $this->validPrevStep($request, $ope);
            if ($prevStepValid !== true) {
                
                return $prevStepValid;
            }
            

            if ($form->isSubmitted() && $form->isValid()) {
                
                if ($formStep == 1 || $formStep == 2) {
                    $event = new FormEvent($form, $request);
                    $this->dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                    $this->userManager->updateUser($user);

                    return $this->redirectToRoute('espace_perso_prof_itdlc_edit', array(
                        'ope' => $ope->getId(),
                        'step' => ++$formStep
                    ));
                } elseif ($formStep == 3) {
                    $this->em->persist($ope);
                    $this->em->flush();

                    return $this->redirectToRoute('espace_perso_prof_itdlc_edit', array(
                        'ope' => $ope->getId(),
                        'step' => ++$formStep
                    ));
                }
            } elseif ($form->isSubmitted()) { // Form submitted but not valid
                $this->addFlash('error', "Votre demande n'a pu être mise à jour car certaines informations ont été mal renseignées. Veuillez les vérifier, puis enregistrez à nouveau votre demande.");
            }
        }
        
            $othersUsers = $this->em->getRepository(User::class)->findClosestWithPartners($user);
            // Convert  $othersUsers into object from raw query result
            $othersUsers = json_decode(json_encode($othersUsers), false);
            
            $nomainjs = true;

            return $this->render('Front/Demande/ITDLC/form.html.twig', array(
                'type' => 'ITDLC',
                'mode' => 'edit',
                'form' => $form->createView(),
                'step'=> $formStep,
                'ope' => $ope,
                'othersUsers' => $othersUsers,
                'nomainjs' => $nomainjs
            ));

        return $this->render('Front/Demande/ITDLC/form.html.twig', array(
            'form' => $form->createView(),
            'type' => 'ITDLC',
            'mode' => 'edit',
            'step'=> $formStep,
            'ope' => $ope,
            'othersUsers' => $othersUsers,
            'nomainjs' => $nomainjs
        ));
    }

    /**
     * Mise en relation d'un intervenant avec une demande d'intervention
     *
     * @Route(
     *      "/espace-perso/demande-itdlc-p/choix-ingenieur/{ope}/{inge}",
     *      name = "espace_perso_prof_itdlc_choix_inge"
     * )
     * @ParamConverter("ope", class = "AppBundle:OperationITDLC", options = {
     *      "repository_method" = "findAllWithAvailabilities",
     *      "mapping": {"ope": "operationId", },
     *      "map_method_signature" = true
     * })
     * @ParamConverter("inge", class = "AppBundle:User", options={"id" = "inge"})
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addMERITDLCAction(Request $request, OperationITDLC $ope, User $inge)
    {

        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType() || $user->getId() !== $ope->getProf()->getId()) {
            //throw $this->createAccessDeniedException();
            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return $this->redirectToRoute('espace_perso');
        }

        if (OperationITDLCType::OPERATION === $ope->getType()) {
            $this->addFlash('error', $this->translator->trans(
                'notice.demandeITDLC.error.operation.cant_edit',
                [],
                'notice'
            ));
            return $this->redirectToRoute('espace_perso');
        }

        $MerITDLC = $ope->getMerITDLC()[0];
        $MerITDLC->setOpe($ope);
        $MerITDLC->setInge($inge);

        $MerHistory = new MerHistoryITDLC();
        $MerHistory->setInfos("Intervention proposée à ".$inge->getFirstname()." ".$inge->getLastname());
        $MerITDLC->addHistory($MerHistory);

        // On passe la demande à en cours
        $ope->setState(OperationITDLCState::ONGOING);
        $ope->setInge($inge);
       
        $this->em->persist($ope);

        // L'ingénieur devient indisponible
        $inge->setIsAvailable(false);

        $this->em->persist($MerITDLC);



        //Envoi email à l'ingénieur
        if ($this->itdlcMailer->sendMerToInge($MerITDLC)) {
            $this->em->flush();

            $this->addFlash('success', "Votre demande d'intervention a été envoyée à l'intervenant.e..<br/>Un délai de 5 jours lui est octroyé pour donner suite à votre mail avant l'envoi d'une relance.<br/>Sans nouvelle de sa part dans un délai de 10 jours ou en cas de réponse négative, nous vous invitons à consulter et contacter un autre profil.");

            
        } else {
            $this->addFlash('error', "Suite à une erreur votre demande n'a pas été envoyé à l'ingénieur");
        }

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

    protected function getErrorMessages(\Symfony\Component\Form\Form $form)
    {
        $errors = array();

        foreach ($form->getErrors() as $key => $error) {
            $errors[] = $error->getMessage();
        }

        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }

        return $errors;
    }


    /**
     * Update informations du profil ingénieur pour répondre aux demandes ITDLC
     *
     * @Route(
     *      "/espace-perso/demande-itdlc-it",
     *      name = "espace_perso_inge_itdlc"
     * )
     *
     * @param Request $request
     * @return null|RedirectResponse|Response
     * @throws \Exception
     */
    public function addIngeITDLCAction(Request $request)
    {
        // Récupération des variables $formStep de l'URL
        $formStep = $request->query->getInt('step', 1);
        
        $user = $this->getUser();

        // Stock return path in session and redirect to login if user is anonymous
        if (!is_object($user) || !$user instanceof UserInterface) {
            $this->session->set('_return', base64_encode($this->generateUrl($request->get('_route'), $request->get('_route_params'), UrlGeneratorInterface::ABSOLUTE_URL)));

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

        if (UserType::ENGINEER !== $user->getType()) {
            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return $this->redirectToRoute('espace_perso');
        }

        $ope = new OperationITDLC;

        $form = $this->getITDLCForm($formStep, $ope);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if($formStep == 1 || $formStep == 2) {
                $event = new FormEvent($form, $request);
                $this->dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                if($formStep == 1)
                {
                    $companyName = $form->get('establishmentNameOther')->getData();

                    $em = $this->getDoctrine()->getManager();
                    $company = $em->getRepository(Company::class)->findOneByName($companyName);

                    if (!$company) {
                        $company = new Company();
                        $company->setName($companyName);
                        $company->setAvailableForUsers(true);

                        $em->persist($company);
                        $em->flush();

                        $user->setEstablishment($company);
                    }
                }
                $this->userManager->updateUser($user);

                return $this->redirectToRoute('espace_perso_inge_itdlc', array(
                    'step'=>++$formStep
                ));
            }
            elseif($formStep == 3) {
                $event = new FormEvent($form, $request);
                $this->dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                $this->userManager->updateUser($user);

                $this->itdlcMailer->confirmDemande($user);

                if (null === $response = $event->getResponse()) {
                    // $subject = 'Venez visiter le site cgenial.org';
                    // $body = str_replace("\n", '%0D%0A', // Required for line break representation in the mailto: URL scheme
                    //     $this->renderView('Front/Mail/invitation.html.twig', array(
                    //         'firstname' => $user->getFirstname(),
                    //         'lastname' => $user->getLastname(),
                    //     ))
                    // );

                    $this->addFlash('info', '<div class="confirm"><span style="font-weight: bold;">Un.e enseignant.e peut désormais prendre contact avec vous pour vous proposer une intervention dans sa classe.</span><br/><br/>
                    Le cas échéant nous reviendrons vers vous dès qu\'une rencontre correspondra à vos critères.</div>');

                    $url = $this->generateUrl('espace_perso');
                    $response = new RedirectResponse($url);
                }

                $this->dispatcher->dispatch(
                    FOSUserEvents::PROFILE_EDIT_COMPLETED,
                    new FilterUserResponseEvent($user, $request, $response)
                );

                return $response;
            }
        } else if ($form->isSubmitted()) { // Form submitted but not valid
            $this->addFlash('error', "Votre demande n'a pu être effectuée car certaines informations ont été mal renseignées. Veuillez les vérifier, puis enregistrez à nouveau votre demande.");
        }

        return $this->render('Front/Demande/ITDLC/form.html.twig', array(
            'form' => $form->createView(),
            'step'=>$formStep,
            'mode'=>'add',
        ));
    }

    /**
     * Historique des mises en relation d'une opération
     *
     * @Route(
     *      "/espace-perso/operations/historiques/{ope}",
     *      name = "modal_merITDLC_histories"
     * )
     * @ParamConverter("ope", class = "AppBundle:OperationITDLC", options={"id" = "ope"})
     * @param Request $request
     * @param OperationITDLC $ope
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function getMERITDLCHistoriesAction(Request $request, OperationITDLC $ope)
    {
        $user = $this->getUser();

        /*
        if (UserType::TEACHER !== $user->getType()) {
            throw $this->createAccessDeniedException();
        }
        */
        return $this->render('Front/Demande/ITDLC/merHistories.html.twig', array(
            'ope' => $ope
        ));
    }


    /**
     * Ajout d'une disponibilité pour une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/espace-perso/availability/add/{ope}/{typedispo}",
     *      requirements = {"typedispo": "precis|hebdo"},
     *      name = "espace_perso_availability_add"
     * )
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @param string $typedispo
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAvailabilityAction(Request $request, OperationITDLC $ope, $typedispo)
    {
        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType()) {
            throw $this->createAccessDeniedException();
        }

        // Formulaire
        $availability = new Availability;
        $form = $this->createForm(
            'precis' == $typedispo ? AvailabilityPrecisType::class : AvailabilityHebdoType::class,
            $availability, [
                'action' => $this->generateUrl('espace_perso_availability_add', [
                    'ope' => $ope->getId(),
                    'typedispo' => $typedispo
                ])
            ]
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $availability->setOperationitdlc($ope);

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

            $this->addFlash('success', 'Disponibilité ajoutée');

            return $this->redirectToRoute('espace_perso_prof_itdlc_edit', [
                'ope' => $ope->getId(),
                'step' => 3,
            ]);
        }

        return $this->render('Front/Demande/ITDLC/availability.html.twig', array(
            'availability' => $availability,
            'form' => $form->createView(),
            'typedispo' => $typedispo,
        ));
    }

    /**
     * Modification d'une disponibilité d'une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/espace-perso/availability/edit/{availability}",
     *      name = "espace_perso_availability_edit"
     * )
     *
     * @param Request $request
     * @param Availability $availability
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAvailabilityAction(Request $request, Availability $availability)
    {
        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType()) {
            throw $this->createAccessDeniedException();
        }

        $form = $this->createForm(
            $availability->getDateVisite() ? AvailabilityPrecisType::class : AvailabilityHebdoType::class,
            $availability
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($availability);
            $this->em->flush();

            $this->addFlash('success', 'Disponibilité modifiée');

            return $this->redirectToRoute('espace_perso_availability_edit', array(
                'availability' => $availability->getId(),
            ));
        }

        return $this->render('Front/Demande/ITDLC/availability.html.twig', array(
            'availability' => $availability,
            'form' => $form->createView(),
        ));
    }


    /**
     * Get ITDLC step Form
     *
     * @param int $formStep
     * @param OperationITDLC $ope
     * @return ProfDemandeITDLCStep1Type|ProfDemandeITDLCStep2Type|ProfDemandeITDLCStep3Type|IngeDemandeITDLCStep1Type|IngeDemandeITDLCStep2Type|IngeDemandeITDLCStep3Type
     */
    private function getITDLCForm(int $formStep, OperationITDLC $ope = null) {
        $user = $this->getUser();
        
        if (UserType::TEACHER === $user->getType()) {
            // Get Step Form
            switch($formStep) {
                case 2 :
                    $form = $this->createForm(ProfDemandeITDLCStep2Type::class, $user);
                    break;
                case 3 :
                    $form = $this->createForm(ProfDemandeITDLCStep3Type::class, $ope);
                    break;

                default:
                case 1 :
                        $form = $this->createForm(ProfDemandeITDLCStep1Type::class, $user);
                        break;

            }
        }
        else {
            // Get Step Form
            switch($formStep) {
                case 2 :
                        $form = $this->createForm(IngeDemandeITDLCStep2Type::class, $user);
                        break;
                case 3 :
                        $form = $this->createForm(IngeDemandeITDLCStep3Type::class, $user);
                        break;
                default:
                case 1 :
                        $form = $this->createForm(IngeDemandeITDLCStep1Type::class, $user);
                        break;

            }
        }

        return $form;
    }


    /**
     * Valid prev data
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @return true|RedirectResponse;
     */
    private function validPrevStep(Request $request, OperationITDLC $ope = null) {
        
        // Récupération des variables $formStep de l'URL
        $formStep = $request->query->getInt('step', 1);

        while ($formStep > 1) {
            $formStep--;

            $prevForm = $this->getITDLCForm($formStep, $ope);
            //$fields = $prevForm->all();

            $options = $prevForm->getConfig()->getOptions();
            
            $prevStepValid = $this->validator->validate($prevForm->getData(), null, $options['validation_groups']);
            
            if (count($prevStepValid) > 0) {
                if ($formStep > 1) {
                    return $this->redirectToRoute($request->get('_route'), array(
                        'step'=>$formStep
                    ));
                }
                else {
                    return $this->redirectToRoute($request->get('_route'));    
                }
                
            } 
        }

        return true;
    }


    /**
     * Modal : Confirmer annulation Demande
     *
     * @Route(
     *      "/espace-perso/modal-cancel-demande-itdlc/{demande}",
     *      name = "modal_cancel_demande_itdlc"
     * )
     *
     * @param Request $request
     * @param OperationITDLC $demande
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function modalCancelDemandeITDLCAction(Request $request, OperationITDLC $demande)
    {
        // Check rights here
        $user = $this->getUser();
        
        if ($user === null || ($user->getId() !== $demande->getProf()->getId() && $user->getId() !== $demande->getInge()->getId())) {
            throw $this->createAccessDeniedException();
        }
        
        return $this->render('Front/Render/Modal/ITDLC/cancel.demande.html.twig', array(
            'demande' => $demande
        ));
    }

    /**
     * Annulation Demande
     *
     * @Route(
     *      "/espace-perso/cancel-demande-itdlc/{demande}",
     *      name = "cancel_demande_itdlc"
     * )
     *
     * @param Request $request
     * @param OperationITDLC $demande
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function cancelDemandeITDLCAction(Request $request, OperationITDLC $demande)
    {
        

        // Check rights here
        $user = $this->getUser();
        
        if($user === null || ($user->getId() !== $demande->getProf()->getId() && $user->getId() !== $demande->getInge()->getId())) {
            throw $this->createAccessDeniedException();
        }
        $demande->setState(OperationITDLCState::CANCELLED);
        
        $this->em->persist($demande);
        $this->em->flush();

        return new JsonResponse(array('result' => true));
    }

    /**
     * Modal : Confirmer annulation Opération
     *
     * @Route(
     *      "/espace-perso/modal-cancel-operation-itdlc/{ope}",
     *      name = "modal_cancel_operation_itdlc"
     * )
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */

    public function modalCancelOperationITDLCAction(Request $request, OperationITDLC $ope)
    {
        // Check rights here
        $user = $this->getUser();
        
        if ($user === null || ($user->getId() !== $ope->getProf()->getId() && $user->getId() !== $ope->getInge()->getId())) {
            throw $this->createAccessDeniedException();
        }
        
        return $this->render('Front/Render/Modal/ITDLC/cancel.operation.html.twig', array(
            'ope' => $ope
        ));
    }

    /**
     * Annulation Opération
     *
     * @Route(
     *      "/espace-perso/cancel-operation-itdlc/{ope}",
     *      name = "cancel_operation_itdlc"
     * )
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function cancelOperationITDLCAction(Request $request, OperationITDLC $ope)
    {
        $type = $request->query->get('type');

        // Check rights here
        $user = $this->getUser();
        
        if ($user === null || ($user->getId() !== $ope->getProf()->getId() && $user->getId() !== $ope->getInge()->getId())) {
            throw $this->createAccessDeniedException();
        }

        // Formulaire
        $MerITDLC = $this->em->getRepository(MerITDLC::class)->findOneByOpe($ope);
        
        $MerHistory = new MerHistoryITDLC();
        if ($type == UserType::TEACHER) {
            $MerHistory->setInfos("Rencontre de " . $ope->getInge()->getFullname() . " annulée par le professeur " .  $ope->getProf()->getFullname());
            $ope->setState(OperationITDLCState::CANCELLED);
        } elseif ($type == UserType::ENGINEER) {
            $MerHistory->setInfos("Rencontre de " . $ope->getInge()->getFullname() . " annulée par lui même");
            // Anomalie #454
            $ope->setState(OperationITDLCState::CANCELLED);
            //$ope->setState(OperationITDLCState::NEW);
            //$ope->setType(OperationITDLCType::DEMANDE);
            
        }

        $MerITDLC->addHistory($MerHistory);
        
        $this->em->persist($MerITDLC);

        $ope->getInge()->setIsAvailable(true);

        // Anomalie #454
        //$ope->setInge(null);

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

        //Send Email to Admin
        $this->itdlcMailer->cancelOperation($ope, $user, $type);

        return new JsonResponse(array('result' => true));
    }
}