<?php
namespace App\Controller;
use App\Service\SessionService;
use App\Form\RegistrationFormType;
use App\Form\CustomerProfilFormType;
use App\Entity\Customer\Customer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
// use App\Security\EmailVerifier;
use App\Security\CustomerFormAuthenticator;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use Symfony\Component\Form\FormError;
use App\Service\Tools;
use App\Service\ObpAPI;
class CustomerController extends AbstractController
{
private $requestStack;
private $url_bridge_shop = 'https://boutique.1055.fr/bridge-customers.php';
private $centre_prefere = 'lons';
private $obpAPIservice;
// private $emailVerifier;
public function __construct( RequestStack $requestStack, ObpAPI $obpAPIservice ) /*, EmailVerifier $emailVerifier*/
{
$this->requestStack = $requestStack;
$this->obpAPIservice = $obpAPIservice;
// $this->emailVerifier = $emailVerifier;
}
/**
* @Route("/mon-compte/portefeuille", name="wallet")
*/
public function walletCustomer(Request $request): Response
{
$session = $this->requestStack->getSession();
$cart = $session->get('cart');
if($this->container->get('security.token_storage')->getToken() != null) {
$time = new \DateTime(date("Y-m-d H:i:s"));
$customer = $this->container->get('security.token_storage')->getToken()->getUser();
$form = $this->createForm(CustomerProfilFormType::class, $customer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$customer->setDateUpd($time);
$entityManager = $this->getDoctrine()->getManager('customer');
$entityManager->persist($customer);
$entityManager->flush();
}
return $this->render('mon-compte/dashboard.html.twig', [
'customerProfilForm' => $form->createView(),
'cart' => $cart,
'controller_name' => 'CustomerController',
]);
}
return $this->render('mon-compte/dashboard.html.twig', [
'page_name' => 'wallet',
'cart' => $cart,
'controller_name' => 'CustomerController',
]);
}
/**
* @Route("/mon-compte", name="account")
*/
public function dashboardCustomer(Request $request): Response
{
// $em = $this->getDoctrine()->getManager('customer');
$session = $this->requestStack->getSession();
$cart = $session->get('cart');
if($this->container->get('security.token_storage')->getToken() != null) {
$time = new \DateTime(date("Y-m-d H:i:s"));
$customer = $this->container->get('security.token_storage')->getToken()->getUser();
$form = $this->createForm(CustomerProfilFormType::class, $customer);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$customer->setDateUpd($time);
$entityManager = $this->getDoctrine()->getManager('customer');
$entityManager->persist($customer);
$entityManager->flush();
}
return $this->render('mon-compte/dashboard.html.twig', [
'page_name' => 'page_account',
'customerProfilForm' => $form->createView(),
'cart' => $cart,
'controller_name' => 'CustomerController',
]);
} else {
return $this->redirectToRoute('customer_login');
}
// return $this->render('mon-compte/dashboard.html.twig', [
// 'page_name' => 'page_account',
// 'cart' => $cart,
// 'controller_name' => 'CustomerController',
// ]);
}
/**
* @Route("/inscription", name="app_register")
*/
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasherInterface, GuardAuthenticatorHandler $guardHandler, CustomerFormAuthenticator $authenticator): Response
{
$time = new \DateTime(date("Y-m-d H:i:s"));
$user = new Customer();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted()) {
$dataObpAPI = array(
'firstname' => $user->email,
'lastname' => $user->email,
'email' => $user->email,
'password' => $form->get('plainPassword')->getData(),
'g-recaptcha-response' => $request->request->get('g-recaptcha-response'),
'instance' => $this->obpAPIservice->getBaseInstance(),
);
$urlApi = $this->obpAPIservice->getContactApiUrl();
$customer_obp_infos = json_decode(
$this->obpAPIservice->CallAPI('POST', $urlApi.'/cashless/users', json_encode($dataObpAPI))
);
if(!$customer_obp_infos->meta->success && $customer_obp_infos->meta->type == 'EXISTING_EMAIL') {
$form['email']->addError(new FormError('Un compte est déjà associé à ce mail'));
}
}
if ($form->isSubmitted() && $form->isValid() && $customer_obp_infos->meta->success) {
$phone = $user->getPhone();
$phoneMobile = $user->getPhoneMobile();
$user->setPhone(str_replace('±','+',$phone));
$user->setPhoneMobile(str_replace('±','+',$phoneMobile));
// encode the plain password
// $user->setPassword(
// $userPasswordHasherInterface->hashPassword(
// $user,
// $form->get('plainPassword')->getData()
// )
// );
$user->setDateAdd($time);
$user->setDateUpd($time);
// $user->setDateConnexion($time);
// $user->setActive(false);
$entityManager = $this->getDoctrine()->getManager('customer');
$entityManager->persist($user);
$entityManager->flush();
// $number = (int)$user->getId() + 100000;
$number = str_pad((int)$user->getId(), 6, '0', STR_PAD_LEFT);
$user->setCustomerNumber($number);
$user->setStatut('Actif');
$user->setActive(1);
$entityManager->persist($user);
$entityManager->flush();
// // generate a signed url and email it to the user
// $this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
// (new TemplatedEmail())
// ->from(new Address('noreply@1055.fr', 'Team 1055'))
// ->to($user->getMail())
// ->subject('Veuillez confirmer votre email')
// ->htmlTemplate('registration/confirmation_email.html.twig')
// );
// // do anything else you need here, like send an email
$guardHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$authenticator,
'main' // firewall name in security.yaml
);
$query = array( 'create_customer_shop' => true, 'mail' => $request->request->get('registration_form')['email'], 'secret' => '', 'centre' => $this->centre_prefere );
$check_shop_customer = json_decode(Tools::CallAPI('POST', $this->url_bridge_shop, $query));
return $this->redirectToRoute('home');
} else if($customer_obp_infos && !$customer_obp_infos->meta->success && !$customer_obp_infos->meta->type == 'EXISTING_EMAIL') {
$form['email']->addError(new FormError($customer_obp_infos->meta->message));
}
return $this->render('mon-compte/register.html.twig', [
'page_name' => 'page_register',
'registrationForm' => $form->createView(),
]);
}
/**
* @Route("/verify/email", name="app_verify_email")
*/
public function verifyUserEmail(Request $request): Response
{
// dd($this->getUser());
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
// validate email confirmation link, sets Customer::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $this->getUser());
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register');
}
// @TODO Change the redirect on success and handle or remove the flash message in your templates
$this->addFlash('success', 'Votre adresse e-mail a été vérifiée.');
return $this->redirectToRoute('customer_login');
}
/**
* @Route("/send_verify/email", name="app_resend_verify_email")
*/
public function resendEmail(Request $request): Response
{
$customer = $this->getDoctrine()
->getRepository(Customer::class)
->find((int)$request->query->get('id'));
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $customer,
(new TemplatedEmail())
->from(new Address('noreply@1055.fr', 'Team 1055'))
->to($customer->getEmail())
->subject('Veuillez confirmer votre email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
$this->addFlash('success', 'Un mail d\'activation à été envoyé à l\'adresse mail '.$customer->getMail());
return $this->redirectToRoute('customer_login');
}
}