<?php
namespace App\Controller;
use App\Entity\GHGestionTurno;
use App\Entity\GHGrupoTrabajo;
use App\Entity\ParHorario;
use App\Entity\SegHomeOffice;
use App\Form\SegHomeOfficeType;
use App\Repository\SegHomeOfficeRepository;
use DateTimeZone;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use function PHPUnit\Framework\matches;
use Dompdf\Dompdf;
#[Route('/seg/home/office')]
class SegHomeOfficeController extends AbstractController {
private $code = 0;
private $msj = "";
private $url = "";
private $html = "";
private $em = null;
private $documentHandler = null;
private $mailerCore = null;
private $entityManager;
private $token;
public function __construct(\App\Services\DocumentHandler $documentHandler, \App\Services\MailerCore $mailerCore, \Doctrine\ORM\EntityManagerInterface $entityManager, Security $token) {
$this->em = $entityManager;
$this->mailerCore = $mailerCore;
$this->documentHandler = $documentHandler;
$this->entityManager = $entityManager;
$this->token = $token;
}
#[Route('/', name: 'app_seg_home_office_index', methods: ['GET'])]
public function index(SegHomeOfficeRepository $segHomeOfficeRepository): Response {
$entities = $segHomeOfficeRepository->getAllDia($this->getUser()->getPersona()->getId(), date('Y-m-d'));
return $this->render('seg_home_office/index.html.twig', [
'entities' => $entities,
]);
}
#[Route('/panel_control', name: 'app_seg_home_office_panel_control', methods: ['GET'])]
public function panelControl(SegHomeOfficeRepository $segHomeOfficeRepository): Response {
$entities = $segHomeOfficeRepository->getUsuarioProceso($this->getUser()->getPersona()->getId(), date('Y-m-d'));
return $this->render('seg_home_office/panelControl.html.twig', [
'entities' => $entities,
]);
}
#[Route('/panel_control/historicoGrupo', name: 'app_seg_home_office_panel_control_historico_grupo', methods: ['GET'])]
public function panelControlHistoricoGrupo(SegHomeOfficeRepository $segHomeOfficeRepository): Response {
$idGrupos = [];
foreach ($this->getUser()->getPersona()->getGrupoTrabajoJefe() as $grupo) {
$idGrupos[] = $grupo->getId();
}
// Consulta solo si hay al menos un grupo asociado
$entities = !empty($idGrupos)
? $segHomeOfficeRepository->getHistoricoGrupo(date('Y-m-d'), $idGrupos)
: [];
return $this->render('seg_home_office/panelControlHistorico.html.twig', [
'entities' => $entities,
]);
}
function evaluarDiaConexion(GHGestionTurno $turno, SegHomeOffice $registro, \DateTimeInterface $fecha): void
{
$dia = (int) $fecha->format('N'); // 1 = Lunes, ..., 6 = Sábado, 7 = Domingo (que no usas)
$tieneTurno = match ($dia) {
1 => (bool) $turno->isLunes(),
2 => (bool) $turno->isMartes(),
3 => (bool) $turno->isMiercoles(),
4 => (bool) $turno->isJueves(),
5 => (bool) $turno->isViernes(),
6 => (bool) $turno->isSabado(),
default => false,
};
if ($dia >= 1 && $dia <= 6) {
if ($tieneTurno) {
$registro->setDiaConexion('OK');
} else {
$registro->setDiaConexion('DIA SIN H.O');
}
}
}
#[Route('/new', name: 'app_seg_home_office_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response {
$homeOfice = $this->em->getRepository(SegHomeOffice::class)->findOneBy(['usuario' => $this->getUser()->getPersona()->getId(), 'finConexion' => null]);
$personaConGrupo = $this->em->getRepository(GHGrupoTrabajo::class)->findByColaboradorId($this->getUser()->getPersona()->getId());
$personaConTurno = $this->em->getRepository(GHGestionTurno::class)->findOneBy(['colaborador' => $this->getUser()->getPersona()->getId()]);
$cerrarSesionJs = $request->query->get('cerrarSesionJs');
//si la persona no tiene grupo cierra la sesion despues de 10 min
if (!$personaConGrupo){
if ($cerrarSesionJs === '1') {
return $this->redirectToRoute('app_logout');
}else{
$this->addFlash('danger', 'No tienes un grupo asignado, por favor contacta a tu jefe de grupo.');;
return $this->redirectToRoute('app_seg_home_office_index');
}
}
//ahora si la persona si tiene un grupo pero no un turno cierrre la sesion despues de 10 min
$fecha = new \DateTime('now', new DateTimeZone('America/Bogota'));
$dia = (int) $fecha->format('N');
$tieneTurno = match ($dia) {
1 => (bool) $personaConTurno->isLunes(),
2 => (bool) $personaConTurno->isMartes(),
3 => (bool) $personaConTurno->isMiercoles(),
4 => (bool) $personaConTurno->isJueves(),
5 => (bool) $personaConTurno->isViernes(),
6 => (bool) $personaConTurno->isSabado(),
default => false,
};
if ($dia >= 1 && $dia <= 6 && !$tieneTurno) {
if ($cerrarSesionJs === '1') {
return $this->redirectToRoute('app_logout');
}else{
$this->addFlash('danger', 'No tienes turno el dia de hoy, por favor contacta a tu jefe de grupo.');
return $this->redirectToRoute('app_seg_home_office_index');
}
}
//ahora si si tengo un grupo y un turno
else {
$session = $request->getSession();
//si ya me loguee con mi turno del dia y pasan 10 min me cierra el home office y me saca del sistema
if ($homeOfice !== null && !$session->get('home_office_closed')) {
$homeOfice->setFinConexion(new \DateTime('now', new DateTimeZone('America/Bogota')));
$homeOfice->setTipoDesconexion(2);
$homeOfice->setDiaConexion(null);
$homeOfice->setNotificado(false);
$inicioConexion = $homeOfice->getInicioConexion();
$finConexion = $homeOfice->getFinConexion();
$totalTiempo = $inicioConexion->diff($finConexion);
$homeOfice->setTiempoTotal($totalTiempo->format('%H:%i:%s'));
$entityManager->persist($homeOfice);
$entityManager->flush();
$session->set('home_office_closed', true); // Evita redirección repetida
$this->addFlash('success', 'Conexión finalizada correctamente');
if ($cerrarSesionJs === '1') {
return $this->redirectToRoute('app_logout');
} else {
return $this->redirectToRoute('app_seg_home_office_index');
}
}
$session->remove('home_office_closed');
$intervalo = rand(30, 60);
$segHomeOffice = new SegHomeOffice();
$currentDateTime = new \DateTime('now', new DateTimeZone('America/Bogota'));
$this->evaluarDiaConexion($personaConTurno, $segHomeOffice, new \DateTime('now', new \DateTimeZone('America/Bogota')));
if ($cerrarSesionJs === '1') {
return $this->redirectToRoute('app_logout');
}else{
$segHomeOffice
->setUsuario($this->getUser()->getPersona())
->setCreateAt($currentDateTime)
->setCreateUser($this->getUser()->getUsername())
->setUpdateAt($currentDateTime)
->setUpdateUser($this->getUser()->getUsername())
->setInicioConexion($currentDateTime)
->sethorario($entityManager->getRepository(ParHorario::class)->find(4))
->setIntervalo($intervalo)
->setNotificado(false);
$entityManager->persist($segHomeOffice);
$entityManager->flush();
}
}
$this->addFlash('success', 'Conexión creada correctamente');
return $this->redirectToRoute('app_seg_home_office_index');
}
#[Route('/validar_conexion', name: 'app_seg_home_office_validar_conexion', methods: ['POST'])]
public function validarConexion(Request $request): JsonResponse
{
$res = ['tipo' => null];
// Obtenemos conexiones activas para hoy
$valHomeOfice = $this->em
->getRepository(SegHomeOffice::class)
->getConexionAct($this->getUser()->getPersona()->getId(), date('Y-m-d'));
if (count($valHomeOfice) > 0) {
$homeOfice = $this->em
->getRepository(SegHomeOffice::class)
->findOneBy([
'usuario' => $this->getUser()->getPersona()->getId(),
'finConexion' => null,
]);
if ($homeOfice) {
$intervalo = (int) $homeOfice->getIntervalo();
$fechaBase = clone $homeOfice->getUpdateAt();
if ($intervalo > 0) {
$dif = $fechaBase->add(
new \DateInterval(sprintf('PT%dM', $intervalo))
);
} else {
$dif = $fechaBase;
}
$ahora = new \DateTime('now', new \DateTimeZone('America/Bogota'));
$tiempoDiff = $dif->diff($ahora);
if ($dif >= $ahora || $tiempoDiff->i <= 10) {
$res['tipo'] = 'activo';
$res['inter'] = $intervalo;
$res['validar'] = false;
} else {
$homeOfice->setFinConexion($ahora);
$homeOfice->setTipoDesconexion(1);
$this->em->persist($homeOfice);
$this->em->flush();
$res['validar'] = true;
$res['msj'] = 'desconectado';
}
} else {
$res['tipo'] = 'desconectado';
}
} else {
$res['tipo'] = 'NA';
}
return new JsonResponse($res);
}
#[Route('/gestionar', name: 'app_seg_home_office_gestionar', methods: ['GET'])]
public function gestionar(Request $request): Response {
$homeOfice = $this->em->getRepository(SegHomeOffice::class)->findOneBy(['usuario' => $this->getUser()->getPersona()->getId(), 'finConexion' => null]);
$res = [];
if ($homeOfice) {
$homeOfice->setUpdateAt(new \DateTime('now'));
$res['msj'] = 'Conexion actualizada';
$this->em->persist($homeOfice);
$this->em->flush();
} else {
$res['msj'] = 'Imposible continuar no hay registro de conexion';
}
return new Response(json_encode($res));
}
#[Route('/detalle/30_dias/{id}', name: 'app_seg_home_office_detalle')]
public function historicoDetalle(SegHomeOffice $homeOffice, SegHomeOfficeRepository $repo): Response
{
$idPersona = $homeOffice->getUsuario()->getId();
$referencia = $homeOffice->getUsuario()->getNombres();
$historico = $repo->getHistoricoDias([$idPersona], 30);
return $this->render('seg_home_office/detalle.html.twig', [
'historico' => $historico,
'referencia' => $referencia,
]);
}
#[Route('/detalle_reporte/30_dias/{id}', name: 'app_seg_home_office_reporte')]
public function ReporteDetalle(SegHomeOffice $homeOffice, SegHomeOfficeRepository $repo): Response
{
$idPersona = $homeOffice->getUsuario()->getId();
$historico = $repo->getHistoricoDias([$idPersona], 30);
$path = $this->getParameter('kernel.project_dir') . '/public_html/assets/img/brand/logos-empresas.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$rutaLogo = $base64;
$html = $this->renderView('formatos/historicoConexiones.html.twig', ['logo' => $rutaLogo, 'historico' => $historico]);
$dompdf = new Dompdf();
//$customPaper = array(0, 0, 220, 130);
//$dompdf->setPaper($customPaper);
$dompdf->loadHtml($html);
$dompdf->render();
return new Response(
$dompdf->stream('resume', ["Attachment" => false]),
Response::HTTP_OK,
['Content-Type' => 'application/pdf']
);
}
public function notificacionHomeOfficeDesconexion()
{
$ultimoRegistro = $this->entityManager->getRepository(SegHomeOffice::class)->ultiomoRegistroUsuario();
$ahora = new \DateTime('now', new \DateTimeZone('America/Bogota'));
$diaSemana = (int) $ahora->format('N'); // 1 = Lunes, ..., 7 = Domingo
// Solo de lunes a sábado
if ($diaSemana >= 1 && $diaSemana <= 6) {
foreach ($ultimoRegistro as $homeOfficePersona) {
$horario = $homeOfficePersona->getHorario();
$horaDesconexion = $homeOfficePersona->getFinConexion();
$notficado = $homeOfficePersona->isNotificado();
if (!$horario || !$horaDesconexion || $homeOfficePersona->getDiaConexion() !== null) {
continue;
}
// Crear las fechas de hoy con las horas del horario
$inicioJornada = \DateTime::createFromFormat(
'Y-m-d H:i:s',
$ahora->format('Y-m-d') . ' ' . $horario->getHoraInicio(),
new \DateTimeZone('America/Bogota')
);
$finJornada = \DateTime::createFromFormat(
'Y-m-d H:i:s',
$ahora->format('Y-m-d') . ' ' . $horario->getHoraFin(),
new \DateTimeZone('America/Bogota')
);
if ($ahora >= $inicioJornada && $ahora <= $finJornada) {
$diferencia = $horaDesconexion->diff($ahora);
$minutosPasados = ($diferencia->days * 24 * 60) + ($diferencia->h * 60) + $diferencia->i;
if ($minutosPasados >= 120 && !$notficado) {
$this->mailerCore->HomeOffice('notificarDesconexionJefe', [$homeOfficePersona]);
$homeOfficePersona->setNotificado(true);
$this->entityManager->persist($homeOfficePersona);
}
}
}
$this->entityManager->flush();
}
}
}