<?php
namespace App\Controller\Admin;
use App\Entity\Imoveis;
use App\Form\ClientType;
use App\Repository\ImoveisRepository;
use App\Service\AlogliaHelper;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\UrlHelper;
use Symfony\Component\Mime\Address;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use ZipStream\File;
use App\Entity\HistoryClientComissions;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service_locator;
/**
* @Route("/admin/clientes")
* @IsGranted("ROLE_ADMIN" ,"ROLE_OPERATOR")
*/
class ClientesController extends AbstractController
{
public function __construct(UrlHelper $urlHelper, ImoveisRepository $imoveisRepository)
{
$this->urlHelper = $urlHelper;
$this->ImoveisRepository = $imoveisRepository;
}
/**
* @Route("/bitrix", methods={"GET"}, name="admin_clientes_bitrix")
*/
public function clientesBitrix(){
ini_set('memory_limit',-1);
ini_set('max_execution_time',-1);
$connection = $this->getDoctrine()->getConnection();
// $sql ="SELECT cod_stays, nome, email, cpf, celular, plano FROM `imoveis` WHERE cpf not in('000.000.000-00','') and (email <> '' or celular<>'')";
$sql ="SELECT cod_stays, nome, email, cpf, celular, plano FROM `imoveis` WHERE plano > 0";
$clientes = $connection->executeQuery($sql)->fetchAll();
$this->curl = curl_init();
$continue = true; $i=0;
foreach ($clientes as $cliente) {
$idContatct = false; //$this->bitrixGetContact($cliente);
//dump("ID contato: ".$idContatct);
dump($cliente);
$this->bitrixGetImovel($cliente,$idContatct);
$i++;
if($i%15==0)
sleep(2);
}
curl_close($this->curl);
die;
}
protected function bitrixGetImovel($cliente, $cod_contact){
$cod_stays = $cliente['cod_stays'];
$filter['filter']['STAGE_ID'] = 'C28:NEW';
$filter['filter']['UF_CRM_1663851986'] = $cod_stays;
$url = 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.deal.list?'.http_build_query($filter);
curl_setopt_array($this->curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($this->curl);
$result = json_decode($response,true);
if($result['total']==0)
return false;
else {
$id = $result['result'][0]['ID'];
if($cod_contact)
$fields['fields']['CONTACT_ID'] = $cod_contact;
$fields['fields']['UF_CRM_1648061516'] = $cliente['plano'];
dump("ID imovel: ".$id);
$url = 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.deal.update?ID=' . $id . '&' . http_build_query($fields);
dump($url);
curl_setopt_array($this->curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($this->curl);
$result = json_decode($response, true);
dump($result);
}
}
protected function bitrixGetContact($cliente){
$phone = $cliente['celular'];
$name = $cliente['nome'];
$email = $cliente['email'];
$filter['filter']['PHONE'] = $phone;
$fields['fields']['TYPE_ID'] = 'CLIENT';
$fields['fields']['NAME'] = $name;
$fields['fields']['PHONE'][0]['VALUE'] = $phone;
$fields['fields']['PHONE'][0]['VALUE_TYPE'] = 'MOBILE';
$fields['fields']['EMAIL'][0]['VALUE'] = $email;
$fields['fields']['EMAIL'][0]['VALUE_TYPE'] = 'WORK';
$fields['fields']['UF_CRM_1646672583'] = preg_replace("/[^0-9]/", "", $cliente['cpf'] );
$url = 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.contact.list?'.http_build_query($filter);
curl_setopt_array($this->curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($this->curl);
$result = json_decode($response,true);
dump($result);
if($result['total']==0 || !$result){
$url = 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.contact.add/?'.http_build_query($fields);
dump($url);
curl_setopt_array($this->curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($this->curl);
$result2 = json_decode($response,true);
dump('insert');
dump($result2);
return $result2['result'];
}
else{
return $result['result'][0]['ID'];
}
}
/**
* @Route("/lista", methods={"GET"}, name="admin_clientes_lista")
*/
public function lista_clientes()
{
$status=$_GET['status']=='ativos' || !$_GET['status']? 1: 0;
$em = $this->getDoctrine()->getManager();
$imoveis = $em->getRepository(Imoveis::class)->findAlltoArray(['status'=>$status]);
return $this->render('admin/lista_clientes.html.twig', [
'data' => $imoveis,
'status' =>$status
]);
}
/**
* @Route("/migrate_mysql", methods={"GET"}, name="admin_clientes_migrate")
*/
public function migrate_clientes(EntityManagerInterface $em, Connection $connection)
{
die;
$algolia = new AlogliaHelper();
$index = $algolia->client->initIndex('clientes');
$data = $index->search('',[
'hitsPerPage' => 1000,
]);
foreach($data['hits'] as $row){
$imovel = new Imoveis();
$imovel->setObjectID($row['objectID']);
$imovel->setEmail(trim($row['email']));
$imovel->setNome(trim($row['nome']));
$imovel->setCelular(trim($row['celular']));
$imovel->setCidade(trim($row['praia']));
$imovel->setEndereco(trim($row['endereco']));
$imovel->setContrato($row['contrato']);
$imovel->setCpf($row['cpf']);
$imovel->setCodStays($row['cod_stays']);
$imovel->setPlano($row['plano']);
$imovel->setAviso($row['aviso']);
$em->persist($imovel);
$em->flush();
}
$connection->executeQuery('UPDATE imoveis AS U1, imoveis AS U2 SET U1.id = U2.object_id WHERE U2.id = U1.id');
die;
}
/**
* @Route("/migrate_invenstario", methods={"GET"}, name="admin_inventario_migrate")
*/
public function migrate_inventario(EntityManagerInterface $em, Connection $connection)
{
die;
$em = $this->getDoctrine()->getManager();
$imoveis = $em->getRepository(Imoveis::class)->findAll();
$algolia = new AlogliaHelper();
$inventario = $algolia->client->initIndex('inventarios');
/** @var Imoveis $imovel */
foreach ($imoveis as $imovel){
if($imovel->getObjectID()){
$itens = $inventario->search('',[
'facetFilters' => [
"cliente_id:".$imovel->getObjectID(),
],
'hitsPerPage' => 1
]);
$imovel->setInventario($itens['hits'][0]['images']);
$em->persist($imovel);
$em->flush();
}
}
die('aaaa');
}
/**
* @Route("/editar/{id}", methods={"GET","POST"}, name="admin_clientes_edit")
*/
public function edit_clientes(Request $request, ImoveisRepository $imoveisRepository, $id)
{
$cliente = $imoveisRepository->find($id);
$cliente->setPlano($cliente->getPlano()? $cliente->getPlano(): 0);
$planoOld = $cliente->getPlano();
$form = $this->createForm(ClientType::class, $cliente);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if($planoOld!=$cliente->getPlano()){
$updatePlano=true;
}
$validate = $this->verifyDuplicate($cliente);
if($validate['error']){
$this->addFlash('danger', $validate['message']);
return $this->render('admin/clientes_edit.html.twig', [
'data' => $cliente,
'form' => $form->createView(),
'new' => false
]);
}
if($updatePlano){
$this->updatePlano($cliente);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($cliente);
$entityManager->flush();
$this->addFlash('success', 'Atualização realizada com sucesso!');
return $this->redirectToRoute('admin_clientes_lista');
}
return $this->render('admin/clientes_edit.html.twig', [
'data' => $cliente,
'form' => $form->createView(),
'new' => false
]);
}
protected function updatePlano(Imoveis $cliente){
$history = new HistoryClientComissions();
$history->setListingId($cliente->getCodStays());
$history->setPercentege($cliente->getPlano());
$now = new \DateTime('now', new \DateTimeZone('America/Sao_Paulo'));
$history->setUntilDate($now);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($history);
$entityManager->flush();
}
/**
* @Route("/novo", methods={"GET","POST"}, name="admin_clientes_new")
*/
public function new_clientes(Request $request)
{
$imovel = new Imoveis();
$form = $this->createForm(ClientType::class, $imovel);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$validate = $this->verifyDuplicate($imovel);
if($validate['error']){
$this->addFlash('danger', $validate['message']);
return $this->render('admin/clientes_edit.html.twig', [
'form' => $form->createView(),
'data' => $imovel,
'new' => true
]);
}
$imovel->setStatus(1);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($imovel);
$entityManager->flush();
$this->addFlash('success', 'Registro incluído com sucesso!');
return $this->redirectToRoute('admin_clientes_lista');
}
return $this->render('admin/clientes_edit.html.twig', [
'form' => $form->createView(),
'data' => $imovel,
'new' => true
]);
}
/**
* @Route("contrato_upload", methods={"POST"}, name="admin_clientes_contrato")
*/
public function contrato_upload(Request $request){
$file = $request->files->get('file');
/** @var $file UploadedFile */
$id = $_GET['id'];
$dir = __DIR__.'/../../../web/uploads/clientes/'.$id.'/';
$new_name = time().'.pdf';
if($file->move($dir,$new_name)){
return new JsonResponse([
'url' => $this->urlHelper->getAbsoluteUrl(
$this->generateUrl('admin_clientes_contrato_download',[
'file'=>$new_name,
'cliente_id' => $id,
])
)
]);
}
}
/**
* @Route("contrato_download/{cliente_id}/{file}", methods={"GET"}, name="admin_clientes_contrato_download")
*/
public function contrato_download($cliente_id,$file){
$file_path = __DIR__.'/../../../web/uploads/clientes/'.$cliente_id.'/'.$file;
$file = new \Symfony\Component\HttpFoundation\File\File($file_path);
return $this->file($file);
}
public function verifyDuplicate($client){
$connection = $this->getDoctrine()->getConnection();
$sql ='SELECT id FROM imoveis where cod_stays= "'.$client->getCodStays().'"'.($client->getId()? ' and id <> "'.$client->getId().'"': '');
$vCodStays = $connection->executeQuery($sql)->rowCount();
if($vCodStays>0){
return ['error'=>true, 'message'=>'Esse código stays já está sendo utilizado por outro imóvel.'];
}
// $sql ='SELECT id FROM imoveis where cpf= "'.$client->getCpf().'"'.($client->getId()? ' and id <> "'.$client->getId().'"': '');
// $vCpf = $connection->executeQuery($sql)->rowCount();
//
// if($vCpf>0){
// return ['error'=>true, 'message'=>'Esse CPF já está sendo utilizado por outro imóvel.'];
// }
return ['error'=>false];
}
public static function getClient($id){
die('refazer chamada getClient');
}
}