<?php
/**
 * Created by PhpStorm.
 * User: hicham benkachoud
 * Date: 06/01/2020
 * Time: 20:39
 */

namespace App\Controller;


use App\Entity\User;
use App\Entity\Participant;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class AuthController extends ApiController
{

    public function register(Request $request, UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->transformJsonBody($request);
        $password = $request->get('password');
        $email = $request->get('email');
        $fullName= $request->get('fullName');
        $address= $request->get('address');
        $country= $request->get('country');
        $birthDate= $request->get('birthDate');
        $phonenumber = $request->get('phonenumber');

        if (empty($fullName) || empty($password) || empty($email) || empty($address) || empty($country) || empty($birthDate)){
            return $this->respondValidationError("Invalid Username or Password or Email");
        }
        $user = new User();
        $user->setPassword($encoder->encodePassword($user, $password));
        $user->setEmail($email);
        $user->setFullAdress($address);
        $user->setPhoneNumber($phonenumber);
        $user->setUsername($email);
        $user->setRoles(json_encode(['ROLE_PARTICIPANT']));
        $em->persist($user);

        $em->flush();
        $participant= new Participant();
        $participant->setFullName($fullName);
        $participant->setCountry($country);
        $participant->setBirthDate((\DateTime::createFromFormat('d/m/Y',$birthDate)));
        $participant->setUser($user);
        $em->persist($participant);
        $em->flush();

        return $this->respondWithSuccess(sprintf('User %s successfully created', $user->getUsername()));
    }
    public function tokenPassword(Request $request, \Swift_Mailer $mailer)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->transformJsonBody($request);
        $email = $request->get('email');
        $user= $this->getDoctrine()
            ->getRepository(User::class)
            ->findOneBy(['email' =>$email]);
        if(!empty($user)){
            $random = sha1(random_bytes(120));
            $user->setTokenPassword($random);
            $em->persist($user);
            $em->flush();
            $message = (new \Swift_Message('Reset password'))
                ->setFrom(["contact@drooob.net"=>'Drooob'])
                ->setTo($user->getEmail())
                ->setBody(
                    $this->renderView(
                    // templates/emails/registration.html.twig
                        'email/token.html.twig',
                        ['token' => $random]
                    )

                    ,"text/html")
            ;
            // Send the message
            $mailer->send($message);
        return $this->respondWithSuccess(sprintf('User %s token created', $user->getUsername()));
        }
        return $this->respondValidationError("Invalid email");

    }
    public function resetpassword(Request $request , UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->transformJsonBody($request);
        $password = $request->get('password');

        $token= $request->get('token');
        $user= $this->getDoctrine()
            ->getRepository(User::class)
            ->findOneBy(['tokenPassword' =>$token]);
        if(!empty($user)){
                if ( empty($password)){
                    return $this->respondValidationError("Invalid Username or Password or Email");
                }

                $user->setPassword($encoder->encodePassword($user, $password));
                $user->setTokenPassword(null);
                $em->persist($user);
                $em->flush();
                return $this->respondWithSuccess(sprintf('User %s successfully update password', $user->getUsername()));
        }
        return $this->respondValidationError("Invalid token");

    }
    public function updatepassword(Request $request , UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->transformJsonBody($request);
        $password = $request->get('password');
        $newpassword= $request->get('newpassword');
        $user=$this->getUser();
        $match = $encoder->isPasswordValid($user,$password);
        if($match)
        {

            $user->setPassword($encoder->encodePassword($user, $newpassword));
                $em->persist($user);
                $em->flush();
                return $this->respondWithSuccess(sprintf('User %s successfully update password', $user->getUsername()));
        }
        return $this->respondValidationError("Invalid token");

    }
    public function veriftoken(Request $request , UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->transformJsonBody($request);

        $token= $request->get('token');
        $user= $this->getDoctrine()
            ->getRepository(User::class)
            ->findOneBy(['tokenPassword' =>$token]);
        if(!empty($user)){
                return $this->respondWithSuccess(sprintf('valid token', $user->getUsername()));
        }
        return $this->respondValidationError("Invalid token");

    }

    public function updateuser(Request $request, UserPasswordEncoderInterface $encoder)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->transformJsonBody($request);
        $address= $request->get('address');
        $country= $request->get('country');
        $fullName= $request->get('fullName');
        $phonenumber = $request->get('phonenumber');
        $birthDate= $request->get('birthDate');

        if (empty($fullName) || empty($address) || empty($country) || empty($phonenumber)){
            return $this->respondValidationError("Invalid Username or Password or Email");
        }
        $user=$this->getUser();
        $user->setFullAdress($address);
        $user->setPhoneNumber($phonenumber);
        $em->persist($user);
        $em->flush();

        $partipant= $this->getDoctrine()
            ->getRepository(Participant::class)
            ->findOneBy(['user' =>$user]);
        $partipant->setFullName($fullName);
        $partipant->setCountry($country);
        $partipant->setBirthDate((\DateTime::createFromFormat('d/m/Y',$birthDate)));
        $em->persist($partipant);
        $em->flush();
        return $this->respondWithSuccess(sprintf('User %s successfully updated', $user->getUsername()));
    }

    /**
     * @param UserInterface $user
     * @param JWTTokenManagerInterface $JWTManager
     * @return JsonResponse
     */

    public function participantLogin(Request $request, UserPasswordEncoderInterface $encoder, JWTTokenManagerInterface $JWTManager)
    {
        $request = $this->transformJsonBody($request);
        $password = $request->get('password');
        $email = $request->get('email');
        $user= $this->getDoctrine()
            ->getRepository(User::class)
            ->findOneBy(['email' =>$email]);
        if(!empty($user)){

        $match = $encoder->isPasswordValid($user,$password);
        if($match)
            return new JsonResponse(['token' => $JWTManager->create($user)]);
        else
            return $this->respondValidationError("Invalid email or password");
        }
        return $this->respondValidationError("Invalid email or password");

    }


}
