<?php
namespace App\Controller\Customer;
use App\Entity\Addressing\Country;
use App\Entity\Addressing\County;
use App\Entity\Customer\Customer;
use App\Events\Customer\SubscriptionEvent;
use App\Manager\Customer\ConfirmationCommercialNotificationManager;
use App\Model\CustomerModel;
use App\Service\AuthTokenService;
use App\Service\CustomerService;
use App\Service\ReCaptcha;
use App\Validator\RegisterFormValidator;
use FOS\RestBundle\View\View;
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
use Sylius\Component\Resource\Exception\UpdateHandlingException;
use Sylius\Component\Resource\ResourceActions;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use function Sentry\captureException;
class CustomerController extends ResourceController
{
public function manageCustomerAction(Request $request)
{
$customerId = $request->get('customerId');
$customer = $this->getDoctrine()->getRepository(Customer::class)->find($customerId);
return $this->render('@templates/AdminCustom/Customer/manage-customer.html.twig', [
'customer' => $customer
]);
}
public function createAction(Request $request): Response
{
return $this->redirectToRoute('app_shop_customer_register');
}
public function disableCustomerAction(Request $request)
{
$customerModel = new CustomerModel($this->getDoctrine()->getManager());
$result = $customerModel->disableCustomer($request, $this->getUser());
$response = json_encode('Error');
if ($result == -1) {
$response = json_encode('Customer is already disabled');
} elseif ($result == 1) {
$response = json_encode('Success');
}
return new Response($response);
}
public function restoreCustomerAction(Request $request)
{
$customerModel = new CustomerModel($this->getDoctrine()->getManager());
$result = $customerModel->restoreCustomer($request);
$response = json_encode('Error');
if ($result == -1) {
$response = json_encode('Customer is already restored or is not disabled');
} elseif ($result == 1) {
$response = json_encode('Success');
}
return new Response($response);
}
public function registerAction()
{
$user = $this->getUser();
if ($user) {
$this->addFlash('already_logged_in', '1');
return $this->redirectToRoute('sylius_shop_homepage');
}
return $this->render('@templates/Account/register.html.twig', [
'countries' => $this->getDoctrine()->getRepository(Country::class)->findAll(),
]);
}
public function submitRegisterAction(Request $request)
{
$session = $request->getSession();
$registerFormValidator = new RegisterFormValidator($this->getDoctrine()->getManager(), $this->container);
$params = $request->request->all();
$reCaptcha = new ReCaptcha($_ENV['RECAPTCHA3_SECRET']);
if ($registerFormValidator->checkForm($request) && $reCaptcha->verify($params['g-recaptcha-response'], $request->getClientIp())) {
$customerService = new CustomerService($this->getDoctrine()->getManager(), $this->container->get('router'));
if ($customerService->registerNewCustomer($request)) {
$customer = $this->getDoctrine()->getRepository(Customer::class)->findOneByEmail($params['customerEmail']);
$address = $customerService->createNewAddressForCustomer($customer, $params, $this->getDoctrine()->getRepository(County::class));
if ($address) {
$this->getDoctrine()->getManager()->persist($address);
$this->getDoctrine()->getManager()->flush();
}
if (CustomerService::checkIfCustomerWantToSubscribe($request)) {
try {
$customerEvent = new GenericEvent($customer);
$eventDispatcher = $this->get('event_dispatcher');
$eventDispatcher->dispatch($customerEvent, 'app.customer.post_register');
$commercialNotificationService = $this->container->get('app.service.customer.commercial_notification');
$commercialNotificationService->addToQueueConfirmationEmailForCommercialNotificationForCustomer($customer, ConfirmationCommercialNotificationManager::EMAIL_TYPE_NEW_ACCOUNT_ID);
} catch (\Throwable $exception) {
captureException($exception);
}
$customerModel = new CustomerModel($this->getDoctrine()->getManager());
$customerModel->subscribeCustomerToNewsletter($customer, $request->getClientIp());
}
$token = AuthTokenService::authenticateNewCustomer($customer);
$this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch($event, 'security.interactive_login');
$session->set('_sylius.cart.FASHION_WEB', 180);
$session->save();
$response = array('success' => 1);
} else {
$response = array('fail' => 1);
}
} else {
if ($session->has('registerErrors')) {
$response = json_decode($session->get('registerErrors'));
} else {
$response = array('captcha_error' => 1);
}
}
return new Response(json_encode($response));
}
/**
* @param Request $request
* @return Response
* METODA OVERRIDE DIN SYLIUS CONTROLLER
*/
public function updateAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::UPDATE);
$resource = $this->findOr404($configuration);
$form = $this->resourceFormFactory->create($configuration, $resource);
if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true) && $form->handleRequest($request)->isValid()) {
$resource = $form->getData();
$event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
$customer = $this->findOr404($configuration);
$subscriptionEvent = new SubscriptionEvent($customer);
if ($form->has('subscribedToNewsletter')) {
if ($form->get('subscribedToNewsletter')->getData()) {
$this->get('event_dispatcher')->dispatch($subscriptionEvent, SubscriptionEvent::SUBSCRIBE_CUSTOMER);
} else {
$this->get('event_dispatcher')->dispatch($subscriptionEvent, SubscriptionEvent::UNSUBSCRIBE_CUSTOMER);
}
}
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
$this->flashHelper->addFlashFromEvent($configuration, $event);
$eventResponse = $event->getResponse();
if (null !== $eventResponse) {
return $eventResponse;
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
try {
$this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
} catch (UpdateHandlingException $exception) {
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle(
$configuration,
View::create($form, $exception->getApiResponseCode())
);
}
$this->flashHelper->addErrorFlash($configuration, $exception->getFlash());
return $this->redirectHandler->redirectToReferer($configuration);
}
if ($configuration->isHtmlRequest()) {
$this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
}
$postEvent = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
if (!$configuration->isHtmlRequest()) {
$view = $configuration->getParameters()->get('return_content', false) ? View::create($resource, Response::HTTP_OK) : View::create(null, Response::HTTP_NO_CONTENT);
return $this->viewHandler->handle($configuration, $view);
}
$postEventResponse = $postEvent->getResponse();
if (null !== $postEventResponse) {
return $postEventResponse;
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($form, Response::HTTP_BAD_REQUEST));
}
$initializeEvent = $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE, $configuration, $resource);
$initializeEventResponse = $initializeEvent->getResponse();
if (null !== $initializeEventResponse) {
return $initializeEventResponse;
}
$view = View::create()
->setData([
'configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $resource,
$this->metadata->getName() => $resource,
'form' => $form->createView(),
])
->setTemplate($configuration->getTemplate(ResourceActions::UPDATE . '.html'))
;
return $this->viewHandler->handle($configuration, $view);
}
public function updateAccountAction(Request $request): Response
{
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
return $this->render('@templates/Account/Customer/update.html.twig', [
'customerData' => CustomerService::retrieveCustomerDataForAccount($customer),
'translations' => CustomerService::retrieveTranslationsForCustomerAccount($this->container->get('translator')),
]);
}
public function updateProfile(Request $request): Response
{
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
return new Response(json_encode(CustomerService::updateCustomerData($request->request->all(), $customer, $this->getDoctrine()->getManager(), $this->container->get('translator'))));
}
public function tryToFindCustomerData(Request $request)
{
$customerService = new CustomerService($this->getDoctrine()->getManager(), $this->container->get('router'));
return new Response(json_encode($customerService->tryToFindCustomerDataByEmailOrPhone($request->get('email'), $request->get('phone'))));
}
}