<?php
namespace App\Controller;
use App\Form\AccountType;
use App\Form\PasswordChangeType;
use App\Repository\PublicationRepository;
use Doctrine\ORM\EntityManagerInterface;
//use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Psr\Container\ContainerInterface;
use Sulu\Bundle\CommunityBundle\Controller\AbstractController;
use Sulu\Bundle\MediaBundle\Api\Media;
use Sulu\Bundle\MediaBundle\Entity\MediaInterface;
use Sulu\Bundle\SecurityBundle\Entity\User;
use Sulu\Component\Media\SystemCollections\SystemCollectionManager;
use Sulu\Component\Media\SystemCollections\SystemCollectionManagerInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Sulu\Bundle\MediaBundle\Media\Manager\MediaManagerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
class ProfileController extends AbstractController
{
private $entityManager;
private $encoder;
protected $container;
private $mediaManager;
private $collectionManager;
public function __construct(EntityManagerInterface $entityManager, UserPasswordEncoderInterface $encoder, ContainerInterface $container,MediaManagerInterface $mediaManager,SystemCollectionManagerInterface $collectionManager)
{
$this->entityManager = $entityManager;
$this->encoder=$encoder;
$this->container=$container;
$this->mediaManager=$mediaManager;
$this->collectionManager=$collectionManager;
if (is_callable('parent::__construct')) {
parent::__construct();
}
}
/**
* @Route("/profile/profile-Publications", name="profile_publications")
*/
public function profilePublications(PublicationRepository $publicationRepository)
{
$user=$this->getUser();
$publications= $publicationRepository->findBy(['user' => $user->getId()]);
return $this->render('Profile/profil-publications.html.twig',['publications'=>$publications, 'user'=>$user]);
}
/**
* @Route("/profile/profile-Account", name="profile_account")
*/
public function profilAccountSettings(Request $request)
{
/** @var User $user */
$user=$this->getUser();
$form = $this->createForm(AccountType::class, $user);
$form->handleRequest($request);
$entityManager = $this->getDoctrine()->getManager();
if ($form->isSubmitted() && $form->isValid()) {
$fullName=trim($form->get('fullName')->getData());
$firstname=$fullName;
$lastname=$fullName;
if(str_contains($fullName, ' ')){
$fullName=explode(' ',$fullName);
$firstname=$fullName[0];
if(count($fullName)==1){
$firstname=$fullName[1];
$lastname=$fullName[1];
} elseif (count($fullName)==2){
$lastname=$fullName[1];
}else{
array_shift($fullName);
$lastname=implode(" ",$fullName);
}
}
$user->setFirstName($firstname);
$user->setLastName($lastname);
$user->setEmail($form->get('email')->getData());
$this->saveMediaFields($form, $user, $request->getLocale());
if($form->has('avatar')){
$user->setPictureSocial(null);
}
$entityManager->persist($user);
$entityManager->flush();
//$this->addFlash('success', 'You have successfully modified your account!');
}
return $this->render('Profile/profile-settings-account.html.twig', ['form'=> $form->createView(), 'user'=>$user]);
}
///////////////////////////
/**
* @Route("/api/profile/profile-Account", name="update", methods={"POST"})
*/
public function profilAccountSettingsAPI(Request $request)
{
$data = json_decode($request->getContent(), true);
$user = $this->entityManager->getRepository("App\Entity\User")->findOneBy(['username' => $data['email']]);
if ($user) {
$user->setFullname($data['name']);
$user->setCountry($data['country']);
$this->entityManager->persist($user); // Use $this->entityManager
$this->entityManager->flush(); // Use $this->entityManager
return new JsonResponse([
'FullName' => $user->getFullName(),
'Email' => $user->getUserName(),
'Country' => $user->getCountry()]);
} else {
return new JsonResponse("User not found", 404);
}
}
/**
* @Route("/api/update-password", name="update_password", methods={"POST"})
*/
public function updatePassword(Request $request, UserPasswordEncoderInterface $encoder): Response
{
$data = json_decode($request->getContent(), true);
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $data['email']]);
if (!$user) {
return $this->json(['message' => 'User not found'], Response::HTTP_NOT_FOUND);
}
$currentPassword = $data['current_password'];
$newPassword = $data['new_password'];
if (!$encoder->isPasswordValid($user, $currentPassword)) {
return $this->json(['message' => 'Current password is incorrect'], Response::HTTP_UNAUTHORIZED);
}
$hashedPassword = $encoder->encodePassword($user, $newPassword);
$user->setPassword($hashedPassword);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
return $this->json(['message' => 'Password updated successfully'], Response::HTTP_OK);
}
////////////////////////////////
/**
* @Route("/profile/profile-Account-Deactivate", name="profile_deactivation")
*/
public function profilAccountDeactivation(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$user=$this->getUser();
$deactivation_reason=$request->request->get('deactivation-select');
if($deactivation_reason){
$user->setDeleted(true);
$user->setDeletedAt(new \DateTime());
$user->setDeactivationReason($deactivation_reason);
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute("sulu_community.logout");
}
return $this->redirectToRoute("/");
}
/**
* @Route("/profile/profile-Security", name="profil_security")
*/
public function profilSecuritySettings(Request $request)
{
$user=$this->getUser();
$form = $this->createForm(PasswordChangeType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$current_password= $form->get('cuurent_password')->getData();
$new_password= $form->get('plainPassword')->getData();
if($this->encoder->isPasswordValid($user, $current_password)){
$user->setPassword( $this->encoder->encodePassword($user, $new_password));
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('success', 'You have successfully modified your password!');
}else{
$this->addFlash('error', 'Your password is incorrect');
}
}
return $this->render('Profile/profile-settings-security.html.twig', ['form'=> $form->createView(), 'user'=>$user]);
}
/**
* @Route("/profile/profile-Notifications", name="profile_notifications")
*/
public function profilNotificationsSettings()
{
$user=$this->getUser();
return $this->render('Profile/profile-settings-notifications.html.twig', ['user'=>$user]);
}
private function saveMediaFields(FormInterface $form, User $user, string $locale): void
{
$this->saveAvatar($form, $user, $locale);
}
protected function saveAvatar(FormInterface $form, User $user, string $locale): ?Media
{
if (!$form->has('avatar')) {
return null;
}
/** @var UploadedFile|null $uploadedFile */
$uploadedFile = $form->get('avatar')->getData();
if (null === $uploadedFile) {
return null;
}
$avatar = $user->getContact()->getAvatar();
/** @var MediaInterface|null $avatar */
$apiMedia = $this->saveMedia($uploadedFile, null !== $avatar ? $avatar->getId() : null, $locale, $user->getId());
$user->getContact()->setAvatar($apiMedia->getEntity());
return $apiMedia;
}
private function saveMedia(UploadedFile $uploadedFile, ?int $id, string $locale, ?int $userId): Media
{
return $this->mediaManager->save(
$uploadedFile,
[
'id' => $id,
'locale' => $locale,
'title' => $uploadedFile->getClientOriginalName(),
'collection' => $this->getContactMediaCollection(),
],
$userId
);
}
private function getContactMediaCollection(): int
{
return $this->collectionManager->getSystemCollection('sulu_contact.contact');
}
}