<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Entity\Usuario;
use App\Entity\Rol;
use App\Entity\Cita;
use App\Entity\CitaHistorico;
use App\Entity\RedsysAPI;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\CitaAceptacion;
use App\Entity\ImagenesAntesCita;
use App\Entity\ImagenesDespuesCita;
use App\Entity\Sobrecostes;
use PHPExcel;
require_once($_SERVER['DOCUMENT_ROOT']."/libs/PHPMailer_5.2.4/class.phpmailer.php");
class CitaController extends AbstractController
{
public function home(Request $request, $loginerror){
$em=$this->getDoctrine()->getManager();
$this->get('session')->getFlashBag()->clear();
if ($loginerror == 1){
$this->get('session')->getFlashBag()->add(
'Error',
'El mail o la clave no son correctos'
);
}
if ($loginerror == 2){
$this->get('session')->getFlashBag()->add(
'Correcto',
'Si su correo esta registrado se le enviará un email de recuperación a su cuenta de correo.'
);
}
if ($loginerror == 4){
$this->get('session')->getFlashBag()->add(
'Correcto',
'Su clave ha sido modificada correctamente. Ahora puede iniciar sesión.'
);
}
if ($loginerror == 5){
$this->get('session')->getFlashBag()->add(
'Correcto',
'Se ha registrado correctamente. Ahora puede iniciar sesión.'
);
}
$token=" ";
if(isset($_GET["token"])){
$token=$_GET["token"];
}
//renderizamos el home
return $this->render('cita/home.html.twig',array(
'loginerror'=>$loginerror,
"token"=>$token
));
}
public function listado(Request $request,$paginaactual){
date_default_timezone_set('Europe/Madrid');
$em=$this->getDoctrine()->getManager();
$usuario_conectado=$this->getUser();
//elimianamos las citas no activas que tengan mas de 10 minutos.
$sql=" delete from cita where TIMESTAMPDIFF(MINUTE,fecha_alta,NOW()) >=60 and (activo = 0 or activo is null)";
$stmt= $em->getConnection()->query($sql);
$tipovehiculos=$em->getRepository("App:Tipovehiculo")->findBy(array("activo"=>1),array('nombre' => 'ASC'));
$talleres=$em->getRepository("App:Taller")->findBy(array("activo"=>1),array('nombre' => 'ASC'));
if($this->getUser()->getIdrol()->getId()==1){
$sql = "select distinct (DATE_FORMAT(fecha,'%d-%m-%Y')) as fecha from cita where activo = 1 order by fecha desc";
$stmt= $em->getConnection()->query($sql);
$fechas=$stmt->fetchAll();
}else{
$sql = "select distinct (DATE_FORMAT(fecha,'%d-%m-%Y')) as fecha from cita where idtaller =".$this->getUser()->getIdtaller()->getId()." and activo = 1 order by fecha desc";
$stmt= $em->getConnection()->query($sql);
$fechas=$stmt->fetchAll();
}
//filtros
$postfecha="";
$postcliente="";
$postmatricula="";
$posttipovehiculo="";
$posttaller="";
$filtros = "";
if($request->isMethod('POST')){
if(isset($_POST["btn_buscar"])){
$paginaactual=1;
}
if($_POST["fecha"]!=""){
$filtros.=" and DATE_FORMAT(c.fecha,'%d-%m-%Y')='".$_POST["fecha"]."'";
}
$postfecha=$_POST["fecha"];
if($_POST["matricula"]!=""){
$filtros.=" and matricula like '%".$_POST["matricula"]."%'";
}
$postmatricula=$_POST["matricula"];
if($_POST["tipo"]!=""){
$filtros.=" and c.idtipovehiculo =".$_POST["tipo"];
}
$posttipovehiculo=$_POST["tipo"];
if(isset($_POST["taller"]) && $_POST["taller"]!=""){
$filtros.=" and c.idtaller = ".$_POST["taller"];
$posttaller=$_POST["taller"];
}
}
//total
$sql = "SELECT count(c.id) as total ";
$sql .= "FROM cita c ";
$sql .= " inner join usuario on usuario.id=c.idusuario ";
$sql .= " inner join taller on taller.id=c.idtaller ";
$sql .= " inner join tipovehiculo on tipovehiculo.id=c.idtipovehiculo ";
$sql .= " inner join subtipovehiculo on subtipovehiculo.id=c.idsubtipovehiculo ";
$sql .= "WHERE c.activo = 1 ";
if($this->getUser()->getIdrol()->getId()==2){
$sql .= " and c.idtaller= ".$this->getUser()->getIdtaller()->getId();
}
if($filtros!=""){
$sql.=$filtros;
}
$stmt= $em->getConnection()->query($sql);
$total=$stmt->fetchAll()[0]['total'];
//usuario paginados de 20 en 20
$sql = "SELECT c.*,taller.nombre as taller, ";
$sql .= " concat(usuario.nombre,' ',usuario.apellidos) as cliente, ";
$sql .= " usuario.telefono, usuario.numagencia, usuario.email, ";
$sql .= " tipovehiculo.nombre as tipo, ";
$sql .= " tipovehiculo.electrico, ";
$sql .= " tipovehiculo.precio, ";
$sql .= " subtipovehiculo.nombre as modelo, ";
$sql .= " subtipovehiculo.color, ";
$sql .= " tiempo ";
$sql .= " from cita c ";
$sql .= " inner join usuario on usuario.id=c.idusuario ";
$sql .= " inner join taller on taller.id=c.idtaller ";
$sql .= " inner join tipovehiculo on tipovehiculo.id=c.idtipovehiculo ";
$sql .= " inner join subtipovehiculo on subtipovehiculo.id=c.idsubtipovehiculo ";
$sql .= "WHERE c.activo = 1 ";
if($this->getUser()->getIdrol()->getId()==2){
$sql .= " and c.idtaller= ".$this->getUser()->getIdtaller()->getId();
}
if($filtros!=""){
$sql.=$filtros;
}
if (($request->isMethod('POST')) && ($_POST["exportar"] == "EXPORTAR")){
$sql .= " ORDER BY taller.nombre, c.fecha ASC";
}else{
$sql .= " ORDER BY c.fecha ASC";
$sql .= " LIMIT ".(($paginaactual-1)*20).", 20";
}
$stmt= $em->getConnection()->query($sql);
$citas=$stmt->fetchAll();
$numpaginas = ceil($total/20);
if (($request->isMethod('POST')) && ($_POST["exportar"] == "EXPORTAR")){
//creación y exportación de los datos.
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("CITAS");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->mergeCells('A1:K1');
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($this->getEstilos()["cabecera"]);
if(isset($_POST["taller"]) && $_POST["taller"]!=""){
$taller=$em->getRepository("App:Taller")->find($_POST["taller"]);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', $taller->getNombre());
}
$derecha=array('alignment' => array(
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_RIGHT
));
$centrado=array('alignment' => array(
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
));
$objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('G2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('H2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('I2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('J2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('K2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('L2')->applyFromArray($this->getEstilos()["cabecera"]);
$objPHPExcel->getActiveSheet()->getStyle('M2')->applyFromArray($this->getEstilos()["cabecera"]);
//Agregamos el ancho de las columnas
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
$objPHPExcel->getActiveSheet()->SetCellValue('A2', "TALLER");
$objPHPExcel->getActiveSheet()->SetCellValue('B2', "FECHA");
$objPHPExcel->getActiveSheet()->SetCellValue('C2', "HORA INICIO");
$objPHPExcel->getActiveSheet()->SetCellValue('D2', "HORA FIN");
$objPHPExcel->getActiveSheet()->SetCellValue('E2', "CLIENTE");
$objPHPExcel->getActiveSheet()->SetCellValue('F2', "NUM AGENCIA");
$objPHPExcel->getActiveSheet()->SetCellValue('G2', "MATRICULA");
$objPHPExcel->getActiveSheet()->SetCellValue('H2', "TELEFONO");
$objPHPExcel->getActiveSheet()->SetCellValue('I2', "EMAIL");
$objPHPExcel->getActiveSheet()->SetCellValue('J2', "TIPO");
$objPHPExcel->getActiveSheet()->SetCellValue('K2', "DURACIÓN");
$objPHPExcel->getActiveSheet()->SetCellValue('L2', "VEHICULO");
$objPHPExcel->getActiveSheet()->SetCellValue('M2', "COLOR");
$objPHPExcel->getActiveSheet()->SetCellValue('N2', "PRECIO");
$contador=2;
foreach($citas as $cita){
$contador++;
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$contador, $cita['taller']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$contador, $cita['fecha']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$contador, $cita['horainicio']);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$contador, $cita['horafin']);
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$contador, $cita['cliente']);
$objPHPExcel->getActiveSheet()->SetCellValue('F'.$contador, $cita['numagencia']);
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$contador, $cita['matricula']);
$objPHPExcel->getActiveSheet()->SetCellValue('H'.$contador, $cita['telefono']);
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$contador, $cita['email']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$contador, $cita['tipo']);
$objPHPExcel->getActiveSheet()->SetCellValue('K'.$contador, $cita['tiempo']);
$objPHPExcel->getActiveSheet()->SetCellValue('L'.$contador, $cita['electrico']?"ELÉCTRICO":"COMBUSTIBLE");
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$contador, $cita['color']);
$objPHPExcel->getActiveSheet()->SetCellValue('N'.$contador, $cita['precio']." €");
}
$objPHPExcel->getActiveSheet()->getStyle('K3:K'.$contador)->applyFromArray($derecha);
$objPHPExcel->getActiveSheet()->getStyle('H3:H'.$contador)->applyFromArray($centrado);
//exit;
//guardamos el archivo.
$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Citas_'.date("d-m-Y").'.xls"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
//exit;
}else{
//renderizamos el listado de usuario
return $this->render('cita/listado.html.twig',array(
'citas'=>$citas,
'talleres'=>$talleres,
'totalregistros'=>$total,
'paginaactual'=>$paginaactual,
'numpaginas'=> $numpaginas,
'fechas' => $fechas,
'tipovehiculos'=>$tipovehiculos,
'postfecha'=>$postfecha,
'postcliente'=>$postcliente,
'postmatricula'=>$postmatricula,
'posttipovehiculo'=>$posttipovehiculo,
'posttaller'=>$posttaller,
"postfecha"=>$postfecha,
"postmatricula"=>$postmatricula,
"posttipovehiculo"=>$posttipovehiculo
)
);
}
}
public function listadoHistorico(Request $request,$paginaactual){
$em=$this->getDoctrine()->getManager();
$usuario_conectado=$this->getUser();
$tipovehiculos=$em->getRepository("App:Tipovehiculo")->findBy(array("activo"=>1),array('nombre' => 'ASC'));
$talleres=$em->getRepository("App:Taller")->findBy(array("activo"=>1),array('nombre' => 'ASC'));
//para mostrar en el historico solo las citas que no estan en la tabla de citas.
$sql_where="
and (
select count(id) from cita
where cita.matricula=c.matricula
)=0
";
if($this->getUser()->getIdrol()->getId()==1){
$sql = "select distinct (DATE_FORMAT(fecha,'%d-%m-%Y')) as fecha from cita_historico c where 1=1 ".$sql_where." order by fecha desc";
$stmt= $em->getConnection()->query($sql);
$fechas=$stmt->fetchAll();
}else{
$sql = "select distinct (DATE_FORMAT(fecha,'%d-%m-%Y')) as fecha from cita_historico c where idtaller =".$this->getUser()->getIdtaller()->getId()." ".$sql_where." order by fecha desc";
$stmt= $em->getConnection()->query($sql);
$fechas=$stmt->fetchAll();
}
//filtros
$postfecha="";
$postcliente="";
$postmatricula="";
$posttipovehiculo="";
$posttaller="";
$filtros = "";
if($request->isMethod('POST')){
if(isset($_POST["btn_buscar"])){
$paginaactual=1;
}
if($_POST["fecha"]!=""){
$filtros.=" and DATE_FORMAT(c.fecha,'%d-%m-%Y')='".$_POST["fecha"]."'";
}
$postfecha=$_POST["fecha"];
if($_POST["matricula"]!=""){
$filtros.=" and matricula like '%".$_POST["matricula"]."%'";
}
$postmatricula=$_POST["matricula"];
if($_POST["tipo"]!=""){
$filtros.=" and c.idtipovehiculo =".$_POST["tipo"];
}
$posttipovehiculo=$_POST["tipo"];
if(isset($_POST["taller"]) && $_POST["taller"]!=""){
$filtros.=" and c.idtaller = ".$_POST["taller"];
$posttaller=$_POST["taller"];
}
}
//total
$sql = "SELECT count(c.id) as total ";
$sql .= "FROM cita_historico c ";
$sql .= " inner join usuario on usuario.id=c.idusuario ";
$sql .= " inner join taller on taller.id=c.idtaller ";
$sql .= " inner join tipovehiculo on tipovehiculo.id=c.idtipovehiculo ";
$sql .= " inner join subtipovehiculo on subtipovehiculo.id=c.idsubtipovehiculo ";
$sql .= "WHERE 1=1 ";
$sql.=$sql_where;
if($this->getUser()->getIdrol()->getId()==2){
$sql .= " and c.idtaller= ".$this->getUser()->getIdtaller()->getId();
}
if($filtros!=""){
$sql.=$filtros;
}
$stmt= $em->getConnection()->query($sql);
$total=$stmt->fetchAll()[0]['total'];
$numpaginas = ceil($total/20);
//citas paginados de 20 en 20
$sql = "SELECT c.*,taller.nombre as taller,taller.id as id_taller, ";
$sql .= " concat(usuario.nombre,' ',usuario.apellidos) as cliente, ";
$sql .= " usuario.telefono, ";
$sql .= " usuario.email, ";
$sql .= " tipovehiculo.nombre as tipo, ";
$sql .= " tipovehiculo.electrico, ";
$sql .= " subtipovehiculo.nombre as modelo, ";
$sql .= " subtipovehiculo.color, ";
$sql .= " tiempo ";
$sql .= " from cita_historico c ";
$sql .= " inner join usuario on usuario.id=c.idusuario ";
$sql .= " inner join taller on taller.id=c.idtaller ";
$sql .= " inner join tipovehiculo on tipovehiculo.id=c.idtipovehiculo ";
$sql .= " inner join subtipovehiculo on subtipovehiculo.id=c.idsubtipovehiculo ";
$sql .= "WHERE 1=1 ";
$sql.=$sql_where;
if($this->getUser()->getIdrol()->getId()==2){
$sql .= " and c.idtaller= ".$this->getUser()->getIdtaller()->getId();
}
if($filtros!=""){
$sql.=$filtros;
}
$sql .= " ORDER BY c.fecha ASC";
$sql .= " LIMIT ".(($paginaactual-1)*20).", 20";
$stmt= $em->getConnection()->query($sql);
$citas=$stmt->fetchAll();
//renderizamos el listado de usuario
return $this->render('cita/listado_historico.html.twig',array(
'citas'=>$citas,
'talleres'=>$talleres,
'totalregistros'=>$total,
'paginaactual'=>$paginaactual,
'numpaginas'=> $numpaginas,
'fechas' => $fechas,
'tipovehiculos'=>$tipovehiculos,
'postfecha'=>$postfecha,
'postcliente'=>$postcliente,
'postmatricula'=>$postmatricula,
'posttipovehiculo'=>$posttipovehiculo,
'posttaller'=>$posttaller,
"postfecha"=>$postfecha,
"postmatricula"=>$postmatricula,
"posttipovehiculo"=>$posttipovehiculo
)
);
}
public function nuevo(Request $request){
date_default_timezone_set('Europe/Madrid');
$em=$this->getDoctrine()->getManager();
$tipovehiculos=$em->getRepository("App:Tipovehiculo")->findBy(array("activo"=>1),array('id' => 'ASC'));
if($this->getUser()->getIdrol()->getId()==2){
$talleres=$em->getRepository("App:Taller")->findBy(array("activo"=>1,"id"=>$this->getUser()->getIdtaller()->getId()));
}else{
$talleres=$em->getRepository("App:Taller")->findBy(array("activo"=>1),array('nombre' => 'ASC'));
}
$clientes=$em->getRepository("App:Usuario")->findBy(array("activo"=>1,"idrol"=>3),array('nombre' => 'ASC'));
//$urlbanco=$_ENV["URL_BANCO"];
//Si entramos por post, damos de alta la cita
if($request->isMethod('POST')){
//Buscamos si existe una cita con la matricula.
$existe_cita = $em->getRepository("App:Cita")->findBy(["matricula"=>$_POST["matricula"]]);
if(count($existe_cita)>0){
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Error',
'Ya existe una cita con estra matrícula'
);
//volvemos al nuevo.
return $this->redirect($this->generateUrl('cita_nuevo'));
}
$cita=new Cita();
$cita->setMatricula($_POST["matricula"]);
$tipovehiculo=$em->getRepository("App:Tipovehiculo")->find($_POST["tipo_vehiculo"]);
$subtipovehiculo=$em->getRepository("App:Subtipovehiculo")->find($_POST["modelo"]);
$taller=$em->getRepository("App:Taller")->find($_POST["taller"]);
$cita->setIdtipovehiculo($tipovehiculo);
$cita->setIdsubtipovehiculo($subtipovehiculo);
$fecha = new \DateTime($_POST["dia"]);
$cita->setFecha($fecha);
$hora = new \DateTime($_POST["hora"]);
$cita->setHorainicio($hora);
$horafin=new \DateTime($_POST["hora"]);
$horafin->modify("+ ".$tipovehiculo->getTiempo()." minutes");
$cita->setHorafin($horafin);
if(isset($_POST["factura"])){
$cita->setFactura(1);
}else{
$cita->setFactura(0);
}
$cita->setFechaAlta(new \DateTime("now"));
$cita->setActivo(1);
$cliente = $em->getRepository("App:Usuario")->find($_POST["cliente"]);
$cita->setIdusuario($cliente);
$cita->setIdtaller($taller);
$em->persist($cita);
$em->flush();
//Si tenemos aceptacion de trabajo.
if(isset($_POST["aceptatrabajo"])){
$cita->setAceptatrabajo(1);
$cita->setNombreacepta($_POST["nombreacepta"]);
$cita->setApellidosacepta($_POST["apellidosacepta"]);
$cita->setDniacepta($_POST["dniacepta"]);
$cita->setFechaAcepta(new \DateTime("now"));
$data=$_POST["imagen_aceptacion"];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
if (!file_exists($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId())) {
mkdir($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId(), 0777, true);
}
//creamos la carpeta si no existe.
file_put_contents($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId().'/firma_aceptacion.png', $data);
$cita->setFirmaAcepta('/firmas/cita_'.$cita->getId().'/firma_aceptacion.png');
$em->persist($cita);
$em->flush();
$this->enviarCorreoAceptacion($cita);
if(isset($_POST["multisubida_antes"])){
foreach($_POST["multisubida_antes"] as $img){
$nombre_imagen=explode("|",$img)[0];
$imagen=explode("|",$img)[1];
list($type, $imagen) = explode(';', $imagen);
list(, $imagen) = explode(',', $imagen);
$imagen = base64_decode($imagen);
if (!file_exists($_SERVER["DOCUMENT_ROOT"].'/imagenes_antes/cita_'.$cita->getId())) {
mkdir($_SERVER["DOCUMENT_ROOT"].'/imagenes_antes/cita_'.$cita->getId(), 0777, true);
}
file_put_contents($_SERVER["DOCUMENT_ROOT"].'/imagenes_antes/cita_'.$cita->getId().'/'.$nombre_imagen, $imagen);
//guardamos en la base de datos.
$imagenAntes=new ImagenesAntesCita();
$imagenAntes->setIdcita($cita);
$imagenAntes->setImagen('/imagenes_antes/cita_'.$cita->getId().'/'.$nombre_imagen);
$em->persist($imagenAntes);
$em->flush();
}
}
if(isset($_POST["multisubida_despues"])){
foreach($_POST["multisubida_despues"] as $img){
$nombre_imagen=explode("|",$img)[0];
$imagen=explode("|",$img)[1];
list($type, $imagen) = explode(';', $imagen);
list(, $imagen) = explode(',', $imagen);
$imagen = base64_decode($imagen);
if (!file_exists($_SERVER["DOCUMENT_ROOT"].'/imagenes_despues/cita_'.$cita->getId())) {
mkdir($_SERVER["DOCUMENT_ROOT"].'/imagenes_despues/cita_'.$cita->getId(), 0777, true);
}
file_put_contents($_SERVER["DOCUMENT_ROOT"].'/imagenes_despues/cita_'.$cita->getId().'/'.$nombre_imagen, $imagen);
//guardamos en la base de datos.
$imagenDespues=new ImagenesDespuesCita();
$imagenDespues->setIdcita($cita);
$imagenDespues->setImagen('/imagenes_despues/cita_'.$cita->getId().'/'.$nombre_imagen);
$em->persist($imagenDespues);
$em->flush();
}
}
}
//creamos la parte del pago.
/*$amount=$tipovehiculo->getPrecio()*100;
$order = str_pad($cita->getId(), 10, "0", STR_PAD_LEFT); //Se calculará con el identificador de la cita 10 posiciones relleno a 0 por la izquierda
$fuc=$_ENV["FUC"];
$moneda = $_ENV["MONEDA"];
$tipotransaccion = $_ENV["TIPO_TRANSACCION"];
$descripcion = $_POST["matricula"]."-".$taller->getNombre()." - (".$fecha->format("d-m-Y")." ".$hora->format("H:i")." )";
$terminal = $_ENV["TERMINAL"];
$clavesecreta=$_ENV["CLAVE_SECRETA"];
$urlko = "https://gls.tecnosenyal.com/libs/API_PHP/urlerror.php";
$urlok = "https://gls.tecnosenyal.com/libs/API_PHP/urlok.php";
$miObj = new RedsysAPI;
$miObj->setParameter("DS_MERCHANT_AMOUNT",$amount);
$miObj->setParameter("DS_MERCHANT_ORDER",$order);
$miObj->setParameter("DS_MERCHANT_MERCHANTCODE", $fuc);
$miObj->setParameter("DS_MERCHANT_CURRENCY", $moneda);
$miObj->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $tipotransaccion);
$miObj->setParameter("DS_MERCHANT_PRODUCTDESCRIPTION", $descripcion);
$miObj->setParameter("DS_MERCHANT_URLOK",$urlok);
$miObj->setParameter("DS_MERCHANT_URLKO",$urlko);
$miObj->setParameter("DS_MERCHANT_TERMINAL", $terminal);
//Calculamos la firma
$params = $miObj->createMerchantParameters();
$firma = $miObj->createMerchantSignature($clavesecreta);
return new JsonResponse(["id_cita"=>$cita->getId(),"firma"=>$firma,"params"=>$params]);*/
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Correcto',
'Cita creada correctamente'
);
//reedirigmos al listado de citas
return $this->redirect($this->generateUrl('cita_listado'));
}
//renderizamos la plantilla de nueva cita
return $this->render('cita/nuevo.html.twig',array(
'tipovehiculos'=> $tipovehiculos,
'talleres'=> $talleres,
'clientes'=>$clientes
)
);
}
public function editar(Request $request,$idcita){
$em=$this->getDoctrine()->getManager();
$urlbanco=$_ENV["URL_BANCO"];
date_default_timezone_set('Europe/Madrid');
$tipovehiculos=$em->getRepository("App:Tipovehiculo")->findBy(array("activo"=>1),array('id' => 'ASC'));
if($this->getUser()->getIdrol()->getId()==2){
$talleres=$em->getRepository("App:Taller")->findBy(array("activo"=>1,"id"=>$this->getUser()->getIdtaller()->getId()));
}else{
$talleres=$em->getRepository("App:Taller")->findBy(array("activo"=>1),array('nombre' => 'ASC'));
}
$clientes=$em->getRepository("App:Usuario")->findBy(array("activo"=>1,"idrol"=>3),array('nombre' => 'ASC'));
$cita=$em->getRepository("App:Cita")->find($idcita);
$imagenesAntes=$em->getRepository("App:ImagenesAntesCita")->findBy(array("idcita"=>$idcita));
$sobrecostes=$em->getRepository("App:Sobrecostes")->findBy(["idcita"=>$idcita]);
foreach($imagenesAntes as $key=>$imagen){
if(file_exists($_SERVER['DOCUMENT_ROOT'].$imagen->getImagen())){
$imagenesAntes[$key]->size=filesize ($_SERVER['DOCUMENT_ROOT'].$imagen->getImagen());
}else{
$imagenesAntes[$key]->size=0;
}
}
$imagenesDespues=$em->getRepository("App:ImagenesDespuesCita")->findBy(array("idcita"=>$idcita));
foreach($imagenesDespues as $key=>$imagen){
if(file_exists($_SERVER['DOCUMENT_ROOT'].$imagen->getImagen())){
$imagenesDespues[$key]->size=filesize ($_SERVER['DOCUMENT_ROOT'].$imagen->getImagen());
}else{
$imagenesDespues[$key]->size=0;
}
}
//Si entramos por post, damos de alta la cita
if($request->isMethod('POST')){
$cita->setMatricula($_POST["matricula"]);
$tipovehiculo=$em->getRepository("App:Tipovehiculo")->find($_POST["tipo_vehiculo"]);
$subtipovehiculo=$em->getRepository("App:Subtipovehiculo")->find($_POST["modelo"]);
$taller=$em->getRepository("App:Taller")->find($_POST["taller"]);
$cita->setIdtipovehiculo($tipovehiculo);
$cita->setIdsubtipovehiculo($subtipovehiculo);
$fecha = new \DateTime($_POST["dia"]);
$cita->setFecha($fecha);
$hora = new \DateTime($_POST["hora"]);
$cita->setHorainicio($hora);
$horafin=new \DateTime($_POST["hora"]);
$horafin->modify("+ ".$tipovehiculo->getTiempo()." minutes");
$cita->setHorafin($horafin);
if(isset($_POST["factura"])){
$cita->setFactura(1);
}else{
$cita->setFactura(0);
}
$cliente = $em->getRepository("App:Usuario")->find($_POST["cliente"]);
$cita->setIdusuario($cliente);
$cita->setIdtaller($taller);
$em->persist($cita);
$em->flush();
//Si tenemos aceptacion de trabajo.
if(isset($_POST["aceptatrabajo"])){
$aceptaanterior=$cita->getAceptatrabajo();
$cita->setAceptatrabajo(1);
$cita->setNombreacepta($_POST["nombreacepta"]);
$cita->setApellidosacepta($_POST["apellidosacepta"]);
$cita->setDniacepta($_POST["dniacepta"]);
if(!$aceptaanterior){
$cita->setFechaAcepta(new \DateTime("now"));
}
$data=$_POST["imagen_aceptacion"];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
if (!file_exists($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId())) {
mkdir($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId(), 0777, true);
}
if(file_exists($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId().'/firma_aceptacion.png')){
unlink($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId().'/firma_aceptacion.png');
}
//creamos la carpeta si no existe.
file_put_contents($_SERVER["DOCUMENT_ROOT"].'/firmas/cita_'.$cita->getId().'/firma_aceptacion.png', $data);
$cita->setFirmaAcepta('/firmas/cita_'.$cita->getId().'/firma_aceptacion.png');
$em->persist($cita);
$em->flush();
if(!$aceptaanterior){
$this->enviarCorreoAceptacion($cita);
}
}
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Correcto',
'Cita editada correctamente'
);
return $this->redirect($this->generateUrl('cita_editar',["idcita"=>$idcita]));
}
//renderizamos la plantilla de nueva cita
return $this->render('cita/editar.html.twig',array(
'tipovehiculos'=> $tipovehiculos,
'talleres'=> $talleres,
'clientes'=>$clientes,
'cita'=>$cita,
'imagenesAntes'=>$imagenesAntes,
'imagenesDespues'=>$imagenesDespues,
'urlbanco'=>$urlbanco=$_ENV["URL_BANCO"],
'sobrecostes'=>$sobrecostes
)
);
}
public function crearSobreCostes(Request $request){
$em=$this->getDoctrine()->getManager();
$sobrecoste=new Sobrecostes();
$cita=$em->getRepository("App:Cita")->find($_POST["idcita"]);
$sobrecoste->setIdcita($cita);
$sobrecoste->setPrecio($_POST["precio"]);
$sobrecoste->setDescripcion($_POST["descripcion"]);
$sobrecoste->setPagado(0);
$em->persist($sobrecoste);
$em->flush();
//configuracion del pago
//creamos la parte del pago.
$amount=$_POST["precio"]*100;
$order = "S".str_pad($sobrecoste->getId(), 9, "0", STR_PAD_LEFT); //Se calculará con el identificador de la cita 10 posiciones relleno a 0 por la izquierda
$fuc=$_ENV["FUC"];
$moneda = $_ENV["MONEDA"];
$tipotransaccion = $_ENV["TIPO_TRANSACCION"];
$descripcion = $_POST["descripcion"];
$terminal = $_ENV["TERMINAL"];
$clavesecreta=$_ENV["CLAVE_SECRETA"];
$urlko = "https://gls.tecnosenyal.com/libs/API_PHP/urlerror.php";
$urlok = "https://gls.tecnosenyal.com/libs/API_PHP/urlok.php";
$miObj = new RedsysAPI;
$miObj->setParameter("DS_MERCHANT_AMOUNT",$amount);
$miObj->setParameter("DS_MERCHANT_ORDER",$order);
$miObj->setParameter("DS_MERCHANT_MERCHANTCODE", $fuc);
$miObj->setParameter("DS_MERCHANT_CURRENCY", $moneda);
$miObj->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $tipotransaccion);
$miObj->setParameter("DS_MERCHANT_PRODUCTDESCRIPTION", $descripcion);
$miObj->setParameter("DS_MERCHANT_URLOK",$urlok);
$miObj->setParameter("DS_MERCHANT_URLKO",$urlko);
$miObj->setParameter("DS_MERCHANT_TERMINAL", $terminal);
//Calculamos la firma
$params = $miObj->createMerchantParameters();
$firma = $miObj->createMerchantSignature($clavesecreta);
return new JsonResponse(["idsobrecoste"=>$sobrecoste->getId(),"firma"=>$firma,"params"=>$params]);
}
public function solicitarCita(Request $request){
$em=$this->getDoctrine()->getManager();
date_default_timezone_set('Europe/Madrid');
//elimianamos las citas no activas que tengan mas de 10 minutos.
$sql=" delete from cita where TIMESTAMPDIFF(MINUTE,fecha_alta,NOW()) >=60 and (activo = 0 or activo is null)";
$stmt= $em->getConnection()->query($sql);
$urlbanco=$_ENV["URL_BANCO"];
$citas=$em->getRepository("App:Cita")->findBy(["idusuario"=>$this->getUser()->getId(),"activo"=>1]);
//obtenemos los tipos de coches
//$tipovehiculos = $em->getRepository("App:Tipovehiculo")->findAll(["activo"=>1]);
//Si entramos por post, damos de alta la cita
if($request->isMethod('POST')){
//Buscamos si existe una cita con la matricula.
$existe_cita = $em->getRepository("App:Cita")->findBy(["matricula"=>$_POST["matricula"]]);
if(count($existe_cita)>0){
return new JsonResponse(["error"=>"Ya existe una cita con esta matricula."]);
}
$cita=new Cita();
$cita_historico=new CitaHistorico();
$cita->setMatricula(trim($_POST["matricula"]));
$cita_historico->setMatricula(trim($_POST["matricula"]));
$tipovehiculo=$em->getRepository("App:Tipovehiculo")->find($_POST["tipo_vehiculo"]);
$subtipovehiculo=$em->getRepository("App:Subtipovehiculo")->find($_POST["modelo"]);
$taller=$em->getRepository("App:Taller")->find($_POST["taller"]);
$cita->setIdtipovehiculo($tipovehiculo);
$cita->setIdsubtipovehiculo($subtipovehiculo);
$cita_historico->setIdtipovehiculo($tipovehiculo);
$cita_historico->setIdsubtipovehiculo($subtipovehiculo);
$fecha = new \DateTime($_POST["dia"]);
$cita->setFecha($fecha);
$cita_historico->setFecha($fecha);
$hora = new \DateTime($_POST["hora"]);
$cita->setHorainicio($hora);
$cita_historico->setHorainicio($hora);
$horafin=new \DateTime($_POST["hora"]);
$horafin->modify("+ ".$tipovehiculo->getTiempo()." minutes");
$cita->setHorafin($horafin);
$cita_historico->setHorafin($horafin);
//if(isset($_POST["factura"])){
$cita->setFactura(1);
$cita_historico->setFactura(1);
//}else{
// $cita->setFactura(0);
//}
$cita->setFechaAlta(new \DateTime("now"));
$cita_historico->setFechaAlta(new \DateTime("now"));
$cita->setActivo(0);
$cita->setIdusuario($this->getUser());
$cita_historico->setIdusuario($this->getUser());
$cita->setIdtaller($taller);
$cita_historico->setIdtaller($taller);
$em->persist($cita);
$em->persist($cita_historico);
$em->flush();
//creamos la parte del pago.
$amount=$tipovehiculo->getPrecio()*100;
$order = str_pad($cita->getId(), 10, "0", STR_PAD_LEFT); //Se calculará con el identificador de la cita 10 posiciones relleno a 0 por la izquierda
$fuc=$_ENV["FUC"];
$moneda = $_ENV["MONEDA"];
$tipotransaccion = $_ENV["TIPO_TRANSACCION"];
$descripcion = $_POST["matricula"]."-".$taller->getNombre()." - (".$fecha->format("d-m-Y")." ".$hora->format("H:i")." )";
$terminal = $_ENV["TERMINAL"];
$clavesecreta=$_ENV["CLAVE_SECRETA"];
$urlko = "https://gls.tecnosenyal.com/libs/API_PHP/urlerror.php";
$urlok = "https://gls.tecnosenyal.com/libs/API_PHP/urlok.php";
$miObj = new RedsysAPI;
/*if($_SERVER['REMOTE_ADDR'] == "185.153.16.21"){
$amount=0.01*100;
}*/
$miObj->setParameter("DS_MERCHANT_AMOUNT",$amount);
$miObj->setParameter("DS_MERCHANT_ORDER",$order);
$miObj->setParameter("DS_MERCHANT_MERCHANTCODE", $fuc);
$miObj->setParameter("DS_MERCHANT_CURRENCY", $moneda);
$miObj->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $tipotransaccion);
$miObj->setParameter("DS_MERCHANT_PRODUCTDESCRIPTION", $descripcion);
$miObj->setParameter("DS_MERCHANT_URLOK",$urlok);
$miObj->setParameter("DS_MERCHANT_URLKO",$urlko);
$miObj->setParameter("DS_MERCHANT_TERMINAL", $terminal);
//Calculamos la firma
$params = $miObj->createMerchantParameters();
$firma = $miObj->createMerchantSignature($clavesecreta);
return new JsonResponse(["id_cita"=>$cita->getId(),"firma"=>$firma,"params"=>$params]);
}
$sql = "select distinct p.* ";
$sql .= "from provincia p inner join taller t on p.id = t.idprovincia ";
$sql .= "where p.activo =1 order by p.nombre asc";
$stmt= $em->getConnection()->query($sql);
$provincias=$stmt->fetchAll();
$provincias[0]["selected"]=true;
$talleres = $em->getRepository("App:Taller")->findBy(["idprovincia"=>$provincias[0]["id"],"activo"=>1]);
$contador=1;
while(count($talleres)==0){
if($provincias[0]["selected"] == true){
$provincias[0]["selected"]=false;
}
if($contador<count($provincias)){
$talleres = $em->getRepository("App:Taller")->findBy(["idprovincia"=>$provincias[$contador]["id"],"activo"=>1]);
$provincias[$contador]["selected"]=true;
}else{
break;
}
$contador++;
}
return $this->render('cita/registro_cita.html.twig',["provincias"=>$provincias,"talleres"=>$talleres,"urlbanco"=>$urlbanco,"citas"=>$citas]);
}
public function terminos(Request $request){
return $this->render('cita/terminos.html.twig');
}
public function multisubidaImagenes(){
return new JsonResponse(['success' => true,"archivo"=>$_FILES["file"]]);
}
public function multisubidaImagenesAntesEdicion($idcita){
$em=$this->getDoctrine()->getManager();
if (!empty($_FILES)) {
try{
$cita=$em->getRepository('App:Cita')->find($idcita);
$rutafichero ="/imagenes_antes/cita_".$cita->getId();
$directorio_ficheros=$_SERVER["DOCUMENT_ROOT"].$rutafichero;
//si no existe el directorio lo creamos.
if (!file_exists($directorio_ficheros)){
mkdir($directorio_ficheros, 0755);
}
$nombre=$_FILES["file"]["name"];
//Tenemos que poner el nombre con la fecha para no duplicar.
$fichero=$directorio_ficheros."/".$nombre;
$ficheroguardar= $rutafichero."/".$nombre;
move_uploaded_file($_FILES["file"]["tmp_name"],$fichero);
$imagenAntes=new ImagenesAntesCita();
$imagenAntes->setIdcita($cita);
$imagenAntes->setImagen($ficheroguardar);
$em->persist($imagenAntes);
$em->flush();
return new JsonResponse(['success' => true,"id"=>$imagenAntes->getId(),"nombre"=>$nombre]);
}catch(\Exception $e){
echo $e->getMessage();
}
}
exit;
}
public function multisubidaImagenesDespuesEdicion($idcita){
$em=$this->getDoctrine()->getManager();
if (!empty($_FILES)) {
try{
$cita=$em->getRepository('App:Cita')->find($idcita);
$rutafichero ="/imagenes_despues/cita_".$cita->getId();
$directorio_ficheros=$_SERVER["DOCUMENT_ROOT"].$rutafichero;
//si no existe el directorio lo creamos.
if (!file_exists($directorio_ficheros)){
mkdir($directorio_ficheros, 0755);
}
$nombre=$_FILES["file"]["name"];
//Tenemos que poner el nombre con la fecha para no duplicar.
$fichero=$directorio_ficheros."/".$nombre;
$ficheroguardar= $rutafichero."/".$nombre;
move_uploaded_file($_FILES["file"]["tmp_name"],$fichero);
$imagenDespues=new ImagenesDespuesCita();
$imagenDespues->setIdcita($cita);
$imagenDespues->setImagen($ficheroguardar);
$em->persist($imagenDespues);
$em->flush();
return new JsonResponse(['success' => true,"id"=>$imagenDespues->getId(),"nombre"=>$nombre]);
}catch(\Exception $e){
echo $e->getMessage();
}
}
exit;
}
public function eliminarImagenAntes($idimagen){
$em=$this->getDoctrine()->getManager();
$imagen=$em->getRepository('App:ImagenesAntesCita')->find($idimagen);
//eliminamos el fichero fisicamente.
if(file_exists($_SERVER["DOCUMENT_ROOT"].$imagen->getImagen())){
unlink($_SERVER["DOCUMENT_ROOT"].$imagen->getImagen());
}
$em->remove($imagen);
$em->flush();
exit;
}
public function eliminarImagenDespues($idimagen){
$em=$this->getDoctrine()->getManager();
$imagen=$em->getRepository('App:ImagenesDespuesCita')->find($idimagen);
//eliminamos el fichero fisicamente.
if(file_exists($_SERVER["DOCUMENT_ROOT"].$imagen->getImagen())){
unlink($_SERVER["DOCUMENT_ROOT"].$imagen->getImagen());
}
$em->remove($imagen);
$em->flush();
exit;
}
public function eliminarCita($id){
$em=$this->getDoctrine()->getManager();
$sql="delete from imagenes_antes_cita where idcita=".$id;
$em->getConnection()->query($sql);
$sql="delete from imagenes_despues_cita where idcita=".$id;
$em->getConnection()->query($sql);
$cita=$em->getRepository("App:Cita")->find($id);
$em->remove($cita);
$em->flush();
return $this->redirect($this->generateUrl('cita_listado'));
}
public function eliminarCitaHistorico($id){
$em=$this->getDoctrine()->getManager();
$cita=$em->getRepository("App:CitaHistorico")->find($id);
$em->remove($cita);
$em->flush();
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Correcto',
'La cita ha sido eliminada correctamente.'
);
return $this->redirect($this->generateUrl('historico_citas'));
}
public function errorPago(Request $request,$idcita,$codigo){
$em=$this->getDoctrine()->getManager();
//Eliminamos la cita.
$cita=$em->getRepository("App:Cita")->find($idcita);
if($cita){
$em->remove($cita);
$em->flush();
}
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Error',
'Ocurrio un erro al realizar el pago:'.$codigo
);
}else{
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'ErrorCita',
'Ocurrio un erro al realizar el pago:'.$codigo
);
}
//Si el usuario es admin o taller nos vamos a nueva cita de la parte privada
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
return $this->redirect($this->generateUrl('cita_nuevo'));
}else{
return $this->redirect($this->generateUrl('solicitar_cita'));
}
}
public function errorCodigo(Request $request,$idcita,$codigo){
$em=$this->getDoctrine()->getManager();
//Eliminamos la cita.
$cita=$em->getRepository("App:Cita")->find($idcita);
if($cita){
$em->remove($cita);
$em->flush();
}
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Error',
'Código de operación erróneo:'.$codigo
);
}else{
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'ErrorCita',
'Código de operación erróneo:'.$codigo
);
}
//Si el usuario es admin o taller nos vamos a nueva cita de la parte privada
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
return $this->redirect($this->generateUrl('cita_nuevo'));
}else{
return $this->redirect($this->generateUrl('solicitar_cita'));
}
}
public function okPago(Request $request,$idcita){
$em=$this->getDoctrine()->getManager();
//Activamos la cita.
$cita=$em->getRepository("App:Cita")->find($idcita);
if($cita){
$cita->setActivo(1);
$em->persist($cita);
$em->flush();
}else{
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Error',
'Ha expirado el tiempo para solicitar la cita.'
);
}else{
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'ErrorCita',
'Ha expirado el tiempo para solicitar la cita.En caso de porblema de pago pongase en contacto con su taller.'
);
}
//Si el usuario es admin o taller nos vamos a nueva cita de la parte privada
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
return $this->redirect($this->generateUrl('cita_nuevo'));
}else{
return $this->redirect($this->generateUrl('solicitar_cita'));
}
}
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Correcto',
'La cita se ha creado correctamente. Se le enviará un correo al cliente con los datos de la cita.'
);
}else{
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'CorrectoCita',
'La cita se ha creado correctamente. Se le enviará un correo con los datos de la cita.'
);
}
//Enviamos el email.
// return $this->render("cita/email_cita.html.twig",array("nombre"=>$cita->getIdusuario()->getNombre()." ".$cita->getIdusuario()->getApellidos(),"fecha"=>$cita->getFecha()->format("d-m-Y"),"horainicio"=>$cita->getHorainicio()->format("H:i"),"horafin"=>$cita->getHorafin()->format("H:i"),"taller"=>$cita->getIdtaller()->getNombre(),"enlace"=>$cita->getIdtaller()->getMapaGoogle()));
$mail = new \PHPMailer();
$mail->isSMTP();
$mail->Host = $_ENV["EMAIL_HOST"];
$mail->Port = $_ENV["EMAIL_PORT"];
$mail->SMTPSecure = $_ENV["EMAIL_SECURE"];
//$mail->SMTPAutoTLS = false;
//$mail->SMTPSecure = false;
$mail->SMTPAuth = true;
$mail->Username = $_ENV["EMAIL_USERNAME"];
$mail->Password = $_ENV["EMAIL_PASSWORD"];
$mail->From=$_ENV["EMAIL_FROM"];
$mail->FromName=$_ENV["EMAIL_FROMNAME"];
$mail->addAddress($cita->getIdusuario()->getEmail());
$mail->Subject = 'Cita Cambio Imagen';
$mail->IsHTML(true); // El correo se envía como HTML
$mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) );
$plantilla= $this->renderView("cita/email_cita.html.twig",
array("nombre"=>$cita->getIdusuario()->getNombre()." ".$cita->getIdusuario()->getApellidos(),
"fecha"=>$cita->getFecha()->format("d-m-Y"),
"horainicio"=>$cita->getHorainicio()->format("H:i"),
"horafin"=>$cita->getHorafin()->format("H:i"),
"taller"=>$cita->getIdtaller()->getNombre(),
"enlace"=>$cita->getIdtaller()->getMapaGoogle(),
"tipovehiculo"=>$cita->getIdtipovehiculo()->getNombre()
));
$mail->msgHTML(utf8_decode($plantilla));
$mail->SMTPDebug=2;
$exito=$mail->send();
//Si el usuario es admin o taller nos vamos a nueva cita de la parte privada
if(($this->getUser()->getIdrol()->getId() == 1 || $this->getUser()->getIdrol()->getId() == 2)){
return $this->redirect($this->generateUrl('cita_nuevo'));
}else{
return $this->redirect($this->generateUrl('solicitar_cita'));
}
}
public function errorSobrecoste(Request $request,$id,$codigo){
$em=$this->getDoctrine()->getManager();
//Eliminamos el sobrecoste
$sobrecoste=$em->getRepository("App:Sobrecostes")->find($id);
if($sobrecoste){
$em->remove($sobrecoste);
$em->flush();
}
$this->get('session')->getFlashBag()->add(
'Error',
'Error al realizar la operación:'.$codigo
);
return $this->redirect($this->generateUrl('cita_editar',["idcita"=>$sobrecoste->getIdcita()->getId()]));
}
public function errorCodigoSobrecoste(Request $request,$id,$codigo){
$em=$this->getDoctrine()->getManager();
//Eliminamos la cita.
$sobrecoste=$em->getRepository("App:Sobrecostes")->find($id);
if($sobrecoste){
$em->remove($sobrecoste);
$em->flush();
}
$this->get('session')->getFlashBag()->add(
'Error',
'Código de operación erróneo:'.$codigo
);
return $this->redirect($this->generateUrl('cita_editar',["idcita"=>$sobrecoste->getIdcita()->getId()]));
}
public function okSobrecoste(Request $request,$id){
$em=$this->getDoctrine()->getManager();
//Eliminamos la cita.
$sobrecoste=$em->getRepository("App:Sobrecostes")->find($id);
$sobrecoste->setPagado(1);
$em->persist($sobrecoste);
$em->flush();
$this->get('session')->getFlashBag()->add(
'Correcto',
'El sobrecoste ha sido abonado correctamente.'
);
return $this->redirect($this->generateUrl('cita_editar',["idcita"=>$sobrecoste->getIdcita()->getId()]));
}
function enviarCorreoAceptacion($idcita){
$em=$this->getDoctrine()->getManager();
$cita=$em->getRepository("App:Cita")->find($idcita);
$sobrecoste=$em->getRepository("App:Sobrecostes")->findBy(["idcita"=>$idcita]);
//enviamos el correo.
$mail = new \PHPMailer();
$mail->isSMTP();
$mail->Host = $_ENV["EMAIL_HOST"];
$mail->Port = $_ENV["EMAIL_PORT"];
$mail->SMTPSecure = $_ENV["EMAIL_SECURE"];
//$mail->SMTPAutoTLS = false;
//$mail->SMTPSecure = false;
$mail->SMTPAuth = true;
$mail->Username = $_ENV["EMAIL_USERNAME"];
$mail->Password = $_ENV["EMAIL_PASSWORD"];
$mail->From=$_ENV["EMAIL_FROM"];
$mail->FromName=$_ENV["EMAIL_FROMNAME"];
$mail->addAddress($cita->getIdusuario()->getEmail());
$mail->Subject = 'Trabajo Realizado';
$mail->IsHTML(true); // El correo se envía como HTML
$mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) );
$plantilla= $this->renderView("cita/informe_trabajos.html.twig",array("cita"=>$cita,"sobrecoste"=>$sobrecoste));
$mail->msgHTML(utf8_decode($plantilla));
// $mail->SMTPDebug=2;
$exito=$mail->send();
}
public function getEstilos(){
return [
"titulo"=> array(
'alignment' => array(
'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FFFFFF'),
'size' => 16,
),
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => '0473b8')
)
),
"cabecera"=> array(
'alignment' => array(
'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'font' => array(
'bold' => true,
'color' => array('rgb' => '000000'),
'size' => 11,
),
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'cccccc')
)
),
"centrado"=>array(
'alignment' => array(
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
),
"centrado_vertical"=>array(
'alignment' => array(
'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER)
),
"izquierda"=>array(
'alignment' => array(
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT)
),
"borde_izquierda"=>array(
'borders' => array(
'left' => array('style' => \PHPExcel_Style_Border::BORDER_THIN)
),
),
"borde_derecha"=>array(
'borders' => array(
'right' => array('style' => \PHPExcel_Style_Border::BORDER_THIN)
),
),
"borde_abajo" => array(
'borders' => array(
'bottom' => array('style' => \PHPExcel_Style_Border::BORDER_THIN)
),
),
"borde_arriba" => array(
'borders' => array(
'top' => array('style' => \PHPExcel_Style_Border::BORDER_THIN)
),
),
"borde_todos"=>array(
'borders' => array(
'allborders' => array('style' => \PHPExcel_Style_Border::BORDER_THIN)
),
),
"fila"=> array(
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => "90F39C")
)
),
"fila_2"=> array(
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => "F3F390")
)
),
"fondo_gris"=> array(
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => "F0F0F0")
)
)
];
}
public function traspasarCita(Request $request){
$em=$this->getDoctrine()->getManager();
//calculamos la hora fin de la cita en base a la hora de inicio y duracion
$cita_historico=$em->getRepository("App:CitaHistorico")->find($_POST["id_cita_historico"]);
$fecha= new \DateTime($_POST["dia"]);
$fecha=$fecha->format("Y-m-d");
$hora= date($_POST["hora"]);
$horafin = date('H:i', strtotime($hora.'+'.$cita_historico->getIdtipovehiculo()->getTiempo().' minute'));
//realizamos el inserta en la tabla de citas.
$sql=" INSERT INTO cita (idusuario,matricula,idtipovehiculo,fecha,horainicio,horafin,idtaller,idsubtipovehiculo,factura,fecha_alta,activo) ";
$sql.=" select idusuario,matricula,idtipovehiculo,'".$fecha."','".$hora."','".$horafin."',idtaller,idsubtipovehiculo,factura,NOW(),1 ";
$sql.=" from cita_historico where id= ".$cita_historico->getId();
$stmt= $em->getConnection()->query($sql);
//eliminamos la cita del historico.
$em->remove($cita_historico);
$em->flusH();
$this->get('session')->getFlashBag()->clear();
$this->get('session')->getFlashBag()->add(
'Correcto',
'Cita traspasada correctamente'
);
//reedirigmos al listado de historico de citas.
return $this->redirect($this->generateUrl('historico_citas'));
}
}