<?php
namespace App\Controller\Admin;
use App\Entity\Imoveis;
use App\Form\ClientType;
use App\Form\VistoryType;
use App\Service\AlogliaHelper;
use App\Service\MailService;
use App\Utils\Slugger;
use Dompdf\Dompdf;
use Dompdf\Options;
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\Mime\NamedAddress;
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;
/**
* @Route("/admin/clientes/vistoria")
* @IsGranted("ROLE_ADMIN" ,"ROLE_OPERATOR")
*/
class VistoriaController extends AbstractController
{
protected $urlHelper;
public $algoliaIndex;
public function __construct(UrlHelper $urlHelper, MailService $mailer)
{
$this->urlHelper = $urlHelper;
$this->mailer = $mailer;
$algolia = new AlogliaHelper();
$this->algoliaIndex = $algolia->client->initIndex('vistorias');
}
/**
* @Route("/lista/{id}", methods={"GET"}, name="admin_vistoria_list")
*/
public function list_vistoria($id)
{
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($id);
$cliente = $imovel;
$vistorias = $this->algoliaIndex->search('',[
'facetFilters' => [
"client_id:".$id,
],
'hitsPerPage' => 1000
])['hits'];
return $this->render('admin/vistoria/edit.html.twig', [
'cliente' => $cliente,
'vistorias' => $vistorias
]);
}
/**
* @Route("/novo/{id}", methods={"GET","POST"}, name="admin_vistoria_new")
*/
public function new_vistoria(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($id);
$cliente = $imovel;
$form = $this->createForm(VistoryType::class, []);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$vistoria = $request->request->all()['vistory'];
unset($vistoria['_token']);
$vistoria['client_id'] = $id;
$vistoria['checkin'] = \DateTime::createFromFormat('d/m/Y H:i', $vistoria['checkin'])->format('Y-m-d H:i');
$vistoria['checkout'] = \DateTime::createFromFormat('d/m/Y H:i', $vistoria['checkout'])->format('Y-m-d H:i');
$this->algoliaIndex->saveObjects([$vistoria],['autoGenerateObjectIDIfNotExist' => true])->wait();
$this->addFlash('success', 'Registro incluído com sucesso!');
return $this->redirectToRoute('admin_vistoria_list',['id' => $id]);
}
return $this->render('admin/vistoria/new.html.twig', [
'form' => $form->createView(),
'cliente' => $cliente
]);
}
/**
* @Route("/editar/{id}", methods={"GET","POST"}, name="admin_vistoria_edit")
*/
public function edit_vistoria(Request $request, $id)
{
$algolia = self::getChecklist($id);
$vistory = $algolia['data'];
$vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkin'])->format('d/m/Y H:i');
$vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkout'])->format('d/m/Y H:i');
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
$cliente = $imovel;
$form = $this->createForm(VistoryType::class, $vistory);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$vistoria = $request->request->all()['vistory'];
unset($vistoria['_token']);
$vistoria['checkin'] = \DateTime::createFromFormat('d/m/Y H:i', $vistoria['checkin'])->format('Y-m-d H:i');
$vistoria['checkout'] = \DateTime::createFromFormat('d/m/Y H:i', $vistoria['checkout'])->format('Y-m-d H:i');
$this->algoliaIndex->saveObjects([$vistoria],['autoGenerateObjectIDIfNotExist' => true])->wait();
$this->addFlash('success', 'Alteração realizada com sucesso!');
return $this->redirectToRoute('admin_vistoria_list',['id' => $vistory['client_id']]);
}
return $this->render('admin/vistoria/new.html.twig', [
'form' => $form->createView(),
'cliente' => $cliente,
'edit' => true
]);
}
/**
* @Route("/checkin/{id}", methods={"GET","POST"}, name="admin_vistoria_checkin")
*/
public function checkin_vistoria(Request $request, $id)
{
$algolia = self::getChecklist($id);
$vistory = $algolia['data'];
$vistoryOriginal = $vistory;
$vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkin'])->format('d/m/Y H:i');
$vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkout'])->format('d/m/Y H:i');
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
$cliente = $imovel;
$vistoriaData = $request->request->all();
$updated=false;
if($vistoriaData){
$vistoryOriginal['vistoria_checkin'] = $vistoriaData['dados'];
$date = new \DateTime();
$vistoryOriginal['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
$vistoryOriginal['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
unset($vistoryOriginal['_highlightResult']);
$vistory['vistoria_checkin'] = $vistoriaData['dados'];
$vistory['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
$vistory['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
$this->algoliaIndex->saveObjects([$vistoryOriginal]);
$this->addFlash('success', 'Alteração realizada com sucesso!');
$updated=true;
}
$checkin_itens=[];
foreach ($vistory['vistoria_checkin'] as $cat=>$sub) {
foreach ($sub as $subCat=>$item) {
if ($item['condicao'] || $item['observacoes'] || $item['fotos']) {
$item['fotos'] = $item['fotos'] ? explode(',', $item['fotos']) : [];
$checkin_itens[$cat][$subCat] = $item;
}
}
}
return $this->render('admin/vistoria/checkin.html.twig', [
'cliente' => $cliente,
'vistory' => $vistory,
'itens_checked' => $checkin_itens,
'itens_check' => self::getConferenceCheckin(),
'updated' => $updated
]);
}
/**
* @Route("/checkout/{id}", methods={"GET","POST"}, name="admin_vistoria_checkout")
*/
public function checkout_vistoria(Request $request, $id)
{
$algolia = self::getChecklist($id);
$vistory = $algolia['data'];
$vistoryOriginal = $vistory;
$vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkin'])->format('d/m/Y H:i');
$vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkout'])->format('d/m/Y H:i');
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
$cliente = $imovel;
$updated=false;
$vistoriaData = $request->request->all();
if($vistoriaData){
$vistoryOriginal['vistoria_checkout'] = $vistoriaData['dados'];
unset($vistoryOriginal['_highlightResult']);
$date = new \DateTime();
$vistory['vistoria_checkout'] = $vistoriaData['dados'];
$vistory['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
$vistory['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
$vistoryOriginal['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
$vistoryOriginal['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
$this->algoliaIndex->saveObjects([$vistoryOriginal]);
$this->addFlash('success', 'Alteração realizada com sucesso!');
$updated=true;
}
$checkout_itens=[];
foreach ($vistory['vistoria_checkout'] as $cat=>$sub) {
foreach ($sub as $subCat=>$item) {
if ($item['condicao'] || $item['observacoes'] || $item['fotos']) {
$item['fotos'] = $item['fotos'] ? explode(',', $item['fotos']) : [];
$checkout_itens[$cat][$subCat] = $item;
}
}
}
return $this->render('admin/vistoria/checkout.html.twig', [
'cliente' => $cliente,
'vistory' => $vistory,
'itens_checked' => $checkout_itens,
'itens_check' => self::getConferenceCheckout(),
'updated' => $updated
]);
}
protected function generate_pdf($type,$id,$with_fotos=1,$output='browser'){
ini_set('memory_limit',-1);
ini_set('max_execution_time',-1);
$algolia = self::getChecklist($id);
$vistory = $algolia['data'];
$vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkin'])->format('d/m/Y H:i');
$vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkout'])->format('d/m/Y H:i');
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
$cliente = $imovel;
$checkin_itens=[];
$loop = $type=='check-in'? 'vistoria_checkin': 'vistoria_checkout';
foreach ($vistory[$loop] as $cat=>$sub) {
foreach ($sub as $subCat=>$item) {
if ($item['condicao'] || $item['observacoes'] || $item['fotos']) {
$item['fotos'] = $item['fotos'] ? explode(',', $item['fotos']) : [];
$checkin_itens[$cat][$subCat] = $item;
}
}
}
$vistory['vistoria_itens'] = $checkin_itens;
unset($vistory['_highlightResult']);
$pdfOptions = new Options();
$pdfOptions->setIsRemoteEnabled(true);
$dompdf = new Dompdf($pdfOptions);
if($_GET['html']){
return $this->render('admin/vistoria/pdf.html.twig', [
'cliente' => $cliente,
'edited' => $vistory,
'type' => $type,
'com_fotos' => $with_fotos
]);
}
$html = $this->renderView('admin/vistoria/pdf.html.twig', [
'cliente' => $cliente,
'edited' => $vistory,
'type' => $type,
'com_fotos' => $with_fotos
]);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
if($output=='browser') {
return $dompdf->stream($type . "_" . $id . ".pdf", [
"Attachment" => false
]);
}
if($output=='file'){
$file_path = "/tmp/".$type."_".$id.".pdf";
$file_output = $dompdf->output();
file_put_contents($file_path, $file_output);
return $file_path;
}
}
/**
* @Route("/comunica-email/{type}/{id}", methods={"GET"}, name="admin_vistoria_email")
*/
public function pdf_email($type,$id)
{
$with_photos = 1; // gera sempre com fotos para enviar no e-mail
$algolia = self::getChecklist($id);
$vistory = $algolia['data'];
$vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkin'])->format('d/m/Y');
$vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i', $vistory['checkout'])->format('d/m/Y');
$em = $this->getDoctrine()->getManager();
$imovel = $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
$cliente = $imovel;
$cliente['data_evento'] = $vistory[str_replace('-','',$type)];
$pdf_path =$this->generate_pdf($type,$id,$with_photos,'file');
$error=false;
try{
$this->send_mail($cliente,$type,$pdf_path);
}
catch (\Exception $e){
$error=true;
}
return new JsonResponse(['error'=>$error]);
}
/**
* @Route("/pdf/{type}/{id}", methods={"GET"}, name="admin_vistoria_pdf")
*/
public function pdf($type, $id){
return $this->generate_pdf($type,$id,$_GET['com_fotos']);
}
protected function send_mail($cliente, $type, $pdf_path)
{
$message = '<style>
@import url(\'https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap\');
</style>
<table style="width: 500px; text-align: center; font-family: \'Roboto\', sans-serif;">
<tr>
<td style="height: 100px; background: linear-gradient(188.93deg, #FFFFFF 0%, #E2DFFF 0.01%, #FFFFFF 105.25%);">
<img src="https://admin.bnbguests.com.br/imgs/logo-email.png">
</td>
</tr>
<tr>
<td style="padding-top: 20px; text-align: left;">
<p>Olá, '.$cliente['nome'].'.</p>
<p>Atualizamos as informações de '.$type.' ('.$cliente['data_evento'].') do seu imóvel em '.$cliente['endereco'].'.</p>
<p>Segue anexo para conhecimento.</p>
<p>Att,<br>Equipe bnbguests</p>
<p style="color: #cccccc"><i>*Não responda este e-mail*</i></p>
</td>
</tr>
</table>';
$cc = ['suporte@bnbguests.com.br'];
$this->mailer->sendMail($cliente['email'],"Atualização de $type - bnbguests",$message,$cc,$pdf_path);
}
public static function getConferenceCheckin(){
return[
'QUARTOS E SALAS' => [
"Limpeza piso",
"Limpeza Janelas/portas",
"Bancadas e pia",
"Papel higiênico",
"Limpeza de Piso e de Ralo",
"Espelho e box",
],
'COZINHA' => [
"Geladeira",
"Microondas",
"Fogão",
"Bancadas e pisos",
"Móveis",
"Eletrodomésticos",
"Limpeza (detergente, bucha, pano de prato e pano de pia)",
"Alimentos básicos (café, sal, açucar, óleo)",
],
"FUNCIONAMENTO" => [
"Ar condicionado",
"Internet",
"Piscina (aquecimento, limpeza, etc)",
],
"HOTELARIA" => [
"Toalhas- dobrar como hotel",
"Toalhas- 1 toalha de banho por hóspede",
"Toalhas- 1 toalha de rosto por banheiro",
"Roupa de cama- verificar se tem manchas ou sujo",
"Tapete de banheiro- 1 por banheiro",
"Ligar gás aquecimento chuveiro",
"Chocolate de boas vindas + recado",
],
"OUTROS" => [
"Qualaquer área que não esteja pré-definida"
]
];
}
public static function getConferenceCheckout(){
return[
"GERAL" => [
"Objetos esquecidos pelo hóspede",
"Objeto quebrado",
"Eletrodomésticos e utensílios de cozinha",
"Controles de TV",
"Controles de ar condicionado",
"Toalhas ",
"Roupas de cama ",
"Secador de cabelo",
"Som",
"Objetos de decoração",
"Gás (botijão cheio)",
"Capas de colchão e de travesseiro (se estiver suja, tirar pra lavar)",
"Ligar e desligar (luzes, cafeteira, ar condicionado, tv, geladeira, microondas)",
"Recolher móveis da área externa (redes, almofadas, móveis) ",
"Conferir internet",
"Outros"
]
];
}
/**
* @Route("/nova-foto", methods={"POST"}, name="admin_vistoria_nova_foto")
*/
public function upload_image(Request $request){
try {
$file = $request->files->get('file');
/** @var $file UploadedFile */
$id = $request->request->get('id');
$dir = __DIR__ . '/../../../public/uploads/vistoria/' . $id . '/';
$newName = time() . '_' . $file->getClientOriginalName();
if ($file->move($dir, $newName)) {
return new JsonResponse([
'url' => $this->urlHelper->getAbsoluteUrl(
$this->generateUrl('fotos', [
'indice' => 'vistoria',
'object_id' => $id,
'foto' => $newName
])
)
]);
}
}
catch(\Exception $e){
return new JsonResponse([
'error' => $e->getMessage()
]);
}
}
public static function getChecklist($id){
$algolia = new AlogliaHelper();
$index = $algolia->client->initIndex('vistorias');
$data = $index->search('',[
'facetFilters' => [
"objectID:".$id,
],
'hitsPerPage' => 1
]);
return [
'index' => $index,
'data' => $data['hits'][0]
];
}
}