<?php
namespace App\Application\Internit\SettingBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Application\Sonata\UserBundle\Entity\User;
use App\Application\Internit\ContentBundle\Controller\CRUD;
use Doctrine\Common\Collections\ArrayCollection;
use App\Application\Internit\RealEstateBundle\Entity\RealEstate;
use App\Application\Internit\ContactBundle\Entity\ContactUs;
/**
* Hierarchy Front controller.
*
* @Route("/")
*/
class SettingFrontController extends Controller
{
public function getBundleName()
{
return 'ApplicationInternitSettingBundle';
}
public function getEntityName()
{
return 'Hierarchy';
}
public function getFormType()
{
return 'App\Application\Internit\SettingBundle\Form\HierarchyType';
}
/**
* @Route("/", name="front_setting")
*/
public function indexAction(Request $request)
{
// dados enviados pelo assistente virtual (chatbot)
$chatbotData = array(
"nome" => $request->request->get('nome'),
"email" => $request->request->get('email'),
"telefone" => $request->request->get('telefone'),
);
$realEstates = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:Realty')->findIdsAndNames();
$builder = $this->getDoctrine()
->getRepository('ApplicationInternitBuilderBundle:Builder')->find(1);
return $this->render(
'@ApplicationInternit/SettingBundle/Resources/views/Home/home_front.html.twig',
array(
'data' => $realEstates,
'builder' => $builder,
'modaltab' => $request->query->get('modaltab'),
'chatbotData' => json_encode($chatbotData),
)
);
}
/**
* @Route("test")
*/
public function testAction()
{
return $this->render('@ApplicationInternit/SecurityBundle/Resources/views/Mail/Template-email/index.html.twig', array(
'data' => array('email' => '[email protected]', 'username' => 'username', 'password' => '123456')
));
}
/**
* @Route("/respond_account_activation_request", name="respond_account_activation_request")
*/
public function respondAccountActivationRequestAction()
{
$userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null;
$userType = isset($_REQUEST['userType']) ? $_REQUEST['userType'] : null;
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
$actionText = isset($_REQUEST['actionText']) ? $_REQUEST['actionText'] : null;
if (!empty($action) && !empty($userId)) {
$user = $this->container->get('doctrine')
->getRepository('ApplicationSonataUserBundle:User')
->find($userId);
if ($user) {
if ($userType == 'Corretor') {
$realEstates = $this->getRealEstates($user);
$dateOfBirth = $user->getDateOfBirth()->format('d/m/Y');
$message = "$actionText;;";
$message .= "Nome: {$user->getFirstname()};" .
"CPF: {$user->getCpf()};" .
"CRECI: {$user->getCreci()};" .
"Data de nascimento: {$dateOfBirth};" .
"Gênero: {$user->getGenre()};" .
"E-mail: {$user->getEmail()};" .
"Telefone: {$user->getPhone()};" .
"Imobiliária: {$realEstates};";
}
elseif ($userType == 'Imobiliária') {
$realEstate = $user->getRealEstates()[0];
$message = "$actionText;;";
$message .= "Nome: {$realEstate->getName()};" .
"Razão social: {$realEstate->getCorporateName()};" .
"CNPJ: {$realEstate->getCnpj()};" .
"CRECI Jurídico: {$realEstate->getCreci()};" .
"Telefone: {$realEstate->getPhone()};" .
"E-mail padrão: {$realEstate->getEmail()};"
;
}
return $this->render(
'@ApplicationInternit/SettingBundle/Resources/views/Setting/respondAccountActivationRequest.html.twig',
array(
'data' => $user,
'message' => $message,
'userType' => $userType,
'action' => $action,
'actionText' => $actionText
)
);
}
}
return $this->redirectToRoute('front_setting');
}
private function getRealEstates($user) {
return implode(', ', array_map(function($re) { return $re->getName(); }, $user->getRealEstates()->getValues()));
}
/**
* @Route("/activate_user_account", name="activate_user_account")
*/
public function activateUserAccount() {
$userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null;
$userType = isset($_REQUEST['userType']) ? $_REQUEST['userType'] : null;
$notifyUser = isset($_REQUEST['notifyUser']) ? $_REQUEST['notifyUser'] : null;
if ($userId) {
$user = $this->container->get('doctrine')
->getRepository('ApplicationSonataUserBundle:User')
->find($userId);
if ($user) {
$user->setEnabled(true);
$user->setUpdatedAt(new \DateTime());
$em = $this->container->get('doctrine')->getManager();
$em->persist($user);
$em->flush();
if ($notifyUser) {
// e-mail para corretor
$email = $this->get('admin.mail.service');
$email->setMessage()
->setTo(array(
$user->getEmail(),
))
->setBcc(array(
'[email protected]',
))
->setSubject("Conta ativada [Cadastro - $userType]")
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUserActivated.html.twig", array(
'data' => $user,
'userType' => $userType,
'accountAction' => 'ativada'
)), 'text/html');
$email->send();
}
$this->get('session')->getFlashBag()->set('flash_create_success', 'Conta ativada com sucesso');
return new JsonResponse(array('error' => false, 'message' => 'conta ativada'));
}
}
$this->get('session')->getFlashBag()->set('flash_create_error', 'Erro ao ativar conta');
return new JsonResponse(array('error' => true, 'message' => 'conta não localizada'));
}
/**
* @Route("/remove_user_account", name="remove_user_account")
*/
public function removeUserAccount()
{
$userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null;
$userType = isset($_REQUEST['userType']) ? $_REQUEST['userType'] : null;
$notifyUser = isset($_REQUEST['notifyUser']) ? $_REQUEST['notifyUser'] === "true" : null;
if ($userId) {
$user = $this->container->get('doctrine')
->getRepository('ApplicationSonataUserBundle:User')
->find($userId);
if ($user) {
if ($notifyUser) {
// e-mail para corretor
$email = $this->get('admin.mail.service');
$email->setMessage()
->setTo(array(
$user->getEmail(),
))
->setBcc(array(
'[email protected]',
))
->setSubject("Conta Reprovada [Cadastro - $userType]")
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUserActivated.html.twig", array(
'data' => $user,
'userType' => $userType,
'accountAction' => 'removida'
)), 'text/html');
$email->send();
}
$em = $this->container->get('doctrine')->getManager();
$em->remove($user);
$em->flush();
$this->get('session')->getFlashBag()->set('flash_create_success', 'Conta removida com sucesso');
return new JsonResponse(array('error' => false, 'message' => 'conta removida'));
}
}
$this->get('session')->getFlashBag()->set('flash_create_error', 'Erro ao remover conta');
return new JsonResponse(array('error' => true, 'message' => 'conta não localizada'));
}
/**
*
* @Route("/submitUser")
*/
public function submitUserAction()
{
$caracteres = "0123456789abcdefghijklmnopqrstuvwxyz+-/()";
$password = substr(str_shuffle($caracteres),0,10);
$realEstateName = (
isset($_REQUEST['realEstateName']) && !empty($_REQUEST['realEstateName'])
) ? $_REQUEST['realEstateName'] : 'Imobiliária Autônoma';
$realEstate = $this->container->get('doctrine')
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findBy(array('name' => $realEstateName));
if (empty($realEstate)) {
$this->get('session')->getFlashBag()->set('flash_create_error', 'Não foi possível criar a conta. Motivo: imobiliária informada não localizada.');
return $this->redirectToRoute('front_setting');
}
$realEstate = $realEstate[0];
$email = $_REQUEST['email'];
$userArray = $this->container->get('doctrine')
->getRepository('ApplicationSonataUserBundle:User')->findBy(array('email' => $email));
if (!empty($userArray)) {
$this->get('session')->getFlashBag()->set('flash_create_error', 'Não foi possível criar a conta. Motivo: e-mail fornecido já foi cadastrado.');
return $this->redirectToRoute('front_setting');
}
$request = $_REQUEST;
$user = new User();
$user->setFirstname($_REQUEST['firstName']);
$user->setCpf($_REQUEST['cpf']);
$user->setDateOfBirth(new \DateTime($_REQUEST['birthDay']));
$user->setPhone($_REQUEST['phone']);
$user->setGenre($_REQUEST['genre']);
$user->setEmail($_REQUEST['email']);
$user->setCreci($_REQUEST['creci']);
$user->setUsername($_REQUEST['email']);
$user->setPlainPassword($password);
$user->setEnabled(false);
$user->setRealEstates(array($realEstate));
$user->setCreatedAt(new \DateTime());
$user->setUpdatedAt(new \DateTime());
$data['password'] = $password;
$data['username'] = $_REQUEST['email'];
$data['name'] = $_REQUEST['firstName'];
$data['email'] = $_REQUEST['email'];
$data['verifier'] = 'imobiliária';
$em = $this->container->get('fos_user.user_manager');
$em->updateUser($user);
// e-mail para corretor
$email = $this->get('admin.mail.service');
$email->setMessage()
->setTo(array(
$_REQUEST['email'],
))
->setSubject("Conta criada [Cadastro - Corretor]")
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUser.html.twig", array(
'data' => $data,
)), 'text/html');
$email->send();
// e-mail para imobiliária
$email->setMessage()
->setTo(array(
$realEstate->getEmail()
))
->setSubject('Ativar conta [Cadastro - Corretor]')
->setBody(
$this->renderView('@ApplicationInternit/SettingBundle/Resources/views/Mail/emailActivateAccount.html.twig',
array(
'data' => $user
)), 'text/html'
);
$email->send();
$this->get('session')->getFlashBag()->set('flash_create_success', 'Conta criada com sucesso. Aguarde a aprovação por e-mail.');
return $this->redirectToRoute('front_setting');
}
/**
*
* @Route("/submitRealEstate")
*/
public function submitRealEstateAction()
{
$caracteres = "0123456789abcdefghijklmnopqrstuvwxyz";
$password = substr(str_shuffle($caracteres),0,10);
$email = $_REQUEST['email'];
$userArray = $this->container->get('doctrine')
->getRepository('ApplicationSonataUserBundle:User')->findBy(array('email' => $email));
if (!empty($userArray)) {
$this->get('session')->getFlashBag()->set('flash_create_error', 'Não foi possível criar a conta. Motivo: e-mail fornecido já foi cadastrado.');
return $this->redirectToRoute('front_setting');
}
$request = $_REQUEST;
$realEstate = new RealEstate();
$realEstate->setName($_REQUEST['name']);
$realEstate->setCnpj($_REQUEST['cnpj']);
$realEstate->setPhone($_REQUEST['phone']);
$realEstate->setEmail($_REQUEST['email']);
$realEstate->setCorporateName($_REQUEST['corporateName']);
$realEstate->setCreci($_REQUEST['creci']);
$realEstate->setCreatedAt(new \DateTime());
$realEstate->setUpdatedAt(new \DateTime());
$em = $this->container->get('doctrine')->getManager();
$em->persist($realEstate);
$em->flush($realEstate);
$user = new User();
$user->setFirstname($_REQUEST['name']);
$user->setPhone($_REQUEST['phone']);
$user->setCreci($_REQUEST['creci']);
$user->setEmail($_REQUEST['email']);
$user->setUsername($_REQUEST['email']);
$user->setPlainPassword($password);
$user->setEnabled(false);
$user->setCreatedAt(new \DateTime());
$user->setUpdatedAt(new \DateTime());
$user->setRealEstates([$realEstate]);
$group = $this->container->get('doctrine')
->getRepository('ApplicationSonataUserBundle:Group')
->findBy(['name' => 'Imobiliária']);
if (!empty($group)) {
$group = $group[0];
}
$user->addGroup($group);
$data['password'] = $password;
$data['username'] = $_REQUEST['email'];
$data['name'] = $_REQUEST['name'];
$data['email'] = $_REQUEST['email'];
$data['verifier'] = 'construtora';
$em = $this->container->get('fos_user.user_manager');
$em->updateUser($user);
$builder = $this->getDoctrine()
->getRepository('ApplicationInternitBuilderBundle:Builder')->find(1);
$email = $this->get('admin.mail.service');
$email->setMessage()
->setTo(array(
$user->getEmail(),
))
->setSubject("Conta criada [Cadastro - Imobiliária]")
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUser.html.twig", array(
'data' => $data,
)), 'text/html');
$email->send();
if ($builder) {
$accountCreationEmails = $builder->getAccountCreationEmailsToSend();
// mensagem para a construtora
$email->setMessage()
->setTo($accountCreationEmails)
->setSubject("Verificar conta [Cadastro - Imobiliária]")
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailActivateRealEstateAccount.html.twig", array(
'data' => $user,
)), 'text/html');
$email->send();
}
$this->get('session')->getFlashBag()->set('flash_create_success', 'Conta criada com sucesso. Aguarde a aprovação por e-mail.');
return $this->redirectToRoute('front_setting');
}
/**
*
* @Route("/submitContact")
*/
public function submitContactAction()
{
$request = $_REQUEST;
$contact = new ContactUs();
$contact->setName($_REQUEST['name']);
$contact->setEmail($_REQUEST['email']);
$contact->setPhone($_REQUEST['phone']);
$contact->setMessage($_REQUEST['message']);
$contact->setSource('externo');
$contact->setCreatedAt(new \DateTime());
$contact->setUpdatedAt(new \DateTime());
$em = $this->container->get('doctrine')->getManager();
$em->persist($contact);
$em->flush($contact);
$data['name'] = $_REQUEST['name'];
$data['email'] = $_REQUEST['email'];
$data['phone'] = $_REQUEST['phone'];
$data['message'] = $_REQUEST['email'];
$builder = $this->getDoctrine()
->getRepository('ApplicationInternitBuilderBundle:Builder')->find(1);
if ($builder) {
$email = $this->get('admin.mail.service');
$email->setMessage()
->setTo($builder->getContactEmailsToSend())
->setSubject("[Fale Conosco]")
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailContactFront.html.twig", array(
'data' => $data,
)), 'text/html');
$email->send();
}
$this->get('session')->getFlashBag()->set('flash_create_success', 'Mensagem enviada com sucesso');
return $this->redirectToRoute('front_setting');
}
}