<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use App\Entity\User;
use App\Form\EmployeeInfoType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class UserProfileController extends AbstractController
{
    /**   
     * @Route("/userprofile/{page<[1-9]\d*>}", defaults={"page"=1}, name="user_profile_index")
     * @IsGranted("ROLE_ADMIN")
     */
    public function index(Request $request, int $page)
    {
        $data = $request->request->get('form');
        if(isset($data['search']))
        {
            $filter = $data['search'];
        }
        else
        {
            $filter = '';
        }

        $user = $this->getDoctrine()
                     ->getRepository(User::class)
                     ->getAllUsers($page, $filter);  
     
        return $this->render('user_profile/index.html.twig', [
            'users' => $user,
        ]);
    }

    /**
     * @Route("/usernew", name="user_profile_new", methods={"GET","POST"})    
     */
    public function new(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $user = new User();
        $form = $this->createForm(EmployeeInfoType::class, $user)
                     ->add('createNew', SubmitType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
             // encode the plain password
             $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    '14547'
                )
            );
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            
            $this->addFlash('notice', 'Employee Created successfully!'); 

            if ($form->get('createNew')->isClicked()) {
                return $this->redirectToRoute('user_profile_new');
            }

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

        return $this->render('user_profile/new.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/user/edit/{id}", name="user_profile_edit", methods={"GET","POST"})
     * @IsGranted("ROLE_ADMIN")
     */
    public function edit(Request $request, User $user, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $form = $this->createForm(EmployeeInfoType::class, $user);
        
       
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // encode the plain password
            $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    '32789',
                )
            );

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            // do anything else you need here, like send an email

            $this->addFlash('notice', 'User updated successfully!');

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

        return $this->render('user_profile/edit.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("user/searchBar", name="user_searchBar")
     * @IsGranted("ROLE_ADMIN")
     */
    public function SearchBar()
    {
        $form = $this->createFormBuilder(null)
                     ->add('search', TextType::class, array(
                         'attr' => [
                             'class' => 'search-input',
                             'placeholder' => 'Search by any value'
                         ],
                         'label'=>false,
                     ))
                     ->getForm();

        return $this->render('user_profile/searchBar.html.twig', [
            'form' => $form->createView()
        ]);
    }

    /**
     * @Route("/user/{id}/delete", name="user_profile_delete", methods={"POST"})
     * @IsGranted("ROLE_ADMIN")
     */
    public function delete(Request $request, User $user): Response
    {
        if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($user);
            $entityManager->flush();

            $this->addFlash('notice', 'User Deleted successfully!');
            
        }

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


}
