<?php
namespace App\Controller;
use App\Entity\Company;
use App\Entity\Product;
use App\Entity\User;
use App\Form\CompanyIndividualType;
use App\Form\CompanyType;
use App\Form\ForgotPasswordType;
use App\Form\ProductType;
use App\Form\UserType;
use App\Repository\CompanyRepository;
use App\Repository\PageRepository;
use App\Repository\SubCategoryRepository;
use App\Repository\UserRepository;
use App\Services\File;
use App\Services\Mail;
use App\Services\MangoPayService;
use App\Services\Password;
use Doctrine\ORM\EntityManagerInterface;
use MangoPay\UserLegal;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\String\Slugger\SluggerInterface;
class SecurityController extends AbstractController
{
/**
* @var EntityManagerInterface
*/
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @Route("/client/connexion", name="app_login")
*/
public function loginClient(Mail $mail, MangoPayService $mangoPayService, AuthenticationUtils $authenticationUtils, Request $request, UserPasswordEncoderInterface $encoder): Response
{
if ($this->getUser()) {
$target = $request->query->get('target');
if ($target) { // button in home page that redirct to reseaux sociaux
return $this->redirectToRoute('reseau-sociaux_home');
}
return $this->redirectToRoute('front_home');
}
$redirectUrl = $request->query->get('redirect', null);
$user = new User();
$form = $this->createForm(UserType::class, $user)->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$passwordEncoded = $encoder->encodePassword($user, $user->getPassword());
$user->setPassword($passwordEncoded);
$user->setRoles(['ROLE_USER']);
$this->em->persist($user);
$this->em->flush();
$mail->ConfirmationClient($user);
$this->addFlash('success', 'Vous êtes maintenant inscrit, Votre compte est en attente de validation');
return $this->redirectToRoute('app_login');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'form' => $form->createView(),
'redirect' => $redirectUrl
]);
}
/**
* @Route("/acces-prestataire", name="app_login_enterprise")
*/
public function loginEnterprise(AuthenticationUtils $authenticationUtils)
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login_company.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
/**
* @Route("/inscription-prestataire/{type}/etape-1", name="front_subscription_company_step1")
*/
public function subscriptionCompanyStep1(
Request $request,
string $type,
UserPasswordEncoderInterface $encoder,
SluggerInterface $slugger,
SessionInterface $session,
PageRepository $pageRepository,
MangoPayService $mangoPayService)
{
if (($type != Company::COMPANY_TYPE_ENTREPRISE) && ($type != Company::COMPANY_TYPE_INDIVIDUEL)){
throw new AccessDeniedException("Acces interdit : type de prestataire $type inconnu");
}
$company = new Company();
if ($type == Company::COMPANY_TYPE_ENTREPRISE){
$form = $this->createForm(CompanyType::class, $company)->handleRequest($request);
}else if ($type == Company::COMPANY_TYPE_INDIVIDUEL){
$form = $this->createForm(CompanyIndividualType::class, $company)->handleRequest($request);
}
if ($form->isSubmitted() && $form->isValid()) {
$passwordEncoded = $encoder->encodePassword($company, $company->getPassword());
$company->setPassword($passwordEncoded);
$companyName = $company->getCompanyName();
if (empty($companyName)) {
$companyName = $form->get("contactName")->getNormData()." ".$form->get("firstName")->getNormData();
}
$sluggedName = $slugger->slug($companyName)->lower();
$company->setCompanySlug($sluggedName);
$company->setRoles(["ROLE_ENTERPRISE"]);
$company->setIsDirectReservationMode(0);
$company->setCreatedAt( new \DateTime());
$this->em->persist($company);
$this->em->flush();
$session->set('idCompany', $company->getId());
$session->set('isSubscription', true);
return $this->redirectToRoute('front_subscription_company_confirmation');
//return $this->redirectToRoute('front_subscription_company_step2');
}
return $this->render('security/subscription_company_step1.html.twig', [
'form' => $form->createView(),
'type' => $type,
'cgv' => $pageRepository->findOneBy(['name' => 'cgv'])
]);
}
/**
* @Route("/inscription-prestataire/etape-2", name="front_subscription_company_step2")
*/
public function SubscriptionCompanyStep2(SessionInterface $session, Request $request, CompanyRepository $companyRepository, SluggerInterface $slugger, File $file)
{
if (!$session->get('idCompany')) {
return $this->redirectToRoute('app_login_enterprise');
}
$company = $companyRepository->find($session->get('idCompany'));
$ifYoutube = false;
$product = new Product();
$form = $this->createForm(ProductType::class, $product, ['ifYoutube' => $ifYoutube, 'isSubscription' => true,'isNew' => true, 'user' => $company])->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$contentProduct = str_replace('script>', '', $product->getText());
$product->setText($contentProduct);
$product->setCompany($company);
$slugTitle = $slugger->slug($product->getName())->lower();
$product->setProductSlug($slugTitle);
foreach ($product->getPhotos() as $photo) {
$filename = $file->uploadPhotoProduct($photo->getUrl());
$photo->setUrl($filename);
$photo->setProduct($product);
}
if (!empty($request->get('clothing'))) {
$product->setSizes($request->get('clothing'));
}
if (!empty($request->get('color'))) {
$product->setColors($request->get('color'));
}
$arrayTransporteurs = [];
if ($request->get('transporteurs')) {
foreach ($request->get('transporteurs') as $id => $value) {
$arrayTransporteurs[] = $id;
}
}
$product->setTransporteurs($arrayTransporteurs);
$this->em->persist($product);
$this->em->flush();
$session->set('isSubscription', true);
return $this->redirectToRoute('front_subscription_company_confirmation');
}
return $this->render('security/subscription_company_step2.html.twig', [
'form' => $form->createView()
]);
}
/**
* @Route("/inscription-prestataire/confirmation", name="front_subscription_company_confirmation")
*/
public function confirmationSubscription(SessionInterface $session, Mail $mail, CompanyRepository $companyRepository)
{
if (!$session->get('isSubscription')) {
return $this->redirectToRoute('front_subscription_company_step1');
}
if (!$session->get('idCompany')) {
return $this->redirectToRoute('app_login_enterprise');
}
$company = $companyRepository->find($session->get('idCompany'));
//$session->remove('isSubscription');
$mail->subscriptionConfirm($company);
$mail->subscriptionConfirmRoAdmin();
return $this->render('security/subscription_company_confirmation.html.twig');
}
/**
* @Route("/mot-de-passe-oublie", name="front_forgot_password")
*/
public function forgotPassword(Mail $mail, Request $request, UserRepository $userRepository, CompanyRepository $companyRepository, UserPasswordEncoderInterface $userPasswordEncoder)
{
$form = $this->createForm(ForgotPasswordType::class)->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $userRepository->findOneBy(['email' => $form->get('email')->getData()]);
if (!$user) {
$user = $companyRepository->findOneBy(['email' => $form->get('email')->getData()]);
}
if (!$user) {
$this->addFlash('danger', 'Aucun compte ne correspond à cette adresse mail');
return $this->redirectToRoute('front_forgot_password');
}
$newPassword = Password::generatePassword(8);
$encodedPassword = $userPasswordEncoder->encodePassword($user, $newPassword);
$user->setPassword($encodedPassword);
$this->em->flush();
$mail->forgotPassword($newPassword, $user);
$this->addFlash('success', 'Un mail vient de vous être envoyé avec un nouveau mot de passe.');
return $this->redirectToRoute('front_forgot_password');
}
return $this->render('security/forgot_password.html.twig', [
'form' => $form->createView()
]);
}
/**
* @Route("/inscription/get-subcategory", name="front_company__subscription_get_subcategory")
*/
public function getSubCategory(Request $request, SubCategoryRepository $subCategoryRepository)
{
if ($request->get('data')) {
$idCategory = json_decode($request->get('data'));
$subCategory = $subCategoryRepository->find($idCategory->idCategory);
return $this->json([
'isClothing' => $subCategory->getIsClothing(),
'isClothingHTML' => $this->render('front/html/clothing.html.twig')
]);
}
}
/**
* @Route("/deconnexion", name="deconnexion")
*/
public function deconnecter(UserRepository $repo,CompanyRepository $comp)
{
$userconn = $this->getUser();
$user = $userconn ?($repo->find($userconn)?$repo->find($userconn):$comp->find($userconn)):null;
if($user == null)
{
return $this->redirectToRoute('front_home');
}
$user->setStatuCon(false);
$this->em->persist($user);
$this->em->flush();
return $this->redirectToRoute('app_logout');
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}