<?php
namespace App\Controller;
use App\Form\User\Compte\ReferentType;
use App\Form\User\Compte\UserAddress;
use App\Form\User\Compte\UserBrand;
use App\Form\User\Compte\UserGeneral;
use App\Form\User\Compte\UserIbans;
use App\Form\User\Compte\UserPassword;
use App\Form\User\Compte\UserPhone;
use App\Form\User\Compte\UserWholesaler;
use App\Form\User\DeliveryType;
use App\Form\User\UserRegisterType;
use App\Manager\SponsorshipRequestManager;
use App\Manager\User\UserManager;
use App\Model\User\Identity;
use App\Model\User\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
class UserController extends APIController
{
/**
* @Route("/user", name="user")
*/
public function index()
{
return $this->render('user/index.html.twig', [
'controller_name' => 'UserController',
]);
}
/**
* @Route("/inscription", name="kiwi_register_user")
*/
public function register(Request $request, SponsorshipRequestManager $sponsorshipRequestManager)
{
$referralCode = $request->request->get('user_register')['referralCode'] ?? $request->query->get('referralCode') ?? null;
$user = new User();
$identity = new Identity();
if ($facebookUser = $this->requestStack->getSession()->get('kiwi_facebook_user')) {
$facebookUser = json_decode( $this->requestStack->getSession()->get('kiwi_facebook_user'), true);
$identity->setFirstName($facebookUser['data']['first_name']);
$identity->setLastName($facebookUser['data']['last_name']);
$user->setIdentity($identity);
$user->setEmail($facebookUser['data']['email']);
}
$form = $this->createForm(UserRegisterType::class, $user);
$user->setIdentity(
(new Identity())
->setFirstName('')
->setLastName('')
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$json = $serializer->serialize($form->getData(), 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]);
$response = $this->APIKiwi->register($json);
try {
$response->getContent();
$this->requestStack->getSession()->remove('kiwi_facebook_user');
if ($form->getData()->getReferralCode() !== null) {
$email = $form->getData()->getEmail();
$refferalCode = $form->getData()->getReferralCode();
$sponsorshipRequestManager->postAndCheckGodChildExist($email, $refferalCode);
}
return $this->redirectToRoute('kiwi_congratulation_register');
} catch (ClientExceptionInterface $e) {
$content = json_decode($response->getContent(false), true);
if( isset($content['@type']) && $content['@type'] === 'ConstraintViolationList' && isset($content['violations'])) {
foreach ($content['violations'] as $violation) {
$this->addFlash(
'warning',
sprintf("%s %s",
$this->translator->trans(sprintf('api.validation.properties.%s', $violation['propertyPath']), [], 'api'),
$this->translator->trans(sprintf('api.validation.codes.%s', $violation['code']), [], 'api')
)
);
}
} else {
$this->logger->error(sprintf("%s : %s", 'ClientException', $e->getMessage()), $e->getTrace());
$this->addFlash('warning', $this->translator->trans("api.validation.errors.generic", [], "api"));
}
} catch (\Exception $e) {
$this->logger->error(sprintf("%s : %s", get_class($e),$e->getMessage()), $e->getTrace());
$this->addFlash('warning', $this->translator->trans("api.validation.errors.generic", [], "api"));
}
}
return $this->render('user/register.html.twig', [
'form' => $form->createView(),
'referralCode' => $referralCode,
]);
}
/**
* @Route("/mon-compte", name="kiwi_account")
* @param Request $request
* @param UserManager $userManager
* @return Response
* @IsGranted("IS_AUTHENTICATED_FULLY")
*/
public function account(Request $request, UserManager $userManager, SponsorshipRequestManager $sponsorshipRequestManager)
{
$userInterface = $this->getUser();
$user = $this->getUserData();
$email = $user->getEmail();
$referer = $request->request->get('referer');
$formGeneral = $this->createForm(UserGeneral::class, $user);
$formGeneral->handleRequest($request);
if ($formGeneral->isSubmitted() && $formGeneral->isValid()) {
$data = $userManager->prepareUserGeneral($user, $request->request->get('user_general'), $userInterface);
if ($email != $formGeneral->getData()->getEmail()) {
$userManager->requestUser($userInterface, '/users/' . $userInterface->getId(), $data, 'put_user_general');
return $this->redirectToRoute('app_logout');
} else {
$userManager->sendCreateOrUpdateDataCustomerToSalesforce($userInterface);
}
$userManager->requestUser($userInterface, '/users/' . $userInterface->getId(), $data, 'put_user_general');
if ($referer && in_array('catalog', explode('/', $referer))) {
return $this->redirect($referer);
}
}
$formAddress = $this->createForm(UserAddress::class, $user);
$formAddress->handleRequest($request);
if ($formAddress->isSubmitted() && $formAddress->isValid()) {
$data = $userManager->prepareUserGeneral($user, $request->request->get('user_address'), $userInterface);
$userManager->requestUser($userInterface, '/users/' . $userInterface->getId(), $data, 'put_user_general');
$userManager->sendCreateOrUpdateDataCustomerToSalesforce($userInterface);
if ($referer && in_array('catalog', explode('/', $referer))) {
return $this->redirect($referer);
}
}
$formPassword = $this->createForm(UserPassword::class, $user, ['validation_groups' => 'post_user_register_godparent']);
$formPassword->handleRequest($request);
if ($formPassword->isSubmitted() && $formPassword->isValid()) {
$data = $userManager->preparePasswordChange($user, $request->request->get('user_password'));
$userManager->requestUser($userInterface,'/users/passwordchange/' . $user->getId(), $data, 'put_user_password');
}
$formBrand = $this->createForm(UserBrand::class, $user);
$formBrand->handleRequest($request);
if ($formBrand->isSubmitted() && $formBrand->isValid()) {
$data = $userManager->prepareOptinBrand($user, $request->request->get('user_brand'));
$userManager->sendCreateOrUpdateDataCustomerToSalesforce($userInterface);
$userManager->requestUser($userInterface, '/users/'.$userInterface->getId(), $data, 'put_optin_brand');
}
$formPhone = $this->createForm(UserPhone::class, $user);
$formPhone->handleRequest($request);
if ($formPhone->isSubmitted() && $formPhone->isValid()) {
$data = $userManager->prepareOptinPhone($user, $request->request->get('user_phone'));
$userManager->sendCreateOrUpdateDataCustomerToSalesforce($userInterface);
$userManager->requestUser($userInterface, '/users/'.$userInterface->getId(), $data, 'put_optin_phone');
}
$formWholesaler = $this->createForm(UserWholesaler::class, $user->getAdditionalInformation());
$formWholesaler->handleRequest($request);
if ($formWholesaler->isSubmitted() && $formWholesaler->isValid()) {
$dataRequest = $request->request->all();
$userData = $request->request->get('user');
$newFormat = [];
foreach ($userData['additionalInformation'] as $info) {
if (!empty($info)) {
$newFormat[] = ["information" => $info];
}
}
$data = $userManager->prepareWholesaler($user, $newFormat);
$userManager->requestUser($userInterface, '/users/' . $userInterface->getId(), $data, 'put_user_wholesaler');
return $this->redirectToRoute('kiwi_account');
}
$formReferent = $this->createForm(ReferentType::class, $user);
$formReferent->handleRequest($request);
if ($formReferent->isSubmitted() && $formReferent->isValid()) {
$userManager->requestUser($userInterface, '/users/' . $user->getId(), $request->request->get('referent'), 'put_user_referent');
}
if (isset($_ENV['PROJECT_TYPE']) && 'puntos' === $_ENV['PROJECT_TYPE']) {
$template = 'user/account_tabs.html.twig';
$formDelivery = $this->createForm(DeliveryType::class, $user);
$formDelivery->handleRequest($request);
if ($formDelivery->isSubmitted() && $formDelivery->isValid()) {
$userManager->prepareAddressDelivery($user, $request->request->get('delivery'), $userInterface);
if ($referer && in_array('catalog', explode('/', $referer))) {
return $this->redirect($referer);
}
}
return $this->render($template, [
'user' => $this->getUser(),
'email' => $user->getEmail(),
'formGeneral' => $formGeneral->createView(),
'formPassword' => $formPassword->createView(),
'formBrand' => $formBrand->createView(),
'formPhone' => $formPhone->createView(),
'formDelivery' => $formDelivery->createView(),
'formAddress' => $formAddress->createView(),
'formReferent' => $formReferent->createView(),
'formWholesaler' => $formWholesaler->createView(),
]);
}
if (isset($_ENV['PROJECT_TYPE']) && 'step' === $_ENV['PROJECT_TYPE']) {
$template = 'user/account_tabs.html.twig';
$formIban = $this->createForm(UserIbans::class, $user);
$formIban->handleRequest($request);
if ($formIban->isSubmitted() && $formIban->isValid()) {
$data = $userManager->prepareIbanBic($user, $request->request->get('user_ibans'));
$userManager->requestUser($userInterface, '/ibans/alone', $data->getIbans()[0], 'post_user_iban_bic', 'POST');
}
return $this->render($template, [
'user' => $this->getUser(),
'email' => $user->getEmail(),
'formGeneral' => $formGeneral->createView(),
'formPassword' => $formPassword->createView(),
'formBrand' => $formBrand->createView(),
'formPhone' => $formPhone->createView(),
'formAddress' => $formAddress->createView(),
'formReferent' => $formReferent->createView(),
'formIbans' => $formIban->createView(),
'formWholesaler' => $formWholesaler->createView(),
]);
}
$template = 'user/account.html.twig';
// ---- GESTION FORM GENERAL ----
return $this->render($template, [
'user' => $this->getUser(),
'email' => $user->getEmail(),
'formGeneral' => $formGeneral->createView(),
'formPassword' => $formPassword->createView(),
'formBrand' => $formBrand->createView(),
'formAddress' => $formAddress->createView(),
'formReferent' => $formReferent->createView(),
]);
}
/**
* @Route("/felicitation-inscription", name="kiwi_congratulation_register")
*/
public function congratulationRegister()
{
return $this->render('security/congratulation_register.html.twig');
}
/**
* @Route("/mon-espace", name="kiwi_user_space")
* @IsGranted("IS_AUTHENTICATED_FULLY")
*/
public function mySpace()
{
return $this->render('user/user_space.html.twig');
}
}