<?php
namespace App\Controller;
use App\Entity\Client;
use App\Entity\ClientNotification;
use App\Entity\ClientSettings;
use App\Entity\Invitation;
use App\Entity\NotificationType;
use App\Form\Type\ClientType;
use App\Repository\ClientMessageRepository;
use App\Repository\ClientNotificationRepository;
use App\Repository\ClientRepository;
//use App\Service\MailService;
use App\Repository\CountryRepository;
use App\Repository\InvitationRepository;
use App\Service\MailService;
use DateTime;
use \Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Vich\UploaderBundle\VichUploaderBundle;
class ClientController extends AbstractController
{
private ClientRepository $clientRepository;
private ClientActivationTokenController $clientActivationTokenController;
private MailService $mailService;
private InvitationRepository $invitationRepository;
private UserPasswordHasherInterface $encoder;
private CountryRepository $countryRepository;
private ClientNotificationRepository $clientNotificationRepository;
public function __construct(
ClientRepository $clientRepository,
MailService $mailService,
UserPasswordHasherInterface $encoder,
InvitationRepository $invitationRepository,
ClientActivationTokenController $clientActivationTokenController,
CountryRepository $countryRepository,
ClientNotificationRepository $clientNotificationRepository
)
{
$this->clientRepository = $clientRepository;
$this->mailService = $mailService;
$this->encoder = $encoder;
$this->invitationRepository=$invitationRepository;
$this->clientActivationTokenController=$clientActivationTokenController;
$this->countryRepository=$countryRepository;
$this->clientNotificationRepository=$clientNotificationRepository;
}
#[Route("/register-new-client", name: "register_new_client", methods: ["POST"])]
public function registerClient(Request $request): JsonResponse
{
$data = $request->request->all();
$username = $data['username'];
$email = $data['email'];
$password = $data['password'];
if (empty($email) || empty($password)) {
throw new NotFoundHttpException('Expecting mandatory parameters!');
}
$clientExists = false;
$checkClient = $this->clientRepository->findOneByEmail($email);
if(!empty($checkClient)){
$clientExists = true;
}
if(!$clientExists){
$newUser = new Client();
$encoded = $this->encoder->hashPassword($newUser,$password);
$newUser
->setEmail($email)
->setUsername($username)
->setPassword($encoded)
->setName("Unknown")
->setSurname("Unknown")
->setActivatedAt(new \DateTime("0/0/0000 00:00:00"))
->setRoles((['ROLE_CLIENT']))
->setIsDeleted(false)
->setEnabled(true)
->setDateCreated(new \DateTime('now'));
$newClient = $this->clientRepository->save($newUser,true);
$notification = new ClientNotification();
$notification
->setCreatedAt(new \DateTime('now'))
->setTitle('Welcome notification')
->setNotificationText('Welcome to Rap Battle Online '.$newClient->getName())
->setType(NotificationType::INTERACTION_TYPE_MESSAGE)
->setClient($newClient)
->setNotificationRead(false);
$this->clientNotificationRepository->save($notification,true);
$settings = $this->getDefaultClientSettings($newClient);
$newClient->setClientSettings($settings);
$this->clientRepository->save($newUser,true);
$token = $this->clientActivationTokenController->createActivationTokenForClientAction($newClient->getId());
$this->mailService->sendWelcomeMessage($email,$newUser->getUsername(),$token->getToken());
$this->mailService->notifyAgents($newUser->getUsername());
$data = [
'id' => $newClient->getId(),
'email' => $newClient->getEmail()
];
return new JsonResponse($data, Response::HTTP_CREATED);
}else{
return new JsonResponse(["message" => "Email je je vyuzivan"], Response::HTTP_BAD_REQUEST);
}
}
#[Route("/reset-password-process/", name: "reset_password", methods: ["POST"])]
public function resetPassword(Request $request): JsonResponse
{
$data = $request->request->all();
$email = $data['email'];
$client = $this->clientRepository->findOneBy(['email'=>$email]);
if($client != null){
$clientName = $client->getName().' '.$client->getSurname();
$newGeneratedPasswordHash = $this->generateRandomString(12);
$validToDate = new \DateTime('tomorrow');
$client->setResetPasswordHash($newGeneratedPasswordHash);
$client->setResetPasswordHashValidTo($validToDate);
$this->clientRepository->save($client,true);
$this->mailService->sendResetPassword($email,$newGeneratedPasswordHash);
return new JsonResponse(["message" => "Email vyresetovan!", "clientName"=>$clientName, "resetPasswordLink"=>$newGeneratedPasswordHash], Response::HTTP_OK);
}else{
return new JsonResponse(["message" => "Uzivatel nenalezen"], Response::HTTP_NOT_FOUND);
}
}
#[Route("/reseting-password/{hash}", name: "reseting_password_page", methods: ["GET"])]
public function resetingPasswordPage($hash): Response
{
$client = $this->clientRepository->findOneBy(['resetPasswordHash'=>$hash]);
if($client!=null)
{
$validTo = $client->getResetPasswordHashValidTo();
$today = new DateTime('now');
if($today>$validTo){
return $this->render('pages/auth/reseting-password.html.twig', ["clientHash"=>$hash]);
}else{
return $this->render('pages/auth/reseting-password-not-valid.html.twig', []);
}
}
else
{
return $this->render('pages/auth/reseting-password-not-valid.html.twig', []);
}
}
#[Route("/reseting-password", name: "reseting_password_validate", methods: ["POST"])]
public function resetingPasswordValidate(Request $request): JsonResponse
{
//$data = json_decode($request->getContent(), true);
$data = $request->request->all();
dump($data);
$clientHash = $data["clientHash"];
$newPassword = $data["password_new"];
$client = $this->clientRepository->findOneBy(['resetPasswordHash'=>$clientHash]);
$encoded = $this->encoder->hashPassword($client, $newPassword);
$client->setPassword($encoded);
$client->setResetPasswordHash(null);
$client->setResetPasswordHashValidTo(new \DateTime('1/1/2024'));
$this->clientRepository->save($client,true);
return new JsonResponse(["message" => "Heslo zmeneno!"], Response::HTTP_OK);
}
#[Route("/client/edit", name: "edit_client_info", methods: ["POST"])]
public function editClientBasic(Request $request): Response
{
$data = $request->request->all();
$clientId = $data['client_id'];
$firstname = $data['client']['name'];
$surname = $data['client']['surname'];
$username = $data['client']['username'];
$city = $data['client']['city'];
$countryId = $data['client']['country'];
$country = null;
if(intval($countryId)!==0){
$country = $this->countryRepository->findOneBy(['id'=>$countryId]);
}
$client = $this->clientRepository->findOneBy(['id'=>$clientId]);
$form=$this->createForm(ClientType::class,$client);
$form->handleRequest($request);
$updatedClient=null;
if($form->isSubmitted() && $form->isValid()){
dump($form->getExtraData());
$client
->setName($firstname)
->setSurname($surname)
->setUsername($username)
->setCity($city)
->setCountry($country)
->setDateUpdated(new DateTime('now'));
$updatedClient = $this->clientRepository->save($client,true);
}
// $data = [
// 'id' => $updatedClient->getId(),
// 'email' => $updatedClient->getEmail()
// ];
// if($updatedClient->getUsername() === $username && $updatedClient->getSurname() === $surname && $updatedClient->getName() === $firstname){
return $this->redirectToRoute('profile');
// }else{
// return new JsonResponse("Err", Response::HTTP_BAD_REQUEST);
// }
}
#[Route("/reset-password", name: "reset_password_page")]
public function resetPasswordPageAction(): Response
{
return $this->render('pages/auth/reset-password.html.twig');
}
#[Route("/sent-reset-password/{email}", name: "reset_password_sent",methods: ['GET'])]
public function resetPasswordSent($email): Response
{
return $this->render('pages/reseting-password-email-sent.html.twig',[
'email'=>$email
]);
}
#[Route("/invite-client", name: "invite_client", methods: ["POST"])]
public function inviteNewClient(Request $request): JsonResponse
{
$data = $request->request->all();
$email = $data['email'];
$client = $this->clientRepository->findBy(['email'=>$email]);
if($client!=null){
return new JsonResponse($data, Response::HTTP_FOUND);
}
// Create valid invite
$invitationHash = $this->generateRandomString();
$invite = new Invitation();
$invite
->setInvitedEmail($email)
->setInvitationHash($invitationHash)
->setInviteAccepted(false)
->setInviteSendDate(new \DateTime('now'));
$this->invitationRepository->save($invite,true);
//TODO Notify new client
return new JsonResponse($data, Response::HTTP_CREATED);
}
#[Route("/check-username-exist", name: "check_username_exist", methods: ["POST"])]
public function checkUsernameExistAction(Request $request): JsonResponse
{
$data = $request->request->all();
$username = $data['username'];
$client = $this->clientRepository->findOneBy(['username'=>$username]);
$exist=false;
if($client!=null){
$exist=true;
}
$data=[
"exist"=>$exist
];
return new JsonResponse($data,200);
}
#[Route("/check-email-exist", name: "check_email_exist", methods: ["POST"])]
public function checkEmailExistAction(Request $request): JsonResponse
{
$data = $request->request->all();
$email = $data['email'];
$client = $this->clientRepository->findOneBy(['email'=>$email]);
$exist=false;
if($client!=null){
$exist=true;
}
$data=[
"exist"=>$exist
];
return new JsonResponse($data,200);
}
#[Route(path: '/client-avatar-upload', name: 'clientUploadAvatar', methods: ['POST'])]
public function frontendClientUploadAvatarAction(Request $request): JsonResponse
{
$user = $this->getUser();
$client = $this->clientRepository->findOneByEmail($user->getUserIdentifier());
$avatarNew = $request->files->get('imageFile');
$form = $this->createForm(ClientType::class, $client);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$client
->setDateUpdated(new \DateTime('now'));
}
if($this->clientRepository->save($client,true)){
return new JsonResponse("Uploaded", Response::HTTP_OK);
}else{
return new JsonResponse("Error", Response::HTTP_BAD_REQUEST);
}
}
// HELPERS
public function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function getDefaultClientSettings($newClient):ClientSettings
{
$res = new ClientSettings();
$res->setDisplayContact(true)->setClient($newClient);
return $res;
}
// public function upload(Request $request):Response
// {
// $client = new Client();
// $form = $this->createForm(ImageType::class, $image);
// $token = $request->request->get('token');
// $form->handleRequest($request);
//
// if ($form->isSubmitted() && $this->isCsrfTokenValid('image-upload', $token)) {
// dump($image);
// dump($form->getData());
// $this->em->persist($image);
// $this->em->flush();
// return $this->redirectToRoute('admin_image_index');
// }
//
// return $this->render('admin/image/upload.html.twig', array(
// 'form' => $form->createView()
// ));
// }
}