<?php
/**
 * Created by PhpStorm.
 * User: remy.bages
 * Date: 17/05/2018
 * Time: 11:22
 */

namespace AppBundle\Controller;


use AppBundle\Entity\Historique;
use AppBundle\Entity\Utilisateur;
use AppBundle\Form\AddNewAgent;
use AppBundle\Form\UpdateAgent;
use AppBundle\Form\User\AgentPasswordUpdate;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

/**
 * Class UtilisateurAdminController
 * @package AppBundle\Controller
 * @Route("/panel")
 */
class UtilisateurAdminController extends Controller
{
    /**
     *
     * @Route("/user", name="users_list")
     * @Template("@App/Admin/listeUtilisateurs.html.twig")
     * @Security("is_granted('ROLE_ALLOWED_TO_SWITCH')")
     */
    public function listUsersAction(Request $request)
    {

        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();
        $entete = $em->getRepository('AppBundle:Entete')->findOneBy(['localisation'=>'GestionUtilisateur']);

        $users = $em->getRepository('AppBundle:Utilisateur')->findAll();

        //$interlocuteurs = $em->getRepository('AppBundle:Interlocuteur')->findAll();
        $interlocteurSelected= null;

        if (isset($_POST['siret']) and $_POST['siret']!='' )
        {
                $interlocteurSelected = $em->getRepository('AppBundle:Interlocuteur')->findOneBy(['siret'=>$_POST['siret']]);

                if (!$interlocteurSelected == null)
                    $users = $interlocteurSelected->getUtilisateur();


        }

        return [
            'user' => $user,
            'users' => $users,
            'entete'=>$entete,
            'interlocuteurSelected' => $interlocteurSelected,
        ];

    }

    /**
     * @Route("/agent", name="agents_list")
     * @Template("@App/Admin/listeAgents.html.twig")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function listAgentsAction(Request $request)
    {
        $user = $this->getUser();
        $doc = $this->getDoctrine();
        $em = $doc->getManager();

        $agents = $em->getRepository('AppBundle:Utilisateur')->findBy(['isAgent' => 1]);

        return [
            'user' => $user,
            'agents' => $agents
        ];
    }

    /**
     * @Route("/agent/passwordReset", name="agent_password_reset")
     * @Template("@App/Admin/agentResetPassword.html.twig")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_AGENT')")
     */
    public function agentResetPasswordAction(Request $request, UserPasswordEncoderInterface $encoder )
    {

        $form = $this->createForm(AgentPasswordUpdate::class);
        $form->handleRequest($request);
        $em = $this->getDoctrine()->getManager();

        /** @var Utilisateur $user */
        $user = $this->getUser();
        $user = $this->getDoctrine()->getRepository('AppBundle:Utilisateur')->find($user->getId());

        $errors = [];
        $status = 200;


        if($form->isValid()) {

            $data = $form->getData();

            $uppercase = preg_match('@[A-Z]@', $data['new']);
            $lowercase = preg_match('@[a-z]@', $data['new']);
            $number    = preg_match('@[0-9]@', $data['new']);

            $encoded = $encoder->encodePassword($user, $data['current']);

            if($encoded != $user->getPassword()) {
              $status = 500;
              $errors[] = $this->get('translator')->trans("ERROR_PASSWORD_DONT_MATCH");
            }

            if(!$uppercase || !$lowercase || !$number || strlen($data['new']) < 8) {
              $status = 500;
              $errors[] = $this->get('translator')->trans("ERROR_NEW_PASSWORD_STRENGTH");
            }

            if($data['new'] != $data['confirmation']) {
              $status = 500;
              $errors[] = $this->get('translator')->trans("ERROR_PASSWORD_CONFIRMATION_FAIL");
            }

            if($status == 200) {
              $newPassword = $encoder->encodePassword($user, $data['new']);
              $user->setMdp($newPassword);

              $histo = new Historique('Modification', 'Utilisateur', $this->getUser()->getUsername().' a modifié son mot de passe', $user);

              $em->persist($histo);
              $em->persist($user);
              $em->flush();

                $this->get('aeap.mailer')->sendMail('AEAP : Mot de passe modifié',$user->getEmail(),'@App/Email/mdpChange.html.twig', [
                    'date' => new \DateTime('now')
                ]);


                $this->get('session')->getFlashBag()
                  ->add('success', $this->get('translator')->trans('PASSWORD_SAVED'));


              $this->get('aeap.mailer')->sendMail('AEAP : Mot de passe modifié', $user->getEmail(), '@App/Email/mdpChange.html.twig', [
                  'date' => new \DateTime()
              ]);

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

        return [
            'form' => $form->createView(),
            'errors' => $errors
        ];

    }

    /**
     * @param Request $request
     * @param $userId
     * @Route("/api/user/{userId}/activate", name="user_activate")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function activateUserAction(Request $request, $userId)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:Utilisateur')->find($userId);
        $histo = new Historique('Activation', 'Utilisateur', $this->getUser()->getUsername()." a activé ".$user->getUsername(), $this->getUser());

        $user->setIsActif(1);
        $em->persist($user);
        $em->persist($histo);
        try {
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('USER_ACTIVATE'));
        } catch (Exception $e) {
            $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_500_HELP'));
        }

        return $this->redirect($request->headers->get('referer'));
    }

    /**
     * @Route("/agent/new", name="new_agent")
     * @Template("@App/Admin/createAgent.html.twig")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function newAgentAction(Request $request, UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $status = 200;
        $errors = [];

        $form = $this->createForm(AddNewAgent::class);
        $form->handleRequest($request);


        if($form->isValid()) {

            /** @var Utilisateur $data */
            $data = $form->getData();
            $agent = new Utilisateur($data);
            $agent->setIsAgent(1);

            //il faut faire ça manuellement car le constructeur d'utilisateur set isAdmin à 0 et isActif à 1 par défaut.
            $agent->setIsActif($data['isActif']);
            $agent->setIsAdmin($data['isAdmin']);

            $unique = $this->getDoctrine()->getRepository(Utilisateur::class)->findOneBy(['email'=>$data['email']]);

            $password = $encoder->encodePassword($agent, $data['password']);
            $agent->setMdp($password);
            $agent->setHasValidated(1);


            $uppercase = preg_match('@[A-Z]@', $data['password']);
            $lowercase = preg_match('@[a-z]@', $data['password']);
            $number    = preg_match('@[0-9]@', $data['password']);


            if(empty($data['nom']) or empty($data['prenom'])) {
                $status = 500;
                $errors[] = $this->get('translator')->trans('ERROR_NAME_FIRSTNAME_FILLED');
            }

            if(!empty($unique)) {
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_EMAIL_EXISTS");
            }

            if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL)){
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_EMAIL_VALIDATION");
            }

            if($data['password'] != $data['confirmation']) {
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_PASSWORD_CONFIRMATION_FAIL");
            }

            if(!$uppercase || !$lowercase || !$number || strlen($data['password']) < 8) {
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_NEW_PASSWORD_STRENGTH");
            }

            if (strlen($data['telephone'])!=10 or !is_numeric($data['telephone']))
            {
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_TELEPHONE_FORMAT");
            }


            if ($status==200)
            {
                $histo = new Historique('Creation', 'Utilisateur', $this->getUser()->getUsername().'a créé un nouvel agent', $this->getUser());

                $em->persist($histo);
                $em->persist($agent);
                $em->flush();

                $this->get('session')->getFlashBag()
                    ->add('success', 'Le nouvel agent a bien été crée.');
                return $this->redirectToRoute('panel');
            }

        }

        return [
            'form' => $form->createView(),
            'errors' => $errors
        ];

    }

    /**
     * @Route("/agent/{agentID}/update", name="update_agent")
     * @Template("@App/Admin/updateAgent.html.twig")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function updateAgentAction(Request $request, $agentID)
    {
        $em = $this->getDoctrine()->getManager();
        $agent = $em ->getRepository('AppBundle:Utilisateur')->findOneBy(['id'=>$agentID]);
        $agences = $em->getRepository('AppBundle:Agence')->findAll();
        $agencesFinal = [];
        $errors=[];


        $formData['agent'] = $agent;
        $form = $this->createForm(UpdateAgent::class, $agent, ['data' => $formData]);

        //if the previous phone number is wrong, you need to reset it manually otherwise the form->isValid() will be false
        $form->getData()['agent']->setTelephone('0000000000');

        $form->handleRequest($request);


        if ($form->isValid())
        {
            /** @var Utilisateur $data */
            $data = $form->getData();
            $status = 200;

            $unique = $this->getDoctrine()->getRepository(Utilisateur::class)->findOneBy(['email'=>$data['email']]);

            if($data['telephone'])


            if(empty($data['nom']) or empty($data['prenom'])) {
                $status = 500;
                $errors[] = $this->get('translator')->trans('ERROR_NAME_FIRSTNAME_FILLED');
            }
            if(!(empty($unique)) and !($unique->getEmail() == $agent->getEmail())) {
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_EMAIL_EXISTS");
            }

            if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL)){
                $status = 500;
                $errors[] = $this->get('translator')->trans("ERROR_EMAIL_VALIDATION");
            }

            if(strlen($data['telephone'])!=10 or !is_numeric($data['telephone']))
            {
                $status=500;
                $errors[]=$this->get('translator')->trans("ERROR_TELEPHONE_FORMAT");
            }

            $agent->setNom($data['nom']);
            $agent->setPrenom($data['prenom']);
            $agent->setEmail($data['email']);
            $agent->setTelephone($data['telephone']);

            if ($status == 200)
            {
                $this->get('session')->getFlashBag()
                    ->add('success', "L'agent a bien été modifié.");

                $histo = new Historique('Modification', 'Utilisateur', $this->getUser()->getUsername()." a modifié l'agent ". $agent->getUsername(), $this->getUser());

                $em->persist($histo);
                $em->persist($agent);
                $em->flush();

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

        }

        return [
            'form' => $form->createView(),
            'errors' => $errors,
            'agent' => $agent
        ];

    }

    /**
     * @param Request $request
     * @param Utilisateur $user
     * @param UserPasswordEncoderInterface $encoder
     * @return array
     * @Route("/user/{user}/update", name="user_admin_update")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     * @Template("@App/UtilisateurAdmin/updateUser.html.twig")
     */
    public function updateUserAction(Request $request, Utilisateur $user, UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $userForm = $this->createForm('AppBundle\Form\User\UpdateUserAdminType', $user);
        $pwForm = $this->createForm('AppBundle\Form\Security\UserPasswordReset');
        $userForm->handleRequest($request);
        $pwForm->handleRequest($request);

        if ($userForm->isValid()) {

            if($user == $this->getUser()) {
                if ($user->isIsAdmin() == false) {
                    $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_SELF_DEMOTE'));
                    $user->setIsAdmin(true);
                }
                if ($user->getDateFinBan()) {
                    $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_SELF_BAN'));
                    $user->setDateFinBan(null);
                }
            } else {
                $histo = new Historique('Modification', 'Utilisateur', $this->getUser()->getUsername().' a modifié les informations de '. $user->getUsername(), $this->getUser());

                $em->persist($histo);
                $em->persist($user);
                $em->flush();
                $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('USER_UPDATED'));
            }
        }

        if ($pwForm->isValid()) {
            $data = $pwForm->getData();
            $user->setMdp($encoder->encodePassword($user, $data['password']));
            $histo = new Historique('Modification', 'Utilisateur', $this->getUser()->getUsername().' a modifié le mot de passe de '. $user->getUsername(), $this->getUser());

            $em->persist($histo);
            $em->persist($user);
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('PASSWORD_SAVED'));
        }

        return [
            'userForm' => $userForm->createView(),
            'pwForm' => $pwForm->createView()
        ];
    }

    /**
     * @param Request $request
     * @param $userId
     * @Route("/api/user/{userId}/deactivate", name="user_deactivate")
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deactivateUserAction(Request $request, $userId)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:Utilisateur')->find($userId);
        $histo = new Historique('Désactivation', 'Utilisateur', $this->getUser()->getUsername()." a désactivé ".$user->getUsername(), $this->getUser());

        $user->setIsActif(0);
        $em->persist($user);
        $em->persist($histo);
        try {
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('USER_DEACTIVATE'));
        } catch (Exception $e) {
            $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_500_HELP'));
        }

        return $this->redirect($request->headers->get('referer'));
    }

    /**
     * @param Request $request
     * @param $userId
     * @Route("/api/user/{userId}/promoteAdmin", name="user_promoteAdmin")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function promoteAdminAction(Request $request, $userId)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:Utilisateur')->find($userId);
        $histo = new Historique('Modification', 'Utilisateur', $this->getUser()->getUsername()." a promu admin ".$user->getUsername(), $this->getUser());

        $user->setIsAdmin(1);
        $em->persist($user);
        $em->persist($histo);
        try {
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('USER_PROMOTED'));
        } catch (Exception $e) {
            $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_500_HELP'));
        }

        return $this->redirect($request->headers->get('referer'));
    }

    /**
     * @param Request $request
     * @param $userId
     * @Route("/api/user/{userId}/demoteAdmin", name="user_demoteAdmin")
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @Security("!is_granted('ROLE_PREVIOUS_ADMIN')")
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function demoteAdminAction(Request $request, $userId)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('AppBundle:Utilisateur')->find($userId);
        $histo = new Historique('Modification', 'Utilisateur', $this->getUser()->getUsername()." a retiré le droits admin à ".$user->getUsername(), $this->getUser());
        $user->setIsAdmin(0);
        $em->persist($user);
        $em->persist($histo);
        try {
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('USER_DEMOTED'));
        } catch (Exception $e) {
            $this->get('session')->getFlashBag()->add('error', $this->get('translator')->trans('ERROR_500_HELP'));
        }

        return $this->redirect($request->headers->get('referer'));
    }




}