<?php
namespace App\Application\Internit\LeadBundle\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\Internit\LeadBundle\Entity\Lead;
use App\Application\Internit\LeadBundle\Entity\ChatbotLead;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Product Front controller.
*
* @Route("/api/leads")
*/
class ProductFrontController extends Controller
{
public function getBundleName()
{
return 'ApplicationInternitLeadBundle';
}
public function getEntityName()
{
return 'Product';
}
public function getFormType()
{
return 'App\Application\Internit\LeadBundle\Form\ProductType';
}
/**
* @Route("/send", name="front_product_lead_send")
* @Method("POST")
*/
public function send(Request $request)
{
$data = json_decode($request->getContent());
$statusCode=400;
$result=[];
if(!$data)
return $this->sendStatus(400,"New Lead is not valid");
if(isset($data->token)){
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->findOneByToken($data->token);
if(!$product)
return $this->sendStatus(404,"Product not found");
if(!empty($data->name) &&
!empty($data->origem) &&
!empty($data->group)
){
// form de whatsapp não traz e-mail
$emailLead = isset($data->email) ? $data->email : '';
$extraInfo = array();
$to = $this->get('tupi.caster.service')->next($product, $emailLead);
//dd($to);
// dump($to);exit;
$newLead = new Lead();
//Obrigatórios
$newLead->setName($data->name);
$newLead->setGroup($data->group);
$newLead->setOrigem($data->origem);
$newLead->setProduct($product);
$newLead->setEmail($emailLead);
$newLead->setPhone(isset($data->phone) ? $data->phone : '');
//Opcionais
if(isset($data->fixedPhone)) {
$newLead->setFixedPhone(($data->fixedPhone ? $data->fixedPhone : ''));
}
if(isset($data->empreendimento))
$newLead->setEmpreendimento(($data->empreendimento ? $data->empreendimento : ''));
if(isset($data->utm_source))
$newLead->setUtm_source(($data->utm_source ? $data->utm_source : ''));
if(isset($data->utm_medium))
$newLead->setUtm_medium(($data->utm_medium ? $data->utm_medium : ''));
if(isset($data->utm_campaign))
$newLead->setUtm_campaign(($data->utm_campaign ? $data->utm_campaign : ''));
if(isset($data->message))
$newLead->setMessage(($data->message ? $data->message : ''));
// e-mail que a construtora configura para receber os leads deste produto.
$productEmail = $product->getEmail();
if(!empty($productEmail) || !is_null($to)){
// obter e-mails de lead da imobiliária da vez
$realEstateLeadEmails = $this->getDoctrine()
->getRepository('ApplicationInternitLeadBundle:RealEstateEmail')
->findRealEstateLeadEmails($to['imob']);
$realEstate = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findOneBy(['name' => $to['imob']]);
//Chamar service de disparo para corretor
$email1 = $this->get('admin.mail.service');
//$email2 = $this->get('admin.mail.service');
// EMAILS COPY
$emailCopySend = [];
if($realEstate){
if($realEstate->getReceiveLead()){
$emailCopySend[] = $realEstate->getEmail();
//$email->setMessage()->setBCC($realEstate->getEmail());
}
}
if ( ! empty($productEmail) ) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail){
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
}
// se houver o e-mail do corretor, ele é o destinatário principal e
// o e-mail padrão da campanha é cópia oculta
if ( !empty($to['email']) ) {
$email1->setMessage()->setTo($to['email']);
//dd($realEstate);
if(!empty($emailCopySend)){
$email1->setMessage()->setCC($emailCopySend);
}
}
// se não houver nenhum corretor para receber e-mail, o e-mail padrão
// da campanha é o destinatário principal
else if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail){
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
$email1->setMessage()->setTo($emailsSend);
if(!empty($emailCopySend)){
$email1->setMessage()->setCC($emailCopySend);
}
}
// if (!empty($realEstateLeadEmails)) {
// $email->setMessage()->setCC($realEstateLeadEmails);
// }
$newLead->setBrokerEmail( ! empty($to['email']) ? $to['email'] : $productEmail ); //Seta email do corretor que recebeu o lead
$newLead->setBrokerRealState($to['imob']); //Seta Imobiliaria do corretor que recebeu o lead
$extraInfo['broker_name'] = $to['name'];
//if($to['phone'])
// $extraInfo['broker_phone'] = preg_replace('/[^0-9]/', '', $to['phone']);
$extraInfo['realstate_name'] = $to['imob']; //strtoupper()
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($newLead);
$entityManager->flush();
$email1
->setMessage()
->setSubject("[leadcalper] ".$product->getName() . ' - ' . $newLead->getGroup() . ' - ' . $to['name'])
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
'corretor' => $to['name'],
)), 'text/html');
$email1->send();
/* $email2
->setMessage()
->setSubject("[Lead] ".$product->getName() . ' - ' . $newLead->getGroup())
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
)), 'text/html');
$email2->send();*/
}
// dump($newLead);
return $this->sendStatus(200,"Lead created", $extraInfo);
}
else{
return $this->sendStatus(400,"Invalid content");
}
}
return $this->sendStatus(400,"Token is required");
}
public function sendLast(Request $request)
{
$data = json_decode($request->getContent());
$statusCode=400;
$result=[];
if(!$data)
return $this->sendStatus(400,"New Lead is not valid");
if(isset($data->token)){
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->findOneByToken($data->token);
if(!$product)
return $this->sendStatus(404,"Product not found");
if(!empty($data->name) &&
!empty($data->origem) &&
!empty($data->group)
){
// form de whatsapp não traz e-mail
$emailLead = isset($data->email) ? $data->email : '';
$extraInfo = array();
$to = $this->get('tupi.caster.service')->next($product, $emailLead);
//dd($to);
// dump($to);exit;
$newLead = new Lead();
//Obrigatórios
$newLead->setName($data->name);
$newLead->setGroup($data->group);
$newLead->setOrigem($data->origem);
$newLead->setProduct($product);
$newLead->setEmail($emailLead);
$newLead->setPhone(isset($data->phone) ? $data->phone : '');
//Opcionais
if(isset($data->fixedPhone)) {
$newLead->setFixedPhone(($data->fixedPhone ? $data->fixedPhone : ''));
}
if(isset($data->empreendimento))
$newLead->setEmpreendimento(($data->empreendimento ? $data->empreendimento : ''));
if(isset($data->utm_source))
$newLead->setUtm_source(($data->utm_source ? $data->utm_source : ''));
if(isset($data->utm_medium))
$newLead->setUtm_medium(($data->utm_medium ? $data->utm_medium : ''));
if(isset($data->utm_campaign))
$newLead->setUtm_campaign(($data->utm_campaign ? $data->utm_campaign : ''));
if(isset($data->message))
$newLead->setMessage(($data->message ? $data->message : ''));
// e-mail que a construtora configura para receber os leads deste produto.
$productEmail = $product->getEmail();
if(!empty($productEmail) || !is_null($to)){
// obter e-mails de lead da imobiliária da vez
$realEstateLeadEmails = $this->getDoctrine()
->getRepository('ApplicationInternitLeadBundle:RealEstateEmail')
->findRealEstateLeadEmails($to['imob']);
$realEstate = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findOneBy(['name' => $to['imob']]);
//Chamar service de disparo para corretor
$email1 = $this->get('admin.mail.service');
$email2 = $this->get('admin.mail.service');
// EMAILS COPY
$emailCopySend = [];
if($realEstate){
if($realEstate->getReceiveLead()){
$emailCopySend[] = $realEstate->getEmail();
//$email->setMessage()->setBCC($realEstate->getEmail());
}
}
if ( ! empty($productEmail) ) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail){
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
}
// se houver o e-mail do corretor, ele é o destinatário principal e
// o e-mail padrão da campanha é cópia oculta
if ( !empty($to['email']) ) {
$email1->setMessage()->setTo($to['email']);
//dd($realEstate);
if(!empty($emailCopySend)){
$email2->setMessage()->setTo($emailCopySend);
}
}
// se não houver nenhum corretor para receber e-mail, o e-mail padrão
// da campanha é o destinatário principal
else if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail){
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
$email1->setMessage()->setTo($emailsSend);
if(!empty($emailCopySend)){
$email2->setMessage()->setTo($emailCopySend);
}
}
// if (!empty($realEstateLeadEmails)) {
// $email->setMessage()->setCC($realEstateLeadEmails);
// }
$newLead->setBrokerEmail( ! empty($to['email']) ? $to['email'] : $productEmail ); //Seta email do corretor que recebeu o lead
$newLead->setBrokerRealState($to['imob']); //Seta Imobiliaria do corretor que recebeu o lead
$extraInfo['broker_name'] = $to['name'];
if($to['phone'])
$extraInfo['broker_phone'] = preg_replace('/[^0-9]/', '', $to['phone']);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($newLead);
$entityManager->flush();
$email1
->setMessage()
->setSubject("[Lead] ".$product->getName() . ' - ' . $newLead->getGroup())
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
)), 'text/html');
$email1->send();
$email2
->setMessage()
->setSubject("[Lead] ".$product->getName() . ' - ' . $newLead->getGroup())
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
)), 'text/html');
$email2->send();
}
// dump($newLead);
return $this->sendStatus(200,"Lead created", $extraInfo);
}
else{
return $this->sendStatus(400,"Invalid content");
}
}
return $this->sendStatus(400,"Token is required");
}
private function sendStatus($code = 401, $message = "Requisição não autorizada",$extra = array()){
$array = array('message' => $message);
$array = array_merge($array, $extra);
$response = new Response(json_encode($array), $code);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}