- <?php
- /**
-  * Created by PhpStorm.
-  * User: Carlos.Rojas
-  * Date: 18/12/2019
-  * Time: 12:49
-  */
- namespace App\MDS\GreenPatioBundle\Controller;
- use App\Entity\Cities;
- use App\Entity\Client;
- use App\Entity\Country;
- use App\Entity\Regions;
- use App\Entity\SettingsCompany;
- use App\Entity\Supplier;
- use App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceItems;
- use App\MDS\GreenPatioBundle\Entity\Reservation;
- use App\MDS\GreenPatioBundle\Entity\ReservationBudgetItems;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceProformaItems;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRec;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRecItems;
- use App\MDS\GreenPatioBundle\Entity\ReservationPaymentsClient;
- use App\MDS\GreenPatioBundle\Entity\ReservationProforma;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoice;
- use App\MDS\GreenPatioBundle\Entity\ReservationProformaDeposit;
- use App\MDS\GreenPatioBundle\Entity\ReservationTracing;
- use App\MDS\GreenPatioBundle\Form\ReservationPaymentsClientType;
- use App\MDS\GreenPatioBundle\Form\ReservationInvoiceType;
- use Doctrine\ORM\EntityManagerInterface;
- use Symfony\Component\Routing\Annotation\Route;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceDepositItems;
- use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceDepositControl;
- use App\MDS\GreenPatioBundle\Entity\ReservationLounge;
- use App\MDS\GreenPatioBundle\Entity\ReservationLoungeProfile;
- use App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple;
- use App\MDS\GreenPatioBundle\Entity\ReservationService;
- use App\MDS\GreenPatioBundle\Form\ReservationInvoiceDepositItemsType;
- use DateTime;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\Style\Fill;
- use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
- use Symfony\Component\HttpFoundation\ResponseHeaderBag;
- use Symfony\Contracts\Translation\TranslatorInterface;
- class ReservationsInvoiceController extends AbstractController
- {
-     private $translator;
-     public function __construct(TranslatorInterface $translator) {
-         $this->translator = $translator;
-     }
-     
-     /**
-      * @Route("/payment/{id}",  name="reservations_payment")
-      */
-     public function detailsReservationProformaAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $paymentsClient = new ReservationPaymentsClient();
-         $paymentsClient->setReservationId($id);
-         $form = $this->createReservationPaymentsClientForm($paymentsClient);
-         $reserva = $em->getRepository(Reservation::class)->findOneById($id);
-         $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
-         $services = $em->getRepository(ReservationService::class)->findByReservationId($id);
-         $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
-         $form1 = $this->createReservationInvoiceProformaForm($reservaInv);
-         if (!empty($proforma)){
-             $type = 'Proforma';
-             $number = $proforma->getId();
-             $date = $proforma->getDateAt();
-             $prefix = $proforma->getPrefix();
-             $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
-             $token = $data['token'];
-         }else{
-             return $this->redirectToRoute('reservations_generate_proforma',
-                 array(
-                     'id' => $id
-                 )
-             );
-         }
-         $idLounges = array();
-         $loungesBoolToInvoice = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $item) {
-                 $idLounges[] = $item['id'];
-                 $loungesBoolToInvoice[] = 1;
-             }
-             $idLounges = implode(',', $idLounges);
-             $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-         } else {
-             $idLounges = '0';
-             $loungesBoolToInvoice = '0';
-         }
-         $idPayments = array();
-         $paymentsBoolToInvoice = array();
-         if (array_key_exists('payment',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['payment'] as $item) {
-                 $idPayments[] = $item['id'];
-                 $paymentsBoolToInvoice[] = 1;
-             }
-             $idPayments = implode(',', $idPayments);
-             $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-             // Se han generado dos arreglos, cada uno dividido en 2 strings
-             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-             // Para manipularlos entre la vista y el JS
-         } else {
-             $idPayments = '0';
-             $paymentsBoolToInvoice = '0';
-         }
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         //INICIO: Facturas de deposito
-         $allInvoiceDeposit = array();
- //        $allInvoiceDepositControl = $em->getRepository(ReservationInvoiceDepositControl::class)->findByReservationId($id);
- //        foreach($allInvoiceDepositControl as $control){
- //
- //            $items = $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($control->getId());
- //
- //            foreach ($items as $item){
- //                $allInvoiceDeposit[$control->getId()] = array(
- //                    'controlId' => $control->getId(),
- //                    'dateAt' => $control->getDateAt(),
- //                    'itemId' => $item->getId(),
- //                    'name' => $item->getName(),
- //                    'amount' => $item->getAmount(),
- //                    'iva' => $item->getIva(),
- //                    'reservationId' => $item->getReservationId()
- //                );
- //            }
- //        }
-         $items = $em->getRepository(ReservationProformaDeposit::class)->findByReservationId($id);
-         foreach ($items as $item){
-             $allInvoiceDeposit[$item->getId()] = array(
- //                'controlId' => $control->getId(),
- //                'dateAt' => $control->getDateAt(),
-                 'itemId' => $item->getId(),
-                 'name' => $item->getName(),
-                 'amount' => $item->getAmount(),
-                 'iva' => $item->getIva(),
-                 'reservationId' => $item->getReservationId(),
-                 'total' => $item->getTotal()
-             );
-         }
-         //FIN: Facturas de deposito
-         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'idLounges' => $idLounges,
-                 'reserva' => $reserva,
-                 'idPayments' => $idPayments,
-                 'loungesBoolToInvoice' => $loungesBoolToInvoice,
-                 'paymentsBoolToInvoice' => $paymentsBoolToInvoice,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => $token,
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'currency' => $data['currency'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'payments' => $payments,
-                 'allInvoiceDeposit' => $allInvoiceDeposit,
-                 'user_id' => $user_id,
-                 'form' => $form->createView(),
-                 'form1' => $form1->createView(),
-             )
-         );
-     }
-     private function createReservationInvoiceProformaForm(ReservationInvoice $entity)
-     {
-         $form = $this->createForm(ReservationInvoiceType::class, $entity, array(
-             'action' => $this->generateUrl('reservation_proforma_invoice_pdf_print_action'),
-             'method' => 'POST'
-         ));
-         return $form;
-     }
-     private function createReservationPaymentsClientForm(ReservationPaymentsClient $entity)
-     {
-         $form = $this->createForm(ReservationPaymentsClientType::class, $entity, array(
-             'action' => $this->generateUrl('reservation_payments_client_add'),
-             'method' => 'POST'
- //            'method' => 'PUT'
-         ));
-         return $form;
-     }
-     /**
-      * @Route("/payment/delete/{id}",  name="reservations_payment_delete")
-      */
-     public function deleteReservationPaymentAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $payment = $em->getRepository(ReservationPaymentsClient::class)->findOneById($id);
-         $reservationId = $payment->getReservationId();
-         $em->remove($payment);
-         $em->flush();
-         return $this->redirectToRoute('reservations_payment',
-             array(
-                 'id' =>$reservationId
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/payments", name="reservation_payments_client_add")
-      */
-     public function createAction(Request $request)
-     {
-         $paymentsClient = new ReservationPaymentsClient();
-         $form = $this->createReservationPaymentsClientForm($paymentsClient);
-         $form->handleRequest($request);
-         // INICIO: Si la reserva esta facturada no puede ser modificada, no se pueden agregar pagos
-         $em = $this->getDoctrine()->getManager();
-         $tempoReserva = $em->getRepository(Reservation::class)->findOneById($paymentsClient->getReservationId());
-         if ($tempoReserva->getStatus() == 'Invoiced'){
-             return $this->redirectToRoute('reservations_payment',
-                 array('id' => $paymentsClient->getReservationId()));
-         }
-         // FIN: Si la reserva esta facturada no puede ser modificada, no se pueden agregar pagos
-         if($form->isValid())
-         {
-             $em = $this->getDoctrine()->getManager();
-             /* Obtengo usuario logueado */
-             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-             $user_id = $user_logueado->getId();
-             $paymentsClient->setCreatedAt(new \DateTime('now'));
-             $paymentsClient->setCreatedId($user_id);
-             $paymentsClient->setUpdatedId($user_id);
-             $paymentsClient->setUpdatedAt(new \DateTime('now'));
-             /* Gestión de eventos en Log */
-             $user_lastname = $user_logueado->getLastname();
-             $user_name = $user_logueado->getName();
-             $user_email = $user_logueado->getEmail();
-             $user_rol = $user_logueado->getRoles();
-             $event_url = $request->getPathInfo();
-             $event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
-             $em->persist($paymentsClient);
-             $em->flush();
-             $event = 'the payment was registered';
-             $successMessage = $this->translator->trans($event);
-             $this->addFlash('mensajepaymentsclient', $successMessage);
-             $tempoReserva->setStatus('Confirmed');
-             $em->persist($tempoReserva);
-             $em->flush();
-             return $this->redirectToRoute('reservations_payment',
-                 array(
-                     'id' => $paymentsClient->getReservationId()
-                 )
-             );
-         }else{
-             $errorMessage = $this->translator->trans('Error, some fields are empty');
-             $this->addFlash('mensajepaymentsclienterror', $errorMessage);
-         }
-         return $this->redirectToRoute('reservations_payment',
-             array(
-                 'id' => $paymentsClient->getReservationId()
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/proforma/invoice/pdf/print/action", name="reservation_proforma_invoice_pdf_print_action")
-      */
-     public function createProformaInvoicePdfPrintAction(Request $request)
-     {
- //        d('llegue', $request);
-         $array = $request->request->get('mds_greenpatiobundle_reservationsinvoice');
- //        d(
- //            array_keys($array)[0]
- //
- //        );
- //        d($request->request->get('mds_greenpatiobundle_reservationsinvoice'));
- //
- //        exit();
-         $paymentsClient = new ReservationPaymentsClient();
-         $form = $this->createReservationPaymentsClientForm($paymentsClient);
-         $form->handleRequest($request);
-         if($form->isValid())
-         {
-             $em = $this->getDoctrine()->getManager();
-             /* Obtengo usuario logueado */
-             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-             $user_id = $user_logueado->getId();
-             $paymentsClient->setCreatedAt(new \DateTime('now'));
-             $paymentsClient->setCreatedId($user_id);
-             $paymentsClient->setUpdatedId($user_id);
-             $paymentsClient->setUpdatedAt(new \DateTime('now'));
-             /* Gestión de eventos en Log */
-             $user_lastname = $user_logueado->getLastname();
-             $user_name = $user_logueado->getName();
-             $user_email = $user_logueado->getEmail();
-             $user_rol = $user_logueado->getRoles();
-             $event_url = $request->getPathInfo();
-             $event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
-             $em->persist($paymentsClient);
-             $em->flush();
-             $event = 'the payment was registered';
-             $successMessage = $this->translator->trans($event);
-             $this->addFlash('mensajepaymentsclient', $successMessage);
-             return $this->redirectToRoute('reservations_payment',
-                 array(
-                     'id' => $paymentsClient->getReservationId()
-                 )
-             );
-         }else{
-             $errorMessage = $this->translator->trans('Error, some fields are empty');
-             $this->addFlash('mensajepaymentsclienterror', $errorMessage);
-         }
-         return $this->redirectToRoute('reservations_payment',
-             array(
-                 'id' => $paymentsClient->getReservationId()
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/generate/proforma/{id}",  name="reservations_generate_proforma")
-      */
-     public function generateProformaAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-         $prefix = "GP-".date('dmy')."-";
-         if (is_null($proforma)){
-             $proforma_new = new ReservationProforma();
-             $proforma_new->setReservationId($id);
-             $proforma_new->setPrefix($prefix);
-             $proforma_new->setDateAt(new \DateTime("now"));
-             // En items, se ponen todas las salas y pagos de esa reserva
-             $lounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
-             $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
-             $services = $em->getRepository(ReservationService::class)->findByReservationId($id);
-             $items = '';
-             if (!empty($lounges)) {
-                 foreach ($lounges as $item) {
-                     if ($items == ''){
-                         $items = 'L' . $item->getId();  // L## para lounges
-                     } else {
-                         $items = $items . ',' . 'L' . $item->getId();  // L## para lounges
-                     }
-                 }
-             }
-             if (!empty($payments)) {
-                 foreach ($payments as $item) {
-                     if ($items == ''){
-                         $items = 'P' . $item->getId();  // P## para payments
-                     } else {
-                         $items = $items . ',' . 'P' . $item->getId();  // P## para payments
-                     }
-                 }
-             }
-             if (!empty($services)) {
-                 foreach ($services as $item) {
-                     if ($items == ''){
-                         $items = 'S' . $item->getId();  // S## para services
-                     } else {
-                         $items = $items . ',' . 'S' . $item->getId();  // S## para services
-                     }
-                 }
-             }
-             $proforma_new->setItems($items);
-             /* Obtengo usuario logueado */
-             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-             $user_id = $user_logueado->getId();
-             $proforma_new->setCreatedId($user_id);
-             $proforma_new->setUpdatedId($user_id);
-             $proforma_new->setCreatedAt(new \DateTime("now"));
-             $proforma_new->setUpdatedAt(new \DateTime("now"));
-             //Access Key para entrar en la proforma
-             $accessKey = md5('CR-JDEF'. rand() * time());
-             $proforma_new->setAccessKey($accessKey);
-             $em->persist($proforma_new);
-             $em->flush();
-         }
-         return $this->redirectToRoute('reservations_payment',
-             array(
-                 'id' => $id
-             )
-         );
-     }
-     private function baseInvoiceReservation($id, $type, $number, $prefix, $date)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $client[0]->setPopulation($city);
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $client[0]->setRegion($region);
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client[0]->setCountry($country);
-             $client['city'] = $city;
-             $client['region'] = $region;
-             $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Acumuladores de los calculos
-         $totales_neto_all = 0;
-         $data_iva = array(
-             'iva' => 21,
-             'ivaMontoVeintiUno' => 0,
-             'ivaMontoDiez' => 0,
-             'ivaMontoCero' => 0,
-         );
-         // Buscamos las salas reservadas, pagos y servicios para el evento
-         $reservationLounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
-         $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
-         $services = $em->getRepository(ReservationService::class)->findBy(['reservationId' => $id, 'toinvoice' => 1]);
-         $data_supplier = array();
-         $i = 0;
-         $iva = '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre será un 21%". Si tiene un Iva se sustituirá. Modificación en la ley.
-         $pax = '-';
-         $qty = '1';
-         $lounge = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         $service = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         foreach ($reservationLounges as $item){
-             // Verificamos que el salon no se encuentre ya en una factura
-             $existe = $em->getRepository(ReservationInvoiceItems::class)->findByLngControlId($item->getId());
-             $existeCvr = $em->getRepository(CvrReservationInvoiceItems::class)->findByLngControlId($item->getId());
-             $existe = (!empty($existe) or !empty($existeCvr));
-             if (is_null($item->getServicePrice()) or empty($item->getServicePrice()) or !empty($existe)){
-                 $subtotal = 0;
-                 $neto = 0;
-                 $subneto = 0;
-                 $subtotalLounge = 0;
-             } else {
-                 $iva = ($item->getIva() === null || $item->getIva() === '') ? 21 : $item->getIva();
-                 $subtotalLounge = ($item->getServicePrice() * (1 + ($iva / 100)));
-                 $subneto = $item->getServicePrice();
-                 $subtotal =  $subtotalLounge;
-                 $neto =  $subneto;
-                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                 $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                 $neto = round($neto,2,PHP_ROUND_HALF_UP);
-             }
-             // Acumula netos totales e IVA
-             $totales_neto_all = $totales_neto_all + $neto;
-             switch ($iva){
-                 case 21: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
-                 case 10: $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * 0.1); break;
-                 case 0: break;
-                 default: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
-             }
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
-             // Acumula netos totales e IVA
-             $lounge['neto'] = $lounge['neto'] + $neto;
-             $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
-             $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
-             $data_supplier['lounge'][$i] = array (
-                 'id' => $item->getId(),
-                 'loungeName' => $item->getLoungeName(),
-                 'idLounge' => $item->getIdLounge(),
-                 'dateStart' => $item->getDateStart(),
-                 'dateEnd' => $item->getDateEnd(),
-                 'servicePrice' => $item->getServicePrice(),
-                 'subtotalLounge' => $subtotalLounge,
-                 'iva' => $iva,
-                 'pax' => $pax,
-                 'qty' => $qty,
-                 'type' => $item->getType(),
-                 'subtotal' => $subtotal,
-             );
-             $i++;
-         }
-         $data_supplier['loungeSubTotal'] = array(
-             'neto' => $lounge['neto'],
-             'sumSubT' => $lounge['sumSubT'],
-         );
-         $payment = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         $i = 0;
-         foreach ($payments as $item){
-             // Verificamos que el pago no se encuentre ya en una factura
-             $existe = $em->getRepository(ReservationInvoiceItems::class)->findByPayControlId($item->getId());
-             $existeCvr = $em->getRepository(CvrReservationInvoiceItems::class)->findByPayControlId($item->getId());
-             $existe = (!empty($existe) or !empty($existeCvr));
-             // Por indicaciones de Esteban Rincon, no deseamos estos conceptos en las facturas
-             if (!($item->getWayToPay() == 'TRANSFERENCIA') and !($item->getWayToPay() == 'VISA') and !($item->getWayToPay() == 'AMEX') and !($item->getWayToPay() == 'CHEQUE') and !($item->getWayToPay() == 'EFECTIVO')) {
-                 if (!empty($existe)) {
-                     $payment['sumSubT'] = $payment['sumSubT'] + 0;
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
-                 } else {
-                     $subtotalLounge = $item->getAmountTotal() * (-1);
-                     $subneto = $item->getAmount() * (-1);
-                     $subtotal = $subtotalLounge;
-                     $neto = $subneto;
-                     $payment['sumSubT'] = $payment['sumSubT'] - $item->getAmountTotal();
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
-                     // Acumula netos totales e IVA
-                     $ivaPayment = $item->getVat();
-                     if (empty($item->getVat()) && !is_numeric($item->getVat())) {
-                         $ivaPayment = 21;
-                     }
-                     $totales_neto_all = $totales_neto_all + $neto;
-                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($ivaPayment / 100));
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $totales_neto_all = round($totales_neto_all, 2, PHP_ROUND_HALF_UP);
-                     $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2, PHP_ROUND_HALF_UP);
-                     // Acumula netos totales e IVA
-                 }
-                 $data_supplier['payment'][$i] = array(
-                     'id' => $item->getId(),
-                     'amount' => $item->getAmount() * (-1),
-                     'datePayAt' => $item->getDatePayAt(),
-                     'wayToPay' => $item->getWayToPay(),
-                     'amountTotal' => $item->getAmountTotal() * (-1),
-                     'vat' => $item->getVat(),
-                 );
-                 $i++;
-             }
-         }
-         if (!empty($payments)) {
-             $data_supplier['paymentSubTotal'] = array(
-                 'neto' => $payment['neto'],
-                 'sumSubT' => $payment['sumSubT'],
-             );
-         }
-         // Mapeo de serviceCatId a serviceType
-         $serviceTypes = [
-             1 => 'Hotel',
-             2 => 'Actividad',
-             3 => 'AV',
-             4 => 'Creativo',
-             5 => 'Crucero',
-             6 => 'Entretenimiento',
-             7 => 'Regalos',
-             8 => 'Guía',
-             9 => 'Itinerarios',
-             11 => 'Catering',
-             12 => 'Otros',
-             13 => 'Transporte',
-             14 => 'Tecnología',
-             15 => 'Asistente',
-             16 => 'DDR',
-             17 => 'Seguridad',
-             18 => 'WiFi',
-             19 => 'Mobiliario',
-             20 => 'Parking',
-             21 => 'Limpieza',
-             // Agrega más mapeos según sea necesario
-         ];
-         $i = 0;
-         foreach ($services as $item) {
-             // Verificar si el servicio ya existe en una factura
-             $existe = !empty($em->getRepository(ReservationInvoiceItems::class)->findBySrvControlId($item->getId())) ||
-                     !empty($em->getRepository(CvrReservationInvoiceItems::class)->findBySrvControlId($item->getId()));
-             // Inicializar variables comunes
-             $pax = max(1, (int)$item->getPax());
-             $unitsServ = max(1, (int)$item->getUnits());
-             $dateIn = $item->getDateInAt();
-             $dateOut = $item->getDateOutAt();
-             $days = ($item->getServiceCatId() == 5) ? $dateIn->diff($dateOut)->days : ($dateIn->diff($dateOut)->days + 1);
-             $dateServ = ($days > 1) ? $dateIn->format('d/m/Y') . ' - ' . $dateOut->format('d/m/Y') : $dateIn->format('d/m/Y');
-             // Obtener el tipo de servicio
-             $serviceCatId = $item->getServiceCatId();
-             $serviceType = isset($serviceTypes[$serviceCatId]) ? $serviceTypes[$serviceCatId] : 'Otros';
-             // Determinar si se usa precio del item o se calcula
-             if (is_null($item->getPrice()) || empty($item->getPrice()) || $existe) {
-                 $subtotalService = 0;
-                 $subneto = 0;
-                 if ($serviceCatId == 1) { // Alojamiento
-                     $numNoches = $dateIn->diff($dateOut)->days;
-                     $subtotalService = $subtotalService * $numNoches * $unitsServ;
-                     $subnetoUnit = $subneto;
-                     $subneto = $subneto * $numNoches * $unitsServ;
-                 } else {
-                     // Para otras categorías, se asume la misma lógica base
-                     $subtotalService = 0;
-                     $subneto = 0;
-                 }
-                 // Configurar datos del proveedor
-                 $data_supplier['service'][$i] = [
-                     'id' => $item->getId(),
-                     'serviceCatId' => $serviceCatId,
-                     'serviceName' => $item->getName(),
-                     'serviceType' => $serviceType,
-                     'date' => $dateServ,
-                     'qty' => $unitsServ,
-                     'iva' => $item->getIva(),
-                     'pax' => ($serviceCatId == 1) ? '-' : $pax,
-                     'precioUnit' => isset($subnetoUnit) ? $subnetoUnit : 0,
-                     'subneto' => $subneto,
-                     'subtotal' => $subtotalService,
-                 ];
-             } else {
-                 // Calcular subtotalService y subneto basado en el precio del item
- //                $subtotalService = (float)$item->getPrice();
- //                $subneto = (float)$item->getPrice();
-                 // Aplicar comisiónº
- //                $comTemp = $item->getCommission();
- //                if ($item->getOpCommission() == '1') {
- //                    $subtotalService *= (1 + ((float)($comTemp) / 100));
- //                    $subneto *= (1 + ((float)($comTemp) / 100));
- //                } else {
- //                    $subtotalService *= (1 - ((float)($comTemp) / 100));
- //                    $subneto *= (1 - ((float)($comTemp) / 100));
- //                }
-                 // Manejar Comision y Over en precio unitario
-                 $priceExtra = (float)$item->getPrice();
-                 $commissionExtra = (float)$item->getCommission();
-                 $subnetoUnitExtra = ($item->getOpCommission() == '1')
-                     ? ($priceExtra + ($priceExtra * $commissionExtra / 100))
-                     : ($priceExtra - ($priceExtra * $commissionExtra / 100));
-                 $subnetoUnitExtra = ($item->getOpOver() == '1') ? ($subnetoUnitExtra + $item->getOver()) : ($subnetoUnitExtra - $item->getOver());
-                 $subneto = $subnetoUnitExtra;
-                 $subtotalService = $subnetoUnitExtra;
-                 // Calcular subtotal y subneto según la categoría de servicio
-                 switch ($serviceCatId) {
-                     case 1: // Alojamiento
-                         $numNoches = $dateIn->diff($dateOut)->days;
-                         $subtotalService *= $numNoches * $unitsServ;
-                         $subnetoUnit = $subneto;
-                         $subneto *= $numNoches * $unitsServ;
-                         break;
-                     case 2: // Actividades
-                         $subtotalService *= $days * $unitsServ;
-                         $subnetoUnit = $subneto;
-                         $subneto *= $days * $unitsServ;
-                         break;
-                     // Agrega más casos según las necesidades específicas de cada categoría
-                     default:
-                         $subtotalService *= $days * $unitsServ * $pax;
-                         $subnetoUnit = $subneto;
-                         $subneto *= $days * $unitsServ * $pax;
-                         break;
-                 }
-                 // Actualizar datos del proveedor
-                 $data_supplier['service'][$i] = [
-                     'id' => $item->getId(),
-                     'serviceCatId' => $serviceCatId,
-                     'serviceName' => $item->getName(),
-                     'serviceType' => $serviceType,
-                     'date' => $dateServ,
-                     'qty' => $unitsServ,
-                     'iva' => $item->getIva(),
-                     'pax' => ($serviceCatId == 1) ? '-' : $pax,
- //                    'precioUnit' => $subnetoUnit ?? 0,
-                     'precioUnit' => $subnetoUnitExtra,
-                     'subneto' => $subneto,
-                     'subtotal' => $subtotalService,
-                 ];
-                 // Manejar Over
- //                if ($item->getOpOver() == '1') {
- //                    $subtotalService += $item->getOver();
- //                    $subneto += $item->getOver();
- //                } else {
- //                    $subtotalService -= $item->getOver();
- //                    $subneto -= $item->getOver();
- //                }
-                 // Aplicar IVA
-                 if ($item->getOpIva() == '1') {
-                     $subtotalService *= (1 + ($item->getIva() / 100));
-                 } else {
-                     $subtotalService = ($item->getPrice() * 100) / (100 + $item->getIva());
-                     $subneto = ($subneto * 100) / (100 + $item->getIva());
-                 }
-                 // Actualizar subtotal y subneto en data_supplier
-                 $data_supplier['service'][$i]['subneto'] = $subneto;
-                 $data_supplier['service'][$i]['subtotal'] = $subtotalService;
-                 // Acumular subtotales
-                 $subtotal = round($subtotalService, 2, PHP_ROUND_HALF_UP);
-                 $neto = round($subneto, 2, PHP_ROUND_HALF_UP);
-             }
-             // Acumular IVA
-             switch ($item->getIva()) {
-                 case 21:
-                     $data_iva['ivaMontoVeintiUno'] += ($neto * 0.21);
-                     break;
-                 case 10:
-                     $data_iva['ivaMontoDiez'] += ($neto * 0.10);
-                     break;
-                 case 0:
-                     // No se acumula IVA
-                     break;
-                 default:
-                     $data_iva['ivaMontoVeintiUno'] += ($neto * ($item->getIva() / 100));
-                     break;
-             }
-             // Acumular totales netos
-             $totales_neto_all += $neto;
-             $totales_neto_all = round($totales_neto_all, 2, PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2, PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'], 2, PHP_ROUND_HALF_UP);
-             // Acumular en la estructura de servicios
-             $service['neto'] = round(($service['neto'] ?? 0) + $neto, 2, PHP_ROUND_HALF_UP);
-             $service['sumSubT'] = round(($service['sumSubT'] ?? 0) + $subtotal, 2, PHP_ROUND_HALF_UP);
-             $i++;
-         }
-         $data_supplier['serviceSubTotal'] = array(
-             'neto' => $service['neto'],
-             'sumSubT' => $service['sumSubT'],
-         );
-         $currency = '€';
-         $totales_total = $totales_neto_all + $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
-         if (!empty($payments)) {
-             $amount_pay = $data_supplier['paymentSubTotal']['sumSubT'];
-         } else {
-             $amount_pay = 0;
-         }
-         $totales_all = $totales_total - $amount_pay;
-         $data = array(
-             'id' => $id,
-             'type' => $type,
-             'number' => $number,
-             'prefix' => $prefix,
-             'date' => $date,
-             'reservation' => $reservation,
-             'token' => $reservation->getAccessKey(),
-             'company' => $company,
-             'clients' => $client,
-             'datasupplier' => $data_supplier,
-             'currency' => $currency,
-             'totales_neto' => $totales_neto_all,
-             'bases_imponibles' => $data_iva,
-             'totales' => $totales_total,
-             'balance' => $totales_all,
-             'paymentInvoice' => $amount_pay,
-         );
-         return $data;
-     }
-     /**
-      * @Route("/reservations/invoice/proforma/print/{id}",  name="reservations_invoice_proforma_print")
-      */
-     public function detailsProformaPrintAction($id, Request $request)
-     {
-         $data = array();
-         $em = $this->getDoctrine()->getManager();
-         $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-         if (!empty($proforma)){
-             $type = 'Proforma';
-             $number = $proforma->getId();
-             $date = $proforma->getDateAt();
-             $prefix = $proforma->getPrefix();
-             $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
-             $token = $data['token'];
-         }else{
-             return $this->redirectToRoute('reservations_generate_proforma',
-                 array(
-                     'id' => $id
-                 )
-             );
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-print-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => $token,
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'currency' => $data['currency'],
-                 'paymentInvoice' => $data['paymentInvoice']
-             )
-         );
-     }
-     /**
-      * @Route("/invoice/{id}",  name="reservations_invoice")
-      */
-     public function detailsReservationInvoiceAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
- ////        $services = $em->getRepository(ReservationService::class)->findByReservationId($id);     // ********************************************** PENDIENTE POR PROGRAMAR EL CALCULO DE CADA TIPO DE SERVICIO PARA LA FACTURA **********************************************
- //        $invoice = $em->getRepository(ReservationInvoice::class)->findOneByReservationId($id);
-         $invoice = $em->getRepository(ReservationInvoice::class)->findOneBy(
-             array(
-                 'reservationId' => $id,
-                 'master' => 'master',
-             )
-         );
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
-         $form1 = $this->createReservationInvoiceProformaForm($reservaInv);
-         if (!empty($invoice)){
-             $type = 'Invoice';
-             $number = $invoice->getId();
-             $date = $invoice->getDateAt();
-             $prefix = $invoice->getPrefix();
-             $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
-             $token = $data['token'];
-         }else{
-             // No hay factura creada se debe enviar a proforma, si es un ADMIN podra generar la factura. Tal vez sea necesario poner un mensaje indicando que no hay factura generada aun
-             return $this->redirectToRoute('reservations_generate_proforma',
-                 array(
-                     'id' => $id
-                 )
-             );
-         }
-         $idLounges = array();
-         $loungesBoolToInvoice = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $item) {
-                 $idLounges[] = $item['id'];
-                 $loungesBoolToInvoice[] = 1;
-             }
-             $idLounges = implode(',', $idLounges);
-             $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-         } else {
-             $idLounges = '0';
-             $loungesBoolToInvoice = '0';
-         }
-         $idPayments = array();
-         $paymentsBoolToInvoice = array();
-         if (array_key_exists('payment',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['payment'] as $item) {
-                 $idPayments[] = $item['id'];
-                 $paymentsBoolToInvoice[] = 1;
-             }
-             $idPayments = implode(',', $idPayments);
-             $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-             // Se han generado dos arreglos, cada uno dividido en 2 strings
-             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-             // Para manipularlos entre la vista y el JS
-         } else {
-             $idPayments = '';
-             $paymentsBoolToInvoice = '';
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'idLounges' => $idLounges,
-                 'idPayments' => $idPayments,
-                 'loungesBoolToInvoice' => $loungesBoolToInvoice,
-                 'paymentsBoolToInvoice' => $paymentsBoolToInvoice,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => $token,
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'currency' => $data['currency'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'payments' => $payments,
-                 'form1' => $form1->createView(),
-                 'clientName' => $invoice->getClientName(),
-                 'clientAddress' => $invoice->getClientAddress(),
-                 'clientDocument' => $invoice->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/print/{id}",  name="reservations_invoice_print")
-      */
-     public function detailsInvoicePrintAction($id, Request $request)
-     {
-         $data = array();
-         $em = $this->getDoctrine()->getManager();
-         $invoice = $em->getRepository(ReservationInvoice::class)->findOneByReservationId($id);
-         if (!empty($invoice)){
-             $type = 'Invoice';
-             $number = $invoice->getId();
-             $date = $invoice->getDateAt();
-             $prefix = $invoice->getPrefix();
-             $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
-             $token = $data['token'];
-         }else{
-             return $this->redirectToRoute('reservations_generate_invoice',
-                 array(
-                     'id' => $id
-                 )
-             );
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-print-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => $token,
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'currency' => $data['currency'],
-                 'paymentInvoice' => $data['paymentInvoice']
-             )
-         );
-     }
-     /**
-      * @Route("/invoice/generate/{id}",  name="reservations_generate_invoice")
-      */
-     public function generateInvoiceAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $invoiceGenerate = $request->request->get('invoiceGenerate');
-         $invoice = $em->getRepository(ReservationInvoice::class)->findOneBy(
-             array(
-                 'reservationId' => $id,
-                 'master' => 'master',
-             )
-         );
-         if (is_null($invoice)){
-             $reserva = $em->getRepository(Reservation::class)->findOneById($id);
-             $pagos = $em->getRepository(ReservationPaymentsClient::class)->findOneByReservationId($id);
-             $servicios = $em->getRepository(ReservationService::class)->findOneByReservationId($id);
-             $salas = $em->getRepository(ReservationLounge::class)->findOneByIdReservation($id);
- //
- //  Aqui se deberia verificar que pagos, salas o servicios, al menos uno sea distinto de null. En caso contrario no hay nada que facturar
- //            if (empty($pagos) and empty($servicios) and empty($salas)){
- //                d('factura vacia');
- //            }
- //
- //
- //
- //
-             $reserva->setStatus('Invoiced');
-             $em->persist($reserva);
-             $em->flush();
-             $invoice_new = new ReservationInvoice();
-             $invoice_new->setNumber('GPF-'.date('d').date('m').substr(date('Y'),-2).'-'.$id);           //GreenPatioFactura - dia mes año idReserva
-             $invoice_new->setDateAt(new \DateTime());
-             $invoice_new->setType($invoiceGenerate['type']);
-             $invoice_new->setReservationId($invoiceGenerate['id']);
-             $invoice_new->setReservationId($id);
-             $invoice_new->setPrefix('');
-             $invoice_new->setType('Invoice');
-             $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-             $type = 'Invoice';
-             $number = $proforma->getId();
-             $date = $proforma->getDateAt();
-             $prefix = $proforma->getPrefix();
-             $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
-             $em->clear();
-             $invoice_new->setTotal($data['totales']);
-             $invoice_new->setTotalNet($data['totales_neto']);
-             $invoice_new->setVat($data['totales'] - $data['totales_neto']);
-             /* Obtengo usuario logueado */
-             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-             $user_id = $user_logueado->getId();
-             $invoice_new->setCreatedId($user_id);
-             $invoice_new->setUpdatedId($user_id);
-             $invoice_new->setCreatedAt(new \DateTime());
-             $invoice_new->setUpdatedAt(new \DateTime());
-             // Guardamos los datos del cliente dentro de la factura
-             $typeClient = $request->request->get('typeClient');
-             $typeClient = empty($typeClient) ? 'Client' : $typeClient;
-             $idClient = $request->request->get('idClient');
-             $idClient = empty($idClient) ? $reserva->getClient() : $idClient;
-             $invoice_new = $this->clientDataToInvoice($invoice_new, $typeClient, $idClient, $invoice_new->getReservationId());
-             $em->persist($invoice_new);
-             $em->flush();
-         }
-         return $this->redirectToRoute('reservations_invoice', array( 'id' => $id ));
-     }
-     /**
-      * @Route("/reservations/invoice/generatenew",  name="reservations_generatenew_invoice")
-      * Generar una nueva factura
-      */
-     public function generatenewInvoiceAction( EntityManagerInterface $em, Request $request )
-     {
-         // Se genera y muestra en nueva pantalla la nueva proforma
-         $arrayBools = array( 'lounge' => null, 'service' => null, 'payment' => null, );
-         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
-         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
-         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
-         $clientName = $request->request->get('clientName');
-         $clientAddress = $request->request->get('clientAddress');
-         $clientDocument = $request->request->get('clientDocument');
-         $clientType = $request->request->get('clientType');
-         $id = $request->request->get('inv_reservation_id');
-         // INICIO: Verificamos la linea de facturacion
-         $parameters = array('id' => $id);
-         $dql = 'SELECT p
-         FROM GreenPatioBundle:ReservationLoungeSimple p
-         WHERE p.idReservation = :id AND p.idLounge > 21';
-         $query = $em->createQuery($dql)->setParameters($parameters);
-         $loungesSimples = $query->getResult();
-         if (!empty($loungesSimples)) {
-             $idLounge = $loungesSimples[0]->getIdLounge();
-             if ($idLounge >= 22 && $idLounge <= 29) {
-                 $route = 'reservations_generatenew_invoice_cvr';
-             } elseif ($idLounge > 29) {
-                 $route = 'reservations_generatenew_invoice_blv';
-             } else {
-                 $route = null;
-             }
-             if ($route !== null) {
-                 return $this->redirectToRoute($route, array(
-                     'id' => $id,
-                     'lounge' => $arrayBools['lounge'],
-                     'service' => $arrayBools['service'],
-                     'payment' => $arrayBools['payment'],
-                     'clientName' => $clientName,
-                     'clientAddress' => $clientAddress,
-                     'clientDocument' => $clientDocument,
-                     'clientType' => $clientType
-                 ));
-             }
-         }
-         // FIN: Verificamos la linea de facturacion
-         //INICIO: buscamos el ID de la factura
-         $allFacturas = $em->getRepository(ReservationInvoice::class)->findAll();
-         if (!empty($allFacturas)){
-             $invoiceId = end($allFacturas)->getId() + 1;
-         } else {
-             $invoiceId = 1;
-         }
-         $boolMakeInvoice = false;  // Control para verificar si se debe hacer factura o todos los indicadores (sala, servicios y pagos) estaban en falso
-         //FIN: buscamos el ID de la factura
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         //Acumuladores de datos globales de la factura
-         $valorTotalNet = 0;
-         $valorVat = 0;
-         //INICIO: Creamos los items de la factura
-         if (!empty($arrayBools['lounge'])) {
-             foreach ($arrayBools['lounge'] as $key => $item) {
-                 if ($item == 'true') {
-                     $boolMakeInvoice = true;
-                     $sala = $em->getRepository(ReservationLoungeSimple::class)->findOneById($key);
-                     $itemInvoice = new ReservationInvoiceItems();
-                     $itemInvoice->setReservationId($id);
-                     $itemInvoice->setInvoiceId($invoiceId);
-                     $itemInvoice->setItemType('LOUNGE');
-                     $itemInvoice->setLngControlId($key);
-                     $itemInvoice->setLngLoungeName($sala->getLoungeName());
-                     $itemInvoice->setLngIdLounge($sala->getIdLounge());
-                     $itemInvoice->setLngIdLounge($sala->getIdLounge());
-                     $itemInvoice->setLngDateStart($sala->getDateStart());
-                     $itemInvoice->setLngDateEnd($sala->getDateEnd());
-                     $itemInvoice->setLngServicePrice($sala->getServicePrice());
-                     $itemInvoice->setLngPax($sala->getPax());
-                     $itemInvoice->setLngType($sala->getType());
-                     $itemInvoice->setLngIva($sala->getIva() ?? 21);
-                     $itemInvoice->setLngOpIva($sala->getOpIva());
-                     $itemInvoice->setCreatedId($user_id);
-                     $itemInvoice->setCreatedAt(new DateTime('now'));
-                     $itemInvoice->setUpdatedId($user_id);
-                     $itemInvoice->setUpdatedAt(new DateTime('now'));
-                     $itemInvoice->setLngHourStart($sala->getHourStart());
-                     $itemInvoice->setLngMinStart($sala->getMinStart());
-                     $itemInvoice->setLngHourEnd($sala->getHourEnd());
-                     $itemInvoice->setLngMinEnd($sala->getMinEnd());
-                     $em->persist($itemInvoice);
-                     $em->flush();
-                     //Acumulamos neto e iva para la factura
-                     $valorTotalNet += $itemInvoice->getLngServicePrice();
-                     $valorVat += round(($itemInvoice->getLngServicePrice() * ($itemInvoice->getLngIva() / 100)),2,PHP_ROUND_HALF_UP);
-                 }
-             }
-         }
-         if (!empty($arrayBools['service'])) {
-             foreach ($arrayBools['service'] as $key => $item) {
-                 if ($item == 'true') {
-                     $boolMakeInvoice = true;
-                     $servicio = $em->getRepository(ReservationService::class)->findOneById($key);
-                     $itemInvoice = new ReservationInvoiceItems();
-                     $itemInvoice->setReservationId($id);
-                     $itemInvoice->setInvoiceId($invoiceId);
-                     $itemInvoice->setItemType('SERVICE');
-                     $itemInvoice->setSrvControlId($key);
-                     $itemInvoice->setSrvName($servicio->getName());
-                     $itemInvoice->setSrvSupplierId($servicio->getSupplierId());
-                     $itemInvoice->setSrvServiceId($servicio->getServiceId());
-                     $itemInvoice->setSrvServiceCatId($servicio->getServiceCatId());
-                     $itemInvoice->setSrvServiceCatName($servicio->getServiceCatName());
-                     $itemInvoice->setSrvPrice($servicio->getPrice());
-                     $itemInvoice->setSrvCurrency($servicio->getCurrency());
-                     $itemInvoice->setSrvUnits($servicio->getUnits());
-                     $itemInvoice->setSrvOpCommission($servicio->getOpCommission());
-                     $itemInvoice->setSrvCommission($servicio->getCommission());
-                     $itemInvoice->setSrvOpOver($servicio->getOpOver());
-                     $itemInvoice->setSrvOver($servicio->getOver());
-                     $itemInvoice->setSrvOpIva($servicio->getOpIva());
-                     $itemInvoice->setSrvIva($servicio->getIva());
-                     $itemInvoice->setSrvPax($servicio->getPax());
-                     $itemInvoice->setSrvHour($servicio->getHour());
-                     $itemInvoice->setSrvDateInAt($servicio->getDateInAt());
-                     $itemInvoice->setSrvDateOutAt($servicio->getDateOutAt());
-                     $itemInvoice->setSrvContcolor($servicio->getContcolor());
-                     $itemInvoice->setSrvRank($servicio->getRank());
-                     $itemInvoice->setSrvAssistantId($servicio->getAssistantId());
-                     $itemInvoice->setSrvActivityId($servicio->getActivityId());
-                     $itemInvoice->setSrvPay($servicio->getPay());
-                     $itemInvoice->setCreatedAt(new DateTime('now'));
-                     $itemInvoice->setUpdatedAt(new DateTime('now'));
-                     $itemInvoice->setCreatedId($user_id);
-                     $itemInvoice->setUpdatedId($user_id);
-                     $em->persist($itemInvoice);
-                     $em->flush();
-                     //Acumulamos neto e iva para la factura
-                     if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
-                         $subtotal = 0;
-                         $neto = 0;
-                         $subtotalService = 0;
-                     } else {
-                         $subtotalService = (float)$itemInvoice->getSrvPrice();
-                         $subneto = (float)$itemInvoice->getSrvPrice();
-                         // Commission
-                         if ($itemInvoice->getSrvOpCommission()=='1'){
-                             $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvCommission()/100));
-                             $subneto = $subneto  * (1 + ($itemInvoice->getSrvCommission()/100));
-                         } else {
-                             $subtotalService = $subtotalService * (1 - ($itemInvoice->getSrvCommission()/100));
-                             $subneto = $subneto * (1 - ($itemInvoice->getSrvCommission()/100));
-                         }
-                         // Over
-                         if ($itemInvoice->getSrvOpOver()=='1'){
-                             $subtotalService = $subtotalService + $itemInvoice->getSrvOver();
-                             $subneto = $subneto + $itemInvoice->getSrvOver();
-                         } else {
-                             $subtotalService = $subtotalService - $itemInvoice->getSrvOver();
-                             $subneto = $subneto - $itemInvoice->getSrvOver();
-                         }
-                         // IVA
-                         if ($itemInvoice->getSrvOpIva()=='1'){
-                             $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvIva()/100));
-                         } else {
-                             $subtotalService = $itemInvoice->getSrvPrice();
-                             $subneto = ($subneto * 100) / (100 + $itemInvoice->getSrvIva());
-                         }
-                         switch ($itemInvoice->getSrvServiceCatId()){
-                             case 1: // Alojamiento
-                                 // el numero de noches $numNoches; precio unitario $subneto
-                                 $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
-                                 // La personas no afectan este calculo
-                                 $subtotal = $subtotalService * $numNoches * $itemInvoice->getSrvUnits();
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $numNoches * $itemInvoice->getSrvUnits();
-                                 break;
-                             case 2: //Actividades
-                                 // El número de personas es considerado en el calculo
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $subtotal = $subtotalService * $days * $itemInvoice->getSrvUnits();
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $itemInvoice->getSrvUnits();
-                                 break;
-                             case 3: // AV
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 4: //Creative
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 5: //Cruise
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 6: //Entertaiment
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 7: // Gifts
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = 1;
-                                 $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 8: //Guide
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 9: //Itineraries
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 10: //Lounge  -- No Aplica
-                                 break;
-                             case 11: //Menu (Catering)
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 12: //Others
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                  $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 13: //Transport
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 14: //Technology
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = 1;
-                                 $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 15: //Assisstant
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 16: //DDR
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 17: //Seguridad
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 18: //WiFi
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 19: //Mobiliario
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 20: //Parking
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 21: //Limpieza
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             default: //Others (por default)
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") { $pax = 1; }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                         }
-                         // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                         $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                         $neto = round($subneto,2,PHP_ROUND_HALF_UP);
-                         $valorTotalNet = $valorTotalNet + $neto;
-                         $valorVat = $valorVat + ($subtotal - $neto);
-                     }
-                 }
-             }
-         }
-         if (!empty($arrayBools['payment'])) {
-             foreach ($arrayBools['payment'] as $key => $item) {
-                 if ($item == 'true') {
-                     $boolMakeInvoice = true;
-                     $pago = $em->getRepository(ReservationPaymentsClient::class)->findOneById($key);
-                     $itemInvoice = new ReservationInvoiceItems();
-                     $itemInvoice->setReservationId($id);
-                     $itemInvoice->setInvoiceId($invoiceId);
-                     $itemInvoice->setItemType('PAYMENT');
-                     $itemInvoice->setPayControlId($key);
-                     $itemInvoice->setPayAmount($pago->getAmount());
-                     $itemInvoice->setPayVat($pago->getVat());
-                     $itemInvoice->setPayAmountTotal($pago->getAmountTotal());
-                     $itemInvoice->setPayDatePayAt($pago->getDatePayAt());
-                     $itemInvoice->setPayWayToPay($pago->getWayToPay());
-                     $itemInvoice->setCreatedAt(new DateTime('now'));
-                     $itemInvoice->setUpdatedAt(new DateTime('now'));
-                     $itemInvoice->setCreatedId($user_id);
-                     $itemInvoice->setUpdatedId($user_id);
-                     $em->persist($itemInvoice);
-                     $em->flush();
-                     //Acumulamos neto e iva para la factura
-                     //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
-                     $valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();
-                     $valorVat = $valorVat - round(($itemInvoice->getPayAmount() * 0.21),2,PHP_ROUND_HALF_UP);
-                 }
-             }
-         }
-         //FIN: Creamos los items de la factura
-         $valorTotal = $valorTotalNet + $valorVat;
-         //INICIO: Creamos la factura
-         $newInvoice = new ReservationInvoice();
-         $newInvoice->setNumber("GPF-".date('dmy')."-".$id);
-         $newInvoice->setDateAt(new DateTime('now'));
-         $newInvoice->setType('Invoice');
-         $newInvoice->setReservationId($id);
-         $newInvoice->setTotalNet($valorTotalNet);
-         $newInvoice->setVat($valorVat);
-         $newInvoice->setTotal($valorTotal);
-         $newInvoice->setCreatedAt(new DateTime('now'));
-         $newInvoice->setCreatedId($user_id);
-         $newInvoice->setUpdatedAt(new DateTime('now'));
-         $newInvoice->setUpdatedId($user_id);
-         $newInvoice->setMaster('master');
-         $newInvoice->setClientName($clientName);
-         $newInvoice->setClientAddress($clientAddress);
-         $newInvoice->setClientDocument($clientDocument);
-         $newInvoice->setClientType($clientType);
-         if ($boolMakeInvoice){
-             // Solo se debe crear factura si hay un elemento
-             $em->persist($newInvoice);
-             $em->flush();
-             $newInvoice->setNumber($newInvoice->getNumber().'-'.$newInvoice->getId());
-             $em->persist($newInvoice);
-             $em->flush();
-         } else {
-             // Se llama a la vista de facturas del expediente
-             return $this->redirectToRoute('reservations_viewreservation_invoices',array('id' => $id));
-         }
-         //FIN: Creamos la factura
-         $paymentsClient = new ReservationPaymentsClient();
-         $paymentsClient->setReservationId($id);
-         $reserva = $em->getRepository(Reservation::class)->findOneById($id);
-         if ($boolMakeInvoice){
-             // Si se creo la factura se cambia el estado de la reserva a Facturado
-             $reserva->setStatus('Invoiced');
-             $em->persist($reserva);
-             $em->flush();
-         }
-         return $this->redirectToRoute('reservations_viewnew_invoice',array('id' => $newInvoice->getId()));
-     }
-     /**
-      * @Route("/reservations/invoice/generatenewproforma",  name="reservations_generatenew_proforma")
-      */
-     public function generatenewProformaAction(Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         // Se genera y muestra en nueva pantalla la nueva proforma
-         $arrayBools = array(
-             'lounge' => null,
-             'service' => null,
-             'payment' => null,
-         );
-         $arrayBools['lounge'] = $request->request->get('lounge_hidden_bool');
-         $arrayBools['service'] = $request->request->get('service_hidden_bool');
-         $arrayBools['payment'] = $request->request->get('payment_hidden_bool');
-         $id = $request->request->get('reservation_id');
-         $proforma_number = $request->request->get('proforma_number');
-         $boolMakeInvoice = false;  // Control para verificar si se debe hacer (PROFORMA) o todos los indicadores (sala, servicios y pagos) estaban en falso
-         //FIN: buscamos el ID de la factura
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         //INICIO: Creamos los items de la proforma
-         if (!empty($arrayBools['lounge'])) {
-             foreach ($arrayBools['lounge'] as $key => $item) {
-                 if ($item == 'true') {
-                     $boolMakeInvoice = true;
-                     $sala = $em->getRepository(ReservationLoungeSimple::class)->findOneById($key);
-                     $itemProforma = new ReservationInvoiceProformaItems();
-                     $itemProforma->setType('LOUNGE');
-                     $itemProforma->setReservationId($id);
-                     $itemProforma->setProformaId($proforma_number);
-                     $itemProforma->setControlId($key);
-                     $em->persist($itemProforma);
-                     $em->flush();
-                 }
-             }
-         }
-         if (!empty($arrayBools['service'])) {
-             foreach ($arrayBools['service'] as $key => $item) {
-                 if ($item === 'true') {
-                     $boolMakeInvoice = true;
-                     $servicio = $em->getRepository(ReservationService::class)->findOneById($key);
-             
-                     // Creación y persistencia del ítem proforma
-                     $itemProforma = new ReservationInvoiceProformaItems();
-                     $itemProforma->setType('SERVICE')
-                                  ->setReservationId($id)
-                                  ->setProformaId($proforma_number)
-                                  ->setControlId($key);
-                     $em->persist($itemProforma);
-                     $em->flush();
-                 }
-             }
-         }
-         if (!empty($arrayBools['payment'])) {
-             foreach ($arrayBools['payment'] as $key => $item) {
-                 if ($item == 'true') {
-                     $boolMakeInvoice = true;
-                     $itemProforma = new ReservationInvoiceProformaItems();
-                     $itemProforma->setType('PAYMENT');
-                     $itemProforma->setReservationId($id);
-                     $itemProforma->setProformaId($proforma_number);
-                     $itemProforma->setControlId($key);
-                     $em->persist($itemProforma);
-                     $em->flush();
-                 }
-             }
-         }
-         //FIN: Creamos los items de la proforma
-         //INICIO: Creamos la proforma
-         $newProforma = new ReservationProforma();
-         $newProforma->setPrefix("GPP-".date('dmy')."-".$id);
-         $newProforma->setDateAt(new DateTime('now'));
-         $newProforma->setReservationId($id);
-         $newProforma->setCreatedAt(new DateTime('now'));
-         $newProforma->setCreatedId($user_id);
-         $newProforma->setUpdatedAt(new DateTime('now'));
-         $newProforma->setUpdatedId($user_id);
-         $newProforma->setItems(null);
-         $newProforma->setAccessKey(null);
-         if ($boolMakeInvoice){
-             // Solo se debe crear factura si hay un elemento
-             $em->persist($newProforma);
-             $em->flush();
-         } else {
-             // Se llama a la vista de facturas del expediente
-             return $this->redirectToRoute('reservations_viewreservation_proformas',array('id' => $id));
-         }
-         //FIN: Creamos la proforma
-         return $this->redirectToRoute('reservations_viewnew_proforma',array('id' => $newProforma->getId()));
-     }
-     /**
-      * @Route("/reservations/invoice/viewnew/{id}",  name="reservations_viewnew_invoice")
-      */
-     public function viewNewInvoiceAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         // Se genera y muestra en nueva pantalla la nueva proforma
-         $arrayBools = array(
-             'lounge' => null,
-             'service' => null,
-             'payment' => null,
-         );
-         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
-         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
-         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         //INICIO: Creamos la factura
-         $newInvoice = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-         //FIN: Creamos la factura
-         $data = array();
-         $data = $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'I');
-         $paymentsClient = new ReservationPaymentsClient();
-         $paymentsClient->setReservationId($id);
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
-         $idLounges = array();
-         $loungesBoolToInvoice = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $item) {
-                 $idLounges[] = $item['id'];
-                 $loungesBoolToInvoice[] = 1;
-             }
-             $idLounges = implode(',', $idLounges);
-             $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-         } else {
-             $idLounges = '0';
-             $loungesBoolToInvoice = '0';
-         }
-         $idPayments = array();
-         $paymentsBoolToInvoice = array();
-         if (array_key_exists('payment',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['payment'] as $item) {
-                 $idPayments[] = $item['id'];
-                 $paymentsBoolToInvoice[] = 1;
-             }
-             $idPayments = implode(',', $idPayments);
-             $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-             // Se han generado dos arreglos, cada uno dividido en 2 strings
-             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-             // Para manipularlos entre la vista y el JS
-         } else {
-             $idPayments = '0';
-             $paymentsBoolToInvoice = '0';
-         }
-         // Una factura solo se puede rectificar una vez
- //        $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
-         $rectf = $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($id);
-         $boolToRec = empty($rectf);
-         $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-         $allInvoicesRec = $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($newInvoice->getReservationId());
-         foreach ($allInvoicesRec as $item){
-             array_push($allInvoices, $item);
-         }
-         $allProformas = $em->getRepository(ReservationProforma::class)->findByReservationId($newInvoice->getReservationId());
-         if(empty($data['type'])){$data['type'] = 'Invoice';}
-         $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-         if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-             $newInvoice = $this->clientDataToInvoice($newInvoice, 'Client', $reservaEquis->getClient(), $newInvoice->getReservationId());
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
-             array(
-                 'id' => $newInvoice->getReservationId(),
-                 'cid' => '',
-                 'fid' => $id,
-                 'invoice' => $allInvoices,
-                 'proformas' => $allProformas,
-                 'boolToRec' => $boolToRec,
-                 'numberadmin' => '',
-                 'type' => $data['type'],
-                 'number' => $newInvoice->getId(),
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' =>  $data['token'],
-                 'reservation' => $data['reservation'],
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'user' => $user_logueado,
-                 'invoicedeposititems' => '',
-                 'arrayItems' => $data['arrayItems'],
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => '',
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'currency' => $data['currency'],
-                 'clientName' => $newInvoice->getClientName(),
-                 'clientAddress' => $newInvoice->getClientAddress(),
-                 'clientDocument' => $newInvoice->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/viewnewprof/{id}",  name="reservations_viewnew_proforma")
-      */
-     public function viewNewProformaAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         // Se genera y muestra en nueva pantalla la nueva proforma
-         $arrayBools = array(
-             'lounge' => null,
-             'service' => null,
-             'payment' => null,
-         );
-         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
-         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
-         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         //FIN: Creamos los items de la proforma
-         $newInvoice = $em->getRepository(ReservationProforma::class)->findOneById($id);
-         //FIN: Creamos la proforma
-         $data = array();
-         $data = $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'P');
-         // Una factura solo se puede rectificar una vez (Las proformas no se rectifican)
-         $boolToRec = false;
-         $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-         $allInvoicesRec = $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($newInvoice->getReservationId());
-         foreach ($allInvoicesRec as $item){
-             array_push($allInvoices, $item);
-         }
-         $allProformas = $em->getRepository(ReservationProforma::class)->findByReservationId($newInvoice->getReservationId());
-         if(empty($data['type'])){$data['type'] = 'Proforma';}
-         $newInvoiceProf = $this->clientDataToInvoice(null, null, null, $newInvoice->getReservationId());
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
-             array(
-                 'id' => $newInvoice->getReservationId(),
-                 'cid' => '',
-                 'fid' => $id,
-                 'invoice' => $allInvoices,
-                 'proformas' => $allProformas,
-                 'boolToRec' => $boolToRec,
-                 'numberadmin' => '',
-                 'type' => $data['type'],
-                 'number' => $newInvoice->getId(),
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' =>  $data['token'],
-                 'reservation' => $data['reservation'],
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'user' => $user_logueado,
-                 'invoicedeposititems' => '',
-                 'arrayItems' => $data['arrayItems'],
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => '',
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'currency' => $data['currency'],
-                 'clientName' => $newInvoiceProf->getClientName(),
-                 'clientAddress' => $newInvoiceProf->getClientAddress(),
-                 'clientDocument' => $newInvoiceProf->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/viewrec/{id}",  name="reservations_viewrec_invoice")
-      */
-     public function viewRecInvoiceAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         // Se genera y muestra en nueva pantalla la nueva proforma
-         $arrayBools = array(
-             'lounge' => null,
-             'service' => null,
-             'payment' => null,
-         );
-         $arrayBools['lounge'] = $request->request->get('inv_lounge_hidden_bool');
-         $arrayBools['service'] = $request->request->get('inv_service_hidden_bool');
-         $arrayBools['payment'] = $request->request->get('inv_payment_hidden_bool');
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         //Acumuladores de datos globales de la factura
-         $valorTotalNet = 0;
-         $valorVat = 0;
- //        $valorTotal = 0;
-         //INICIO: Creamos los items de la factura
-         $arrayInvoicedItems = $em->getRepository(ReservationInvoiceRecItems::class)->findByInvoiceId($id);
-         if (!empty($arrayInvoicedItems)) {
-             foreach ($arrayInvoicedItems as $itemInvoice) {
-                 if ($itemInvoice->getItemType() == 'LOUNGE') {
-                     $ivaNew = $itemInvoice->getLngIva();
-                     //Acumulamos neto e iva para la factura
-                     $valorTotalNet = $valorTotalNet + $itemInvoice->getLngServicePrice();
-                     $valorVat = $valorVat + round(($itemInvoice->getLngServicePrice() * ($ivaNew / 100)),2,PHP_ROUND_HALF_UP);
-                 }
-             }
-         }
-         if (!empty($arrayInvoicedItems)) {
-             foreach ($arrayInvoicedItems as $itemInvoice) {
-                 if ($itemInvoice->getItemType() == 'SERVICE') {
-                     //Acumulamos neto e iva para la factura
-                     if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
-                         $subtotal = 0;
-                         $neto = 0;
-                         $subtotalService = 0;
-                     } else {
-                         $subtotalService = (float)$itemInvoice->getSrvPrice();
-                         $subneto = (float)$itemInvoice->getSrvPrice();
-                         // Commission
-                         if ($itemInvoice->getSrvOpCommission()=='1'){
-                             $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvCommission()/100));
-                             $subneto = $subneto  * (1 + ($itemInvoice->getSrvCommission()/100));
-                         } else {
-                             $subtotalService = $subtotalService * (1 - ($itemInvoice->getSrvCommission()/100));
-                             $subneto = $subneto * (1 - ($itemInvoice->getSrvCommission()/100));
-                         }
-                         // Over
-                         if ($itemInvoice->getSrvOpOver()=='1'){
-                             $subtotalService = $subtotalService + $itemInvoice->getSrvOver();
-                             $subneto = $subneto + $itemInvoice->getSrvOver();
-                         } else {
-                             $subtotalService = $subtotalService - $itemInvoice->getSrvOver();
-                             $subneto = $subneto - $itemInvoice->getSrvOver();
-                         }
-                         // IVA
-                         if ($itemInvoice->getSrvOpIva()=='1'){
-                             $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvIva()/100));
-                         } else {
-                             $subtotalService = $itemInvoice->getSrvPrice();
-                             $subneto = ($subneto * 100) / (100 + $itemInvoice->getSrvIva());
-                         }
-                         switch ($itemInvoice->getSrvServiceCatId()){
-                             case 1: // Alojamiento
-                                 // el numero de noches $numNoches; precio unitario $subneto
-                                 $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
-                                 // La personas no afectan este calculo
-                                 $subtotal = $subtotalService * $numNoches * $itemInvoice->getSrvUnits();
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $numNoches * $itemInvoice->getSrvUnits();
-                                 break;
-                             case 2: //Actividades
-                                 // El número de personas es considerado en el calculo
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $subtotal = $subtotalService * $days * $itemInvoice->getSrvUnits();
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $itemInvoice->getSrvUnits();
-                                 break;
-                             case 3: // AV
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 4: //Creative
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 5: //Cruise
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 6: //Entertaiment
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 7: // Gifts
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = 1;
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 8: //Guide
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 9: //Itineraries
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 10: //Lounge  -- No Aplica
-                                 break;
-                             case 11: //Menu
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 12: //Others
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 13: //Transport
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 14: //Technology
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = 1;
-                                 $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 15: //Assisstant
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             case 16: //DDR
-                                 $pax = $itemInvoice->getSrvPax();
-                                 if (empty($pax) or $pax == "0") {
-                                     $pax = 1;
-                                 }
-                                 $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                 if ($days > 1){
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                 } else {
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                 }
-                                 $unitsServ = $itemInvoice->getSrvUnits();
-                                 if (empty($unitsServ) or $unitsServ == "0") {
-                                     $unitsServ = 1;
-                                 }
-                                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                 $subnetoUnit = $subneto;
-                                 $subneto = $subneto * $days * $unitsServ * $pax;
-                                 break;
-                             default:
-                                 break;
-                         }
-                         // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                         $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                         $neto = round($subneto,2,PHP_ROUND_HALF_UP);
-                         $valorTotalNet = $valorTotalNet + $neto;
-                         $valorVat = $valorVat + ($subtotal - $neto);
-                     }
-                 }
-             }
-         }
-         if (!empty($arrayInvoicedItems)) {
-             foreach ($arrayInvoicedItems as $itemInvoice) {
-                 if ($itemInvoice->getItemType() == 'PAYMENT') {
- //                    $pago = $em->getRepository(ReservationPaymentsClient::class)->findOneById($key);
- //
- //                    $itemInvoice = new ReservationInvoiceItems();
- //                    $itemInvoice->setReservationId($id);
- //                    $itemInvoice->setInvoiceId($invoiceId);
- //                    $itemInvoice->setItemType('PAYMENT');
- //                    $itemInvoice->setPayControlId($key);
- //                    $itemInvoice->setPayAmount($pago->getAmount());
- //                    $itemInvoice->setPayDatePayAt($pago->getDatePayAt());
- //                    $itemInvoice->setPayWayToPay($pago->getWayToPay());
- //                    $itemInvoice->setCreatedAt(new DateTime('now'));
- //                    $itemInvoice->setUpdatedAt(new DateTime('now'));
- //                    $itemInvoice->setCreatedId($user_id);
- //                    $itemInvoice->setUpdatedId($user_id);
- //
- //                    $em->persist($itemInvoice);
- //                    $em->flush();
-                     //Acumulamos neto e iva para la factura
-                     //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
-                 }
-             }
-         }
-         //FIN: Creamos los items de la factura
-         $valorTotal = $valorTotalNet + $valorVat;
-         //INICIO: Creamos la factura
-         $newInvoice = $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
-         //FIN: Creamos la factura
-         $data = array();
-         $data = $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'R');
-         $paymentsClient = new ReservationPaymentsClient();
-         $paymentsClient->setReservationId($id);
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
-         $idLounges = array();
-         $loungesBoolToInvoice = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $item) {
-                 $idLounges[] = $item['id'];
-                 $loungesBoolToInvoice[] = 1;
-             }
-             $idLounges = implode(',', $idLounges);
-             $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-         } else {
-             $idLounges = '0';
-             $loungesBoolToInvoice = '0';
-         }
-         $idPayments = array();
-         $paymentsBoolToInvoice = array();
-         if (array_key_exists('payment',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['payment'] as $item) {
-                 $idPayments[] = $item['id'];
-                 $paymentsBoolToInvoice[] = 1;
-             }
-             $idPayments = implode(',', $idPayments);
-             $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-             // Se han generado dos arreglos, cada uno dividido en 2 strings
-             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-             // Para manipularlos entre la vista y el JS
-         } else {
-             $idPayments = '0';
-             $paymentsBoolToInvoice = '0';
-         }
-         // Una factura solo se puede rectificar una vez
-         //$rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
-         //$boolToRec = empty($rectf);
-         $boolToRec = false; // Estas viendo una factura rectificativa
-         $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-         $allInvoicesRec = $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($newInvoice->getReservationId());
-         foreach ($allInvoicesRec as $item){ array_push($allInvoices, $item); }
-         $allProformas = $em->getRepository(ReservationProforma::class)->findByReservationId($newInvoice->getReservationId());
-         // Por ser una factura rectificativa multiplicamos por -1 el balance
- //        $data['balance'] = $data['balance'] * (-1);
-         if(empty($data['type'])){$data['type'] = 'Invoice Rec';}
-         $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-         if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-             $newInvoice = $this->clientDataToInvoice($newInvoice, 'Client', $reservaEquis->getClient(), $newInvoice->getReservationId());
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
-             array(
-                 'id' => $newInvoice->getReservationId(),
-                 'invoiceIdToRec' => $newInvoice->getInvoiceToRec(),
-                 'cid' => '',
-                 'fid' => $id,
-                 'invoice' => $allInvoices,
-                 'proformas' => $allProformas,
-                 'boolToRec' => $boolToRec,
-                 'numberadmin' => '',
-                 'type' => $data['type'],
-                 'number' => $newInvoice->getId(),
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' =>  $data['token'],
-                 'reservation' => $data['reservation'],
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'user' => $user_logueado,
-                 'invoicedeposititems' => '',
-                 'arrayItems' => $data['arrayItems'],
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => '',
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'currency' => $data['currency'],
-                 'clientName' => $newInvoice->getClientName(),
-                 'clientAddress' => $newInvoice->getClientAddress(),
-                 'clientDocument' => $newInvoice->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/viewreservationinvoices/{id}",  name="reservations_viewreservation_invoices")
-      */
-     public function viewReservationInvoicesAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($id);
-         $allInvoicesRec = $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($id);
-         foreach ($allInvoicesRec as $item){
-             array_push($allInvoices, $item);
-         }
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $client = $em->getRepository(Client::class)->findOneById($reservation->getClient());
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $data = array();
-         $data['clients'][0] = $client;
-         $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $data['datasupplier'] = '';
-         $data['totales_neto'] = '';
-         $data['totales'] = '';
-         $data['bases_imponibles'] = '';
-         $data['balance'] = '';
-         $data['paymentInvoice'] = '';
-         $data['currency'] = '';
-         // Una factura solo se puede rectificar una vez
-         //$rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
-         //$boolToRec = empty($rectf);
-         $boolToRec = false;
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
-             array(
-                 'id' => $id,
-                 'cid' => '',
-                 'fid' => null,
-                 'invoice' => $allInvoices,
-                 'boolToRec' => $boolToRec,
-                 'numberadmin' => '',
-                 'type' => 'Invoice',
-                 'number' => '',
-                 'prefix' => '',
-                 'date' => '',
-                 'token' => '',
-                 'reservation' => '',
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'user' => $user_logueado,
-                 'invoicedeposititems' => '',
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => '',
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'currency' => $data['currency'],
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/viewreservationproformas/{id}",  name="reservations_viewreservation_proformas")
-      */
-     public function viewReservationProformasAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $allInvoices = $em->getRepository(ReservationProforma::class)->findByReservationId($id);
-         $allProformas = $allInvoices;
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $client = $em->getRepository(Client::class)->findOneById($reservation->getClient());
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $data = array();
-         $data['clients'][0] = $client;
-         $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $data['datasupplier'] = '';
-         $data['totales_neto'] = '';
-         $data['totales'] = '';
-         $data['bases_imponibles'] = '';
-         $data['balance'] = '';
-         $data['paymentInvoice'] = '';
-         $data['currency'] = '';
-         // Una factura solo se puede rectificar una vez
-         //$rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$newInvoice->getNumber()));
-         //$boolToRec = empty($rectf);
-         $boolToRec = false;
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-new-invoice.html.twig',
-             array(
-                 'id' => $id,
-                 'cid' => '',
-                 'fid' => null,
-                 'invoice' => $allInvoices,
-                 'proformas' => $allProformas,
-                 'boolToRec' => $boolToRec,
-                 'numberadmin' => '',
-                 'type' => 'Proforma',
-                 'number' => '',
-                 'prefix' => '',
-                 'date' => '',
-                 'token' => '',
-                 'reservation' => '',
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'user' => $user_logueado,
-                 'invoicedeposititems' => '',
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => '',
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'currency' => $data['currency'],
-             )
-         );
-     }
-     /**
-      * @Route("/selinvoice/{id}",  name="reservations_newinvoice")
-      */
-     public function generateReservationNewInvoiceAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $paymentsClient = new ReservationPaymentsClient();
-         $paymentsClient->setReservationId($id);
-         $clientType = 'Client';
-         $clientRequest = $request->request->get('reservation')['client'] ?? null;
-         if (!empty($clientRequest)){
-             $dataCliSup = $this->clientOrSupplierDataSearchToInvoice($clientRequest, $id);
-             $clientName = $dataCliSup['clientName'];
-             $clientAddress = $dataCliSup['clientAddress'];
-             $clientDocument = $dataCliSup['clientDocument'];
-             $clientType = $dataCliSup['clientType'];
-         }
-         if (empty($clientName) and empty($clientAddress) and empty($clientDocument)){
-             $newInvoice = $this->clientDataToInvoice(null, null, null, $id);
-         } else {
-             $newInvoice = new ReservationInvoice();
-             $newInvoice->setClientName($clientName);
-             $newInvoice->setClientAddress($clientAddress);
-             $newInvoice->setClientDocument($clientDocument);
-         }
-         $form = $this->createReservationPaymentsClientForm($paymentsClient);
-         $reserva = $em->getRepository(Reservation::class)->findOneById($id);
-         $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
-         $services = $em->getRepository(ReservationService::class)->findByReservationId($id);
-         $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-         $allProformas = $em->getRepository(ReservationProforma::class)->findAll();
-         if (!empty($allProformas)){
-             $number = end($allProformas)->getId() + 1;
-         } else {
-             // Primer registro de proformas
-             $number = 1;
-         }
-         $type = 'Proforma';
-         $date = new DateTime('now');
-         $prefix = "GP-".$date->format('dmy')."-";
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
-         $form1 = $this->createReservationInvoiceProformaForm($reservaInv);
-         $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
-         $token = $data['token'];
-         $idLounges = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $key => $item) {
-                 $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneByLngControlId($item['id']);
-                 $existeCvr = $em->getRepository(CvrReservationInvoiceItems::class)->findByLngControlId($item['id']);
-                 $existe = (!empty($existe) or !empty($existeCvr));
-                 if (empty($existe)){
-                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = true;
-                 } else {
-                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = false;
-                 }
-             }
-         }
-         if (array_key_exists('service',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['service'] as $key => $item) {
-                 $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneBySrvControlId($item['id']);
-                 $existeCvr = $em->getRepository(CvrReservationInvoiceItems::class)->findBySrvControlId($item['id']);
-                 $existe = (!empty($existe) or !empty($existeCvr));
-                 if (empty($existe)){
-                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = true;
-                 } else {
-                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = false;
-                 }
-             }
-         }
-         $idPayments = array();
-         if (array_key_exists('payment',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['payment'] as $key => $item) {
-                 $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($item['id']);
-                 $existeCvr = $em->getRepository(CvrReservationInvoiceItems::class)->findByPayControlId($item['id']);
-                 $existe = (!empty($existe) or !empty($existeCvr));
-                 if (empty($existe)){
-                     $data['datasupplier']['payment'][$key]['enabledToInvoice'] = true;
-                 } else {
-                     $data['datasupplier']['payment'][$key]['enabledToInvoice'] = false;
-                 }
-             }
-         }
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         // Si el Status no lo permite solo se podra sacar proformas
-         if ($reserva->getStatus() == 'Invoiced' or $reserva->getStatus() == 'Confirmed'){ $cotizarPorEstado = true; } else { $cotizarPorEstado = false; }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-select-items.html.twig',
-             array(
-                 'id' => $id,
-                 'idLounges' => $idLounges,
-                 'reserva' => $reserva,
-                 'idPayments' => $idPayments,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => $token,
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'currency' => $data['currency'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'payments' => $payments,
-                 'user_id' => $user_id,
-                 'form' => $form->createView(),
-                 'form1' => $form1->createView(),
-                 'cotizarPorEstado' => $cotizarPorEstado,
-                 'clientName' => $newInvoice->getClientName(),
-                 'clientAddress' => $newInvoice->getClientAddress(),
-                 'clientDocument' => $newInvoice->getClientDocument(),
-                 'clientType' => $clientType,
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/invoice-proforma/print/{type}/{id}",  name="reservations_invoiceorproforma_print")
-      */
-     public function detailsInvoiceProformaPrintAction($type, $id, Request $request)
-     {
-         $data = array();
-         $em = $this->getDoctrine()->getManager();
-         // Si el ID de factura viene vacio regresamos a ver facturas
-         if (empty($type)){
-             return $this->redirectToRoute('reservations_viewreservation_invoices',array('id' => $id));
-         }
-         //Acumuladores de datos globales de la factura o proforma
-         $valorTotalNet = 0;
-         $valorVat = 0;
-         if ($type == 'I'){
-             //Es una factura
-             //INICIO: Creamos los items de la factura
-             $arrayInvoicedItems = $em->getRepository(ReservationInvoiceItems::class)->findByInvoiceId($id);
-             if (!empty($arrayInvoicedItems)) {
-                 foreach ($arrayInvoicedItems as $itemInvoice) {
-                     if ($itemInvoice->getItemType() == 'LOUNGE') {
-                         //Acumulamos neto e iva para la factura
-                         $valorTotalNet = $valorTotalNet + $itemInvoice->getLngServicePrice();
-                         $valorVat = $valorVat + round(($itemInvoice->getLngServicePrice() * 0.21),2,PHP_ROUND_HALF_UP);
-                     }
-                 }
-             }
-             if (!empty($arrayInvoicedItems)) {
-                 foreach ($arrayInvoicedItems as $itemInvoice) {
-                     if ($itemInvoice->getItemType() == 'SERVICE') {
-                         //Acumulamos neto e iva para la factura
-                         if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
-                             $subtotal = 0;
-                             $neto = 0;
-                             $subtotalService = 0;
-                         } else {
-                             $subtotalService = $itemInvoice->getSrvPrice();
-                             $subtotalService = str_replace(',','.',$subtotalService);
-                             $subtotalService = floatval($subtotalService);
-                             $subneto = $itemInvoice->getSrvPrice();
-                             $subneto = str_replace(',','.',$subneto);
-                             $subneto = floatval($subneto);
-                             // Commission
-                             if ($itemInvoice->getSrvOpCommission()=='1'){
-                                 $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvCommission()/100));
-                                 $subneto = $subneto  * (1 + ($itemInvoice->getSrvCommission()/100));
-                             } else {
-                                 $subtotalService = $subtotalService * (1 - ($itemInvoice->getSrvCommission()/100));
-                                 $subneto = $subneto * (1 - ($itemInvoice->getSrvCommission()/100));
-                             }
-                             // Over
-                             if ($itemInvoice->getSrvOpOver()=='1'){
-                                 $subtotalService = $subtotalService + $itemInvoice->getSrvOver();
-                                 $subneto = $subneto + $itemInvoice->getSrvOver();
-                             } else {
-                                 $subtotalService = $subtotalService - $itemInvoice->getSrvOver();
-                                 $subneto = $subneto - $itemInvoice->getSrvOver();
-                             }
-                             // IVA
-                             if ($itemInvoice->getSrvOpIva()=='1'){
-                                 $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvIva()/100));
-                             } else {
-                                 $subtotalService = $itemInvoice->getSrvPrice();
-                                 $subneto = ($subneto * 100) / (100 + $itemInvoice->getSrvIva());
-                             }
-                             switch ($itemInvoice->getSrvServiceCatId()){
-                                 case 1: // Alojamiento
-                                     // el numero de noches $numNoches; precio unitario $subneto
-                                     $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
-                                     // La personas no afectan este calculo
-                                     $subtotal = $subtotalService * $numNoches * $itemInvoice->getSrvUnits();
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $numNoches * $itemInvoice->getSrvUnits();
-                                     break;
-                                 case 2: //Actividades
-                                     // El número de personas es considerado en el calculo
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $subtotal = $subtotalService * $days * $itemInvoice->getSrvUnits();
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $itemInvoice->getSrvUnits();
-                                     break;
-                                 case 3: // AV
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 4: //Creative
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 5: //Cruise
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 6: //Entertaiment
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 7: // Gifts
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = 1;
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 8: //Guide
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 9: //Itineraries
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 10: //Lounge  -- No Aplica
-                                     break;
-                                 case 11: //Menu (Catering)
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 12: //Others
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 13: //Transport
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 14: //Technology
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = 1;
-                                     $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 15: //Assisstant
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 16: //DDR
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 17: //Seguridad
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 18: //WiFi
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 19: //Mobiliario
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 20: //Parking
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 case 21: //Limpieza
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                                 default: //Others (por default)
-                                     $pax = $itemInvoice->getSrvPax();
-                                     if (empty($pax) or $pax == "0") { $pax = 1; }
-                                     $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                     $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                     $unitsServ = $itemInvoice->getSrvUnits();
-                                     if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                     $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                     $subnetoUnit = $subneto;
-                                     $subneto = $subneto * $days * $unitsServ * $pax;
-                                     break;
-                             }
-                             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                             $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                             $neto = round($subneto,2,PHP_ROUND_HALF_UP);
-                             $valorTotalNet = $valorTotalNet + $neto;
-                             $valorVat = $valorVat + ($subtotal - $neto);
-                         }
-                     }
-                 }
-             }
-             if (!empty($arrayInvoicedItems)) {
-                 foreach ($arrayInvoicedItems as $itemInvoice) {
-                     if ($itemInvoice->getItemType() == 'PAYMENT') {
-                         //Acumulamos neto e iva para la factura
-                         //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
-                     }
-                 }
-             }
-             //FIN: Creamos los items de la factura
-             $valorTotal = $valorTotalNet + $valorVat;
-             //INICIO: Creamos la factura
-             $newInvoice = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-             //FIN: Creamos la factura
-             $data = array();
-             $data = $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'I');
-             $paymentsClient = new ReservationPaymentsClient();
-             $paymentsClient->setReservationId($id);
-             $reservaInv = new ReservationInvoice();
-             $reservaInv->setReservationId($id);
-             $idLounges = array();
-             $loungesBoolToInvoice = array();
-             if (array_key_exists('lounge',$data['datasupplier'])) {
-                 foreach ($data['datasupplier']['lounge'] as $item) {
-                     $idLounges[] = $item['id'];
-                     $loungesBoolToInvoice[] = 1;
-                 }
-                 $idLounges = implode(',', $idLounges);
-                 $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-             } else {
-                 $idLounges = '0';
-                 $loungesBoolToInvoice = '0';
-             }
-             $idPayments = array();
-             $paymentsBoolToInvoice = array();
-             if (array_key_exists('payment',$data['datasupplier'])) {
-                 foreach ($data['datasupplier']['payment'] as $item) {
-                     $idPayments[] = $item['id'];
-                     $paymentsBoolToInvoice[] = 1;
-                 }
-                 $idPayments = implode(',', $idPayments);
-                 $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-                 // Se han generado dos arreglos, cada uno dividido en 2 strings
-                 // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-                 // Para manipularlos entre la vista y el JS
-             } else {
-                 $idPayments = '0';
-                 $paymentsBoolToInvoice = '0';
-             }
-             $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-             //Es una proforma
-             $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-             $invoiceIdToRec = null;
-             $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-             if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-                 $newInvoice = $this->clientDataToInvoice($newInvoice, 'Client', $reservaEquis->getClient(), $newInvoice->getReservationId());
-             }
-         } else {
-             if ($type == 'R'){
-                 //El tipo es una factura rectificativa
-                 //INICIO: Creamos los items de la factura rectficativa
-                 $arrayInvoicedItems = $em->getRepository(ReservationInvoiceRecItems::class)->findByInvoiceRecId($id);
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getItemType() == 'LOUNGE') {
-                             //Acumulamos neto e iva para la factura rectificativa
-                             $valorTotalNet = $valorTotalNet + $itemInvoice->getLngServicePrice();
-                             $valorVat = $valorVat + round(($itemInvoice->getLngServicePrice() * 0.21),2,PHP_ROUND_HALF_UP);
-                         }
-                     }
-                 }
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getItemType() == 'SERVICE') {
-                             //Acumulamos neto e iva para la factura
-                             if (is_null($itemInvoice->getSrvPrice()) or empty($itemInvoice->getSrvPrice())){
-                                 $subtotal = 0;
-                                 $neto = 0;
-                                 $subtotalService = 0;
-                             } else {
-                                 $subtotalService = (float)$itemInvoice->getSrvPrice();
-                                 $subneto = (float)$itemInvoice->getSrvPrice();
-                                 // Commission
-                                 if ($itemInvoice->getSrvOpCommission()=='1'){
-                                     $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvCommission()/100));
-                                     $subneto = $subneto  * (1 + ($itemInvoice->getSrvCommission()/100));
-                                 } else {
-                                     $subtotalService = $subtotalService * (1 - ($itemInvoice->getSrvCommission()/100));
-                                     $subneto = $subneto * (1 - ($itemInvoice->getSrvCommission()/100));
-                                 }
-                                 // Over
-                                 if ($itemInvoice->getSrvOpOver()=='1'){
-                                     $subtotalService = $subtotalService + $itemInvoice->getSrvOver();
-                                     $subneto = $subneto + $itemInvoice->getSrvOver();
-                                 } else {
-                                     $subtotalService = $subtotalService - $itemInvoice->getSrvOver();
-                                     $subneto = $subneto - $itemInvoice->getSrvOver();
-                                 }
-                                 // IVA
-                                 if ($itemInvoice->getSrvOpIva()=='1'){
-                                     $subtotalService = $subtotalService * (1 + ($itemInvoice->getSrvIva()/100));
-                                 } else {
-                                     $subtotalService = $itemInvoice->getSrvPrice();
-                                     $subneto = ($subneto * 100) / (100 + $itemInvoice->getSrvIva());
-                                 }
-                                 switch ($itemInvoice->getSrvServiceCatId()){
-                                     case 1: // Alojamiento
-                                         // el numero de noches $numNoches; precio unitario $subneto
-                                         $numNoches = (($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days;
-                                         // La personas no afectan este calculo
-                                         $subtotal = $subtotalService * $numNoches * $itemInvoice->getSrvUnits();
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $numNoches * $itemInvoice->getSrvUnits();
-                                         break;
-                                     case 2: //Actividades
-                                         // El número de personas es considerado en el calculo
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $subtotal = $subtotalService * $days * $itemInvoice->getSrvUnits();
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $itemInvoice->getSrvUnits();
-                                         break;
-                                     case 3: // AV
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 4: //Creative
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 5: //Cruise
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 6: //Entertaiment
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 7: // Gifts
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = 1;
-                                         $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 8: //Guide
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 9: //Itineraries
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 10: //Lounge  -- No Aplica
-                                         break;
-                                     case 11: //Catering
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 12: //Others
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 13: //Transport
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 14: //Technology
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = 1;
-                                         $dateServ = ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 15: //Assisstant
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 16: //DDR
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 17: //Seguridad
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 18: //WiFi
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 19: //Mobiliario
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 20: //Parking
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 21: //Limpieza
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     default: //Others (por default)
-                                         $pax = $itemInvoice->getSrvPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemInvoice->getSrvDateOutAt())->diff($itemInvoice->getSrvDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemInvoice->getSrvDateInAt())->format('d/m/Y'). ' - '.($itemInvoice->getSrvDateOutAt())->format('d/m/Y') : ($itemInvoice->getSrvDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemInvoice->getSrvUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                 }
-                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                                 $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                                 $neto = round($subneto,2,PHP_ROUND_HALF_UP);
-                                 $valorTotalNet = $valorTotalNet + $neto;
-                                 $valorVat = $valorVat + ($subtotal - $neto);
-                             }
-                         }
-                     }
-                 }
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getItemType() == 'PAYMENT') {
-                             //Acumulamos neto e iva para la factura
-                             //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
-                         }
-                     }
-                 }
-                 //FIN: Creamos los items de la factura
-                 $valorTotal = $valorTotalNet + $valorVat;
-                 //INICIO: Creamos la factura rectificativa
-                 $newInvoice = $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
-                 //FIN: Creamos la factura rectificativa
-                 $data = array();
-                 $data = $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'R');
-                 $paymentsClient = new ReservationPaymentsClient();
-                 $paymentsClient->setReservationId($id);
-                 $reservaInv = new ReservationInvoice();
-                 $reservaInv->setReservationId($id);
-                 $idLounges = array();
-                 $loungesBoolToInvoice = array();
-                 if (array_key_exists('lounge',$data['datasupplier'])) {
-                     foreach ($data['datasupplier']['lounge'] as $item) {
-                         $idLounges[] = $item['id'];
-                         $loungesBoolToInvoice[] = 1;
-                     }
-                     $idLounges = implode(',', $idLounges);
-                     $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-                 } else {
-                     $idLounges = '0';
-                     $loungesBoolToInvoice = '0';
-                 }
-                 $idPayments = array();
-                 $paymentsBoolToInvoice = array();
-                 if (array_key_exists('payment',$data['datasupplier'])) {
-                     foreach ($data['datasupplier']['payment'] as $item) {
-                         $idPayments[] = $item['id'];
-                         $paymentsBoolToInvoice[] = 1;
-                     }
-                     $idPayments = implode(',', $idPayments);
-                     $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-                     // Se han generado dos arreglos, cada uno dividido en 2 strings
-                     // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-                     // Para manipularlos entre la vista y el JS
-                 } else {
-                     $idPayments = '0';
-                     $paymentsBoolToInvoice = '0';
-                 }
-                 $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-                 //Es una proforma
-                 $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-                 $invoiceIdToRec = $newInvoice->getInvoiceToRec();
-                 $data['number'] = $data['number']->getNumber();
-                 $data['balance'] = $data['balance'] *(-1);
-                 $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-                 if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-                     $newInvoice = $this->clientDataToInvoice($newInvoice, 'Client', $reservaEquis->getClient(), $newInvoice->getReservationId());
-                 }
-             } else {
-                 // El tipo es una proforma
-                 //INICIO: Creamos los items de la proforma
-                 $arrayInvoicedItems = $em->getRepository(ReservationInvoiceProformaItems::class)->findByProformaId($id);
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getType() == 'LOUNGE') {
-                             $itemPro = $em->getRepository(ReservationLoungeSimple::class)->findOneById($itemInvoice->getControlId());
-                             //Acumulamos neto e iva para la factura
-                             $valorTotalNet = $valorTotalNet + $itemPro->getServicePrice();
-                             $valorVat = $valorVat + round(($itemPro->getServicePrice() * 0.21),2,PHP_ROUND_HALF_UP);
-                         }
-                     }
-                 }
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getType() == 'SERVICE') {
-                             $itemPro = $em->getRepository(ReservationService::class)->findOneById($itemInvoice->getControlId());
-                             //Acumulamos neto e iva para la factura
-                             if (is_null($itemPro->getPrice()) or empty($itemPro->getPrice())){
-                                 $subtotal = 0;
-                                 $neto = 0;
-                                 $subtotalService = 0;
-                             } else {
-                                 $subtotalService = $itemPro->getPrice();
-                                 $subneto = $itemPro->getPrice();
-                                 // Commission
-                                 if ($itemPro->getOpCommission()=='1'){
-                                     $subtotalService = $subtotalService * (1 + ($itemPro->getCommission()/100));
-                                     $subneto = $subneto  * (1 + ($itemPro->getCommission()/100));
-                                 } else {
-                                     $subtotalService = $subtotalService * (1 - ($itemPro->getCommission()/100));
-                                     $subneto = $subneto * (1 - ($itemPro->getCommission()/100));
-                                 }
-                                 // Over
-                                 if ($itemPro->getOpOver()=='1'){
-                                     $subtotalService = $subtotalService + $itemPro->getOver();
-                                     $subneto = $subneto + $itemPro->getOver();
-                                 } else {
-                                     $subtotalService = $subtotalService - $itemPro->getOver();
-                                     $subneto = $subneto - $itemPro->getOver();
-                                 }
-                                 // IVA
-                                 if ($itemPro->getOpIva()=='1'){
-                                     $subtotalService = $subtotalService * (1 + ($itemPro->getIva()/100));
-                                 } else {
-                                     $subtotalService = $itemPro->getPrice();
-                                     $subneto = ($subneto * 100) / (100 + $itemPro->getIva());
-                                 }
-                                 switch ($itemPro->getServiceCatId()){
-                                     case 1: // Alojamiento
-                                         // el numero de noches $numNoches; precio unitario $subneto
-                                         $numNoches = (($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days;
-                                         // La personas no afectan este calculo
-                                         $subtotal = $subtotalService * $numNoches * $itemPro->getUnits();
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $numNoches * $itemPro->getUnits();
-                                         break;
-                                     case 2: //Actividades
-                                         // El número de personas es considerado en el calculo
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $subtotal = $subtotalService * $days * $itemPro->getUnits();
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $itemPro->getUnits();
-                                         break;
-                                     case 3: // AV
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 4: //Creative
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 5: //Cruise
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 6: //Entertaiment
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 7: // Gifts
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = 1;
-                                         $dateServ = ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 8: //Guide
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 9: //Itineraries
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 10: //Lounge  -- No Aplica
-                                         break;
-                                     case 11: //Menu
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 12: //Others
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 13: //Transport
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 14: //Technology
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = 1;
-                                         $dateServ = ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 15: //Assisstant
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 16: //DDR
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 17: //Seguridad
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 18: //WiFi
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 19: //Mobiliario
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 20: //Parking
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     case 21: //Limpieza
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                     default: //Others (por default)
-                                         $pax = $itemPro->getPax();
-                                         if (empty($pax) or $pax == "0") { $pax = 1; }
-                                         $days = ((($itemPro->getDateOutAt())->diff($itemPro->getDateInAt()))->days + 1);
-                                         $dateServ = ($days > 1) ? ($itemPro->getDateInAt())->format('d/m/Y'). ' - '.($itemPro->getDateOutAt())->format('d/m/Y') : ($itemPro->getDateInAt())->format('d/m/Y');
-                                         $unitsServ = $itemPro->getUnits();
-                                         if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
-                                         $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                                         $subnetoUnit = $subneto;
-                                         $subneto = $subneto * $days * $unitsServ * $pax;
-                                         break;
-                                 }
-                                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                                 $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                                 $neto = round($subneto,2,PHP_ROUND_HALF_UP);
-                                 $valorTotalNet = $valorTotalNet + $neto;
-                                 $valorVat = $valorVat + ($subtotal - $neto);
-                             }
-                         }
-                     }
-                 }
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getType() == 'PAYMENT') {
-                             //Acumulamos neto e iva para la factura
-                             //$valorTotalNet = $valorTotalNet - $itemInvoice->getPayAmount();    // El pago no puede afectar el neto de la factura
-                         }
-                     }
-                 }
-                 //FIN: Creamos los items de la factura
-                 $valorTotal = $valorTotalNet + $valorVat;
-                 //INICIO: Creamos la factura
-                 $newInvoice = $em->getRepository(ReservationProforma::class)->findOneById($id);
-                 //FIN: Creamos la factura
-                 $data = array();
-                 $data = $this->baseInvoiceDoneReservation($newInvoice->getReservationId(), $id,'P');
-                 $paymentsClient = new ReservationPaymentsClient();
-                 $paymentsClient->setReservationId($id);
-                 $reservaInv = new ReservationInvoice();
-                 $reservaInv->setReservationId($id);
-                 $idLounges = array();
-                 $loungesBoolToInvoice = array();
-                 if (array_key_exists('lounge',$data['datasupplier'])) {
-                     foreach ($data['datasupplier']['lounge'] as $item) {
-                         $idLounges[] = $item['id'];
-                         $loungesBoolToInvoice[] = 1;
-                     }
-                     $idLounges = implode(',', $idLounges);
-                     $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-                 } else {
-                     $idLounges = '0';
-                     $loungesBoolToInvoice = '0';
-                 }
-                 $idPayments = array();
-                 $paymentsBoolToInvoice = array();
-                 if (array_key_exists('payment',$data['datasupplier'])) {
-                     foreach ($data['datasupplier']['payment'] as $item) {
-                         $idPayments[] = $item['id'];
-                         $paymentsBoolToInvoice[] = 1;
-                     }
-                     $idPayments = implode(',', $idPayments);
-                     $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-                     // Se han generado dos arreglos, cada uno dividido en 2 strings
-                     // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-                     // Para manipularlos entre la vista y el JS
-                 } else {
-                     $idPayments = '0';
-                     $paymentsBoolToInvoice = '0';
-                 }
-                 $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-                 //Es una proforma
-                 $proforma = $em->getRepository(ReservationProforma::class)->findOneById($id);
-                 $invoiceIdToRec = null;
-                 $reservaEquis = $em->getRepository(Reservation::class)->findOneById($proforma->getReservationId());
- //                if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-                 if(true){ $newInvoice = $this->clientDataToInvoice(null, 'Client', $reservaEquis->getClient(), $reservaEquis->getId()); }
-             }
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-print-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'invoiceIdToRec' => $invoiceIdToRec,
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => '',
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'currency' => $data['currency'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'clientName' => $newInvoice->getClientName(),
-                 'clientAddress' => $newInvoice->getClientAddress(),
-                 'clientDocument' => $newInvoice->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/proforma/printnew",  name="reservations_invoice_printnew")
-      */
-     public function detailsProformaPrintNewAction(Request $request){
-         $em = $this->getDoctrine()->getManager();
-         // Se genera y muestra en nueva pantalla la nueva proforma
-         $arrayBools = array(
-             'lounge' => null,
-             'service' => null,
-             'payment' => null,
-         );
-         $arrayBools['lounge'] = $request->request->get('lounge_hidden_bool');
-         $arrayBools['service'] = $request->request->get('service_hidden_bool');
-         $arrayBools['payment'] = $request->request->get('payment_hidden_bool');
-         $id = $request->request->get('reservation_id');
-         $proformaPrefix = $request->request->get('proforma_prefix');
-         //INICIO: Verificamos que el ID de la proforma se exactamente el ultimo
-         $proformaId = $request->request->get('proforma_number');
-         $allProformas = $em->getRepository(ReservationProforma::class)->findAll();
-         if (!empty($allProformas)){
-             $numberLast = end($allProformas)->getId() + 1;
-         } else {
-             // Primer registro de proformas
-             $numberLast = 1;
-         }
-         if ($numberLast > $proformaId){
-             $proformaId = $numberLast;
-         }
-         //FIN: Verificamos que el ID de la proforma se exactamente el ultimo
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         //INICIO: Creamos los items de la proforma
-         if (!empty($arrayBools['lounge'])) {
-             foreach ($arrayBools['lounge'] as $key => $item) {
-                 if ($item == 'true') {
-                     $itemProforma = new ReservationInvoiceProformaItems();
-                     $itemProforma->setControlId($key);
-                     $itemProforma->setProformaId($proformaId);
-                     $itemProforma->setReservationId($id);
-                     $itemProforma->setType('LOUNGE');
-                     $em->persist($itemProforma);
-                     $em->flush();
-                 }
-             }
-         }
-         if (!empty($arrayBools['service'])) {
-             foreach ($arrayBools['service'] as $key => $item) {
-                 if ($item == 'true') {
-                     $itemProforma = new ReservationInvoiceProformaItems();
-                     $itemProforma->setControlId($key);
-                     $itemProforma->setProformaId($proformaId);
-                     $itemProforma->setReservationId($id);
-                     $itemProforma->setType('SERVICE');
-                     $em->persist($itemProforma);
-                     $em->flush();
-                 }
-             }
-         }
-         if (!empty($arrayBools['payment'])) {
-             foreach ($arrayBools['payment'] as $key => $item) {
-                 if ($item == 'true') {
-                     $itemProforma = new ReservationInvoiceProformaItems();
-                     $itemProforma->setControlId($key);
-                     $itemProforma->setProformaId($proformaId);
-                     $itemProforma->setReservationId($id);
-                     $itemProforma->setType('PAYMENT');
-                     $em->persist($itemProforma);
-                     $em->flush();
-                 }
-             }
-         }
-         //FIN: Creamos los items de la proforma
-         //INICIO: Creamos la proforma
-         $newProforma = new ReservationProforma();
-         $newProforma->setDateAt(new DateTime('now'));
-         $newProforma->setPrefix("GP-".date('dmy')."-");
-         $newProforma->setReservationId($id);
-         $newProforma->setCreatedAt(new DateTime('now'));
-         $newProforma->setCreatedId($user_id);
-         $newProforma->setUpdatedAt(new DateTime('now'));
-         $newProforma->setUpdatedId($user_id);
-         $accessKey = md5('CR-JDEF'. rand() * time());
-         $newProforma->setAccessKey($accessKey);
-         $em->persist($newProforma);
-         $em->flush();
-         //FIN: Creamos la proforma
-         $data = array();
-         $data = $this->baseInvoiceSelectedReservation($id, $arrayBools, 'P'.$newProforma->getId());
-         $paymentsClient = new ReservationPaymentsClient();
-         $paymentsClient->setReservationId($id);
-         $form = $this->createReservationPaymentsClientForm($paymentsClient);
-         $reserva = $em->getRepository(Reservation::class)->findOneById($id);
-         $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
-         $services = $em->getRepository(ReservationService::class)->findByReservationId($id);
-         $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
-         $form1 = $this->createReservationInvoiceProformaForm($reservaInv);
-         $idLounges = array();
-         $loungesBoolToInvoice = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $item) {
-                 $idLounges[] = $item['id'];
-                 $loungesBoolToInvoice[] = 1;
-             }
-             $idLounges = implode(',', $idLounges);
-             $loungesBoolToInvoice = implode(',', $loungesBoolToInvoice);
-         } else {
-             $idLounges = '0';
-             $loungesBoolToInvoice = '0';
-         }
-         $idPayments = array();
-         $paymentsBoolToInvoice = array();
-         if (array_key_exists('payment',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['payment'] as $item) {
-                 $idPayments[] = $item['id'];
-                 $paymentsBoolToInvoice[] = 1;
-             }
-             $idPayments = implode(',', $idPayments);
-             $paymentsBoolToInvoice = implode(',', $paymentsBoolToInvoice);
-             // Se han generado dos arreglos, cada uno dividido en 2 strings
-             // array( [5]=>0, [8]=>1, [10]=>0)  ==>> '5,8,10' y '0,1,0'
-             // Para manipularlos entre la vista y el JS
-         } else {
-             $idPayments = '0';
-             $paymentsBoolToInvoice = '0';
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-print-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'idLounges' => $idLounges,
-                 'reserva' => $reserva,
-                 'idPayments' => $idPayments,
-                 'loungesBoolToInvoice' => $loungesBoolToInvoice,
-                 'paymentsBoolToInvoice' => $paymentsBoolToInvoice,
-                 'type' => $data['type'],
-                 'number' => $proformaId,
-                 'prefix' => $proformaPrefix,
-                 'date' => $data['date'],
-                 'token' => $data['token'],
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'currency' => $data['currency'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'payments' => $payments,
-                 'user_id' => $user_id,
-                 'form' => $form->createView(),
-                 'form1' => $form1->createView(),
-             )
-         );
-     }
-     private function baseInvoiceSelectedReservation($id, $arrayBools, $number)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $items = $em->getRepository(ReservationInvoiceProformaItems::class)->findByReservationId($reservation->getId());
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Acumuladores de los calculos
-         $totales_neto_all = 0;
-         $data_iva = array(
-             'iva' => 21,
-             'ivaMontoVeintiUno' => 0,
-             'ivaMontoDiez' => 0,
-             'ivaMontoCero' => 0,
-         );
-         //INICIO: Determinamos el numero de factura o proforma
-         if (substr($number,0,1) == 'I'){
-             // Es una Factura
-             $numberInvoiceOrProforma = substr($number,1);
-             $number = $numberInvoiceOrProforma;
-             $number = $em->getRepository(ReservationInvoice::class)->findOneById($number);
-             $number = $number->getNumber();
-             $type = 'Invoice';
-         } else {
-             // Es una Proforma
-             $numberInvoiceOrProforma = substr($number,1);
-             $number = $numberInvoiceOrProforma;
-             $number = $em->getRepository(ReservationProforma::class)->findOneById($number);
-             $number = $number->getPrefix().$number->getReservationId();
-             $type = 'Proforma';
-         }
-         //FIN: Determinamos el numero de factura o proforma
-         // Buscamos las salas reservadas, pagos y servicios para el evento
-         $arrayItems = array();
-         $reservationLounges = array();
-         if (!empty($arrayBools['lounge'])) {
-             foreach ($arrayBools['lounge'] as $key => $item) {
-                 if ($item == 'true') { $reservationLounges[] = $em->getRepository(ReservationLoungeSimple::class)->findOneById($key); }
-             }
-         }
-         $payments = array();
-         if (!empty($arrayBools['payment'])) {
-             foreach ($arrayBools['payment'] as $key => $item) {
-                 if ($item == 'true') { $payments[] = $em->getRepository(ReservationPaymentsClient::class)->findOneById($key); }
-             }
-         }
-         $services = array();
-         if (!empty($arrayBools['service'])) {
-             foreach ($arrayBools['service'] as $key => $item) {
-                 if ($item == 'true') { $services[] = $em->getRepository(ReservationService::class)->findOneById($key); }
-             }
-         }
-         $data_supplier = array();
-         $i = 0;
-         $iva = '21';            // Esteban Rincon: "Por Ley de localización del impuesto, siempre será un 21%". La ley ha cambiado.
-         $pax = '-';
-         $qty = '1';
-         $lounge = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         $service = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         foreach ($reservationLounges as $item){
-             if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
-                 $subtotal = 0;
-                 $neto = 0;
-                 $subnetoMounting = 0;
-                 $subtotalLounge = 0;
-                 $subnetoRemoval = 0;
-             } else {
- //                if (!empty($item->getMountingPrice()) and ($item->getMountingPrice() != 0 )){
- //                    $subtotalMounting = $item->getMountingPrice() * 1.21;
- //                    $subnetoMounting = $item->getMountingPrice();
- //                } else {
- //                    $subtotalMounting = 0;
- //                    $subnetoMounting = 0;
- //                }
-                 $subtotalLounge = $item->getServicePrice() * (1 + ($item->getIva() / 100));
-                 $subneto = $item->getServicePrice();
- //                if (!empty($item->getRemovalPrice()) and ($item->getRemovalPrice() != 0 )){
- //                    $subtotalRemoval = $item->getRemovalPrice() * 1.21;
- //                    $subnetoRemoval = $item->getRemovalPrice();
- //                } else {
- //                    $subtotalRemoval = 0;
- //                    $subnetoRemoval = 0;
- //                }
-                 $subtotal =  $subtotalLounge;
-                 $neto =  $subneto;
-                 $iva = $item->getIva();
-                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                 $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                 $neto = round($neto,2,PHP_ROUND_HALF_UP);
-                 $arrayItems[] = array(
-                     'type' => 'Lounge',
-                     'name' => $item->getLoungeName(),
-                     'amount' => $neto,
-                     'iva' => $iva,
-                     'total' => $subtotal,
-                 );
-             }
-             // Acumula netos totales e IVA
-             $totales_neto_all = $totales_neto_all + $neto;
- //            $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21);
-             switch ($iva){
-                 case 21: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
-                 case 10: $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * 0.1); break;
-                 case 0: break;
-                 default: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
-             }
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
-             // Acumula netos totales e IVA
-             $lounge['neto'] = $lounge['neto'] + $neto;
-             $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
-             $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
-             $data_supplier['lounge'][$i] = array (
-                 'id' => $item->getId(),
-                 'loungeName' => $item->getLoungeName(),
-                 'idLounge' => $item->getIdLounge(),
-                 'dateStart' => $item->getDateStart(),
-                 'dateEnd' => $item->getDateEnd(),
-                 'servicePrice' => $item->getServicePrice(),
-                 'subtotalLounge' => $subtotalLounge,
-                 'iva' => $iva,
-                 'pax' => $pax,
-                 'qty' => $qty,
-                 'type' => $item->getType(),
-                 'subtotal' => $subtotal,
-             );
-             $i++;
-         }
-         $data_supplier['loungeSubTotal'] = array(
-             'neto' => $lounge['neto'],
-             'sumSubT' => $lounge['sumSubT'],
-         );
-         $payment = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         $i = 0;
-         foreach ($payments as $item){
-             $payment['neto'] = $payment['neto'] + ($item->getAmount()*(-1));
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $payment['neto'] = round($payment['neto'],2,PHP_ROUND_HALF_UP);
-             $payment['sumSubT'] = $payment['sumSubT'] + ($item->getAmountTotal()*(-1));
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $payment['sumSubT'] = round($payment['sumSubT'],2,PHP_ROUND_HALF_UP);
-             $data_supplier['payment'][$i] = array (
-                 'id' => $item->getId(),
-                 'amount' => $item->getAmount()*(-1),
-                 'amountTotal' => $item->getAmountTotal()*(-1),
-                 'vat' => $item->getVat(),
-                 'datePayAt' => $item->getDatePayAt(),
-                 'wayToPay' => $item->getWayToPay(),
-             );
-             $arrayItems[] = array(
-                 'type' => 'Payment',
-                 'name' => $item->getWayToPay(),
-                 'amount' => $item->getAmount()*(-1),
-                 'total' => $item->getAmountTotal()*(-1),
-                 'iva' => $item->getVat(),
- //                    'iva' => '',
- //                    'total' => $item->getAmount(),
-             );
-             // Acumula netos totales e IVA
-             $totales_neto_all = $totales_neto_all + ($item->getAmount()*(-1));
-             $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + (($item->getAmount()*(-1)) * 0.21);
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
-             // Acumula netos totales e IVA
-             $i++;
-         }
-         if (!empty($payments)) {
-             $data_supplier['paymentSubTotal'] = array(
-                 'neto' => $payment['neto'],
-                 'sumSubT' => $payment['sumSubT'],
-             );
-         }
-         foreach ($services as $item) {
-             if (is_null($item->getPrice()) || empty($item->getPrice())) {
-                 $subtotal = 0;
-                 $neto = 0;
-                 $subtotalService = 0;
-             } else {
-                 // Inicialización de subtotalService y subneto
- //                $subtotalService = $item->getPrice();
- //                $subneto = $item->getPrice();
-                 // Manejar Comision y Over en precio unitario
-                 $priceExtra = (float)$item->getPrice();
-                 $commissionExtra = (float)$item->getCommission();
-                 $subnetoUnitExtra = ($item->getOpCommission() == '1')
-                     ? ($priceExtra + ($priceExtra * $commissionExtra / 100))
-                     : ($priceExtra - ($priceExtra * $commissionExtra / 100));
-                 $subnetoUnitExtra = ($item->getOpOver() == '1') ? ($subnetoUnitExtra + $item->getOver()) : ($subnetoUnitExtra - $item->getOver());
-                 $subneto = $subnetoUnitExtra;
-                 $subtotalService = $subnetoUnitExtra;
-                 // Comisión
-                 $commissionFactor = ($item->getOpCommission() === '1') 
-                     ? 1 + ($item->getCommission() / 100) 
-                     : 1 - ($item->getCommission() / 100);
-                 $subtotalService *= $commissionFactor;
-                 $subneto *= $commissionFactor;
-         
-                 // Cálculos comunes
-                 $pax = $item->getPax();
-                 if (empty($pax) || $pax == "0") { 
-                     $pax = 1; 
-                 }
-         
-                 $unitsServ = $item->getUnits();
-                 if (empty($unitsServ) || $unitsServ == "0") { 
-                     $unitsServ = 1; 
-                 }
-         
-                 // Mapeo de serviceCatId a serviceType
-                 $serviceTypes = [
-                     1 => 'Hotel',
-                     2 => 'Actividad',
-                     3 => 'AV',
-                     4 => 'Creativo',
-                     5 => 'Crucero',
-                     6 => 'Entretenimiento',
-                     7 => 'Regalos',
-                     8 => 'Guía',
-                     9 => 'Itinerarios',
-                     11 => 'Catering',
-                     12 => 'Otros',
-                     13 => 'Transporte',
-                     14 => 'Tecnología',
-                     15 => 'Asistente',
-                     16 => 'DDR',
-                     17 => 'Seguridad',
-                     18 => 'WiFi',
-                     19 => 'Mobiliario',
-                     20 => 'Parking',
-                     21 => 'Limpieza',
-                 ];
-         
-                 $serviceCatId = $item->getServiceCatId();
-                 $serviceType = isset($serviceTypes[$serviceCatId]) ? $serviceTypes[$serviceCatId] : 'Otros';
-         
-                 // Cálculo de días y fecha
-                 $dateIn = $item->getDateInAt();
-                 $dateOut = $item->getDateOutAt();
-                 $diffDays = $dateIn->diff($dateOut)->days;
-                 $days = ($serviceCatId === 1 || $serviceCatId === 5) ? $diffDays : $diffDays + 1;
-         
-                 $dateServ = ($days > 1) 
-                     ? $dateIn->format('d/m/Y') . ' - ' . $dateOut->format('d/m/Y') 
-                     : $dateIn->format('d/m/Y');
-         
-                 // Cálculo del subtotal y subneto
-                 $subtotal = $subtotalService * $days * $unitsServ * $pax;
-                 $subnetoUnit = $subneto;
-                 $subneto = $subneto * $days * $unitsServ * $pax;
-                 // Over
-                 $over = $item->getOver();
-                 $overFactor = ($item->getOpOver() === '1') ? 1 : -1;
-                 $subtotal += $overFactor * $over;
-                 $subneto += $overFactor * $over;
-         
-                 // Asignación al arreglo data_supplier
-                 $data_supplier['service'][$i] = [
-                     'id' => $item->getId(),
-                     'serviceCatId' => $serviceCatId,
-                     'serviceName' => $item->getName(),
-                     'serviceType' => $serviceType,
-                     'date' => $dateServ,
-                     'qty' => $unitsServ,
-                     'iva' => $item->getIva(),
-                     'pax' => $item->getPax(),
-                     'precioUnit' => $subnetoUnitExtra,
-                     'subneto' => $subneto,
-                     'subtotal' => round($subtotal, 2, PHP_ROUND_HALF_UP),
-                 ];
-         
-                 // Acumulación en arrayItems
-                 $arrayItems[] = [
-                     'type' => 'Service',
-                     'name' => $item->getName(),
-                     'amount' => round($subneto, 2, PHP_ROUND_HALF_UP),
-                     'iva' => $item->getIva(),
-                     'total' => round($subtotal, 2, PHP_ROUND_HALF_UP),
-                 ];
-         
-                 // Manejo de IVA
-                 switch ($item->getIva()) {
-                     case 21:
-                         $data_iva['ivaMontoVeintiUno'] += round($subneto * ($item->getIva() / 100), 2, PHP_ROUND_HALF_UP);
-                         break;
-         
-                     case 10:
-                         $data_iva['ivaMontoDiez'] += round($subneto * ($item->getIva() / 100), 2, PHP_ROUND_HALF_UP);
-                         break;
-         
-                     case 0:
-                     default:
-                         // No se acumula IVA
-                         break;
-                 }
-         
-                 // Acumulación de totales
-                 $totales_neto_all += $subneto;
-                 $totales_neto_all = round($totales_neto_all, 2, PHP_ROUND_HALF_UP);
-                 $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2, PHP_ROUND_HALF_UP);
-                 $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'], 2, PHP_ROUND_HALF_UP);
-         
-                 $service['neto'] += round($subneto, 2, PHP_ROUND_HALF_UP);
-                 $service['sumSubT'] += round($subtotal, 2, PHP_ROUND_HALF_UP);
-             }
-         
-             $i++;
-         }        
-         $data_supplier['serviceSubTotal'] = array(
-             'neto' => $service['neto'],
-             'sumSubT' => $service['sumSubT'],
-         );
-         $currency = '€';
-         $totales_total = $totales_neto_all + $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
-         if (!empty($payments)) {
-             $amount_pay = $data_supplier['paymentSubTotal']['sumSubT'];
-         } else {
-             $amount_pay = 0;
-         }
-         $totales_all = $totales_total - $amount_pay;
-         if ($type == 'Invoice'){
-             $em->clear();   // sin este clear se producia error al guardar
-             $newInvoice = $em->getRepository(ReservationInvoice::class)->findOneById($numberInvoiceOrProforma);
-             $newInvoice->setBalance($totales_all);
-             $em->persist($newInvoice);
-             $em->flush();
-         }
-         $data = array(
-             'id' => $id,
-             'type' => $type,
-             'number' => $number,
-             'prefix' => 'GPF-'.(new DateTime('now'))->format('dmy').'-',
-             'date' => new DateTime('now'),
-             'reservation' => $reservation,
-             'token' => $reservation->getAccessKey(),
-             'company' => $company,
-             'clients' => $client,
-             'arrayItems' => $arrayItems,
-             'datasupplier' => $data_supplier,
-             'currency' => $currency,
-             'totales_neto' => $totales_neto_all,
-             'bases_imponibles' => $data_iva,
-             'totales' => $totales_total,
-             'balance' => $totales_all,
-             'paymentInvoice' => $amount_pay,
-         );
-         return $data;
-     }
-     private function baseInvoiceDoneReservation($reservationId, $invoiceId, $typeBase)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $reservation = $em->getRepository(Reservation::class)->findOneById($reservationId);
-         $dateDocument = null;                                                                           //Fecha final del documento
-         if (($typeBase == 'I') or ($typeBase == 'P')) {
-             if ($typeBase == 'I') {
-                 $items = $em->getRepository(ReservationInvoiceItems::class)->findBy(array('reservationId' => $reservationId, 'invoiceId' => $invoiceId));
-             } else {
-                 // Es factura ni proforma
-                 $items = $em->getRepository(ReservationInvoiceProformaItems::class)->findBy(array('reservationId' => $reservationId, 'proformaId' => $invoiceId));
-             }
-         } else {
-             // No es factura ni proforma, es una rectificativa
-             $items = $em->getRepository(ReservationInvoiceRecItems::class)->findBy(array('reservationId' => $reservationId, 'invoiceRecId' => $invoiceId));
-         }
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Acumuladores de los calculos
-         $totales_neto_all = 0;
-         $data_iva = array(
-             'iva' => 21,
-             'ivaMontoVeintiUno' => 0,
-             'ivaMontoDiez' => 0,
-             'ivaMontoCero' => 0,
-         );
-         //INICIO: Determinamos el numero de factura o proforma
-         if ($typeBase == 'I'){
-             // Es una Factura
-             $number = $em->getRepository(ReservationInvoice::class)->findOneById($invoiceId);
-             $dateDocument = $number->getDateAt();
-             $number = $number->getNumber();
-             $type = 'Invoice';
-         } else {
-             if ($typeBase == 'R'){
-                 // Es una factura rectificativa
-                 $number = $em->getRepository(ReservationInvoiceRec::class)->findOneById($invoiceId);
-                 $dateDocument = $number->getDateAt();
-                 $type = 'Invoice Rec';
-             } else {
-                 // Es una Proforma
-                 $number = $invoiceId;
-                 $type = 'Proforma';
-             }
-         }
-         //FIN: Determinamos el numero de factura o proforma
-         // Buscamos las salas reservadas, pagos y servicios para el evento
-         $arrayItems = array();
-         $reservationLounges = array();
-         $payments = array();
-         $services = array();
-         if (!empty($items)) {
-             if (($typeBase == 'I') or ($typeBase == 'R')) {
-                 foreach ($items as $item) {
-                     switch ($item->getItemType()) {
-                         case 'LOUNGE': // Salon
-                             $reservationLounges[] = $item;
-                             break;
-                         case 'PAYMENT': // Pago
-                             $payments[] = $item;
-                             break;
-                         case 'SERVICE': // Servicio
-                             $services[] = $item;
-                             break;
-                         default: break;
-                     }
-                 }
-             } else {
-                 // Es una proforma
-                 foreach ($items as $item) {
-                     switch ($item->getType()) {
-                         case 'LOUNGE': // Salon
-                             $loungePro = $em->getRepository(ReservationLoungeSimple::class)->findOneById($item->getControlId());
-                             if (!empty($loungePro)) {
-                                 $reservationLounges[] = $loungePro;
-                             }
-                             break;
-                         case 'PAYMENT': // Pago
-                             $paymentPro = $em->getRepository(ReservationPaymentsClient::class)->findOneById($item->getControlId());
-                             if (!empty($paymentPro)) {
-                                 $payments[] = $paymentPro;
-                             }
-                             break;
-                         case 'SERVICE': // Servicio
-                             $servicePro = $em->getRepository(ReservationService::class)->findOneById($item->getControlId());
-                             if (!empty($servicePro)) {
-                                 $services[] = $servicePro;
-                             }
-                             break;
-                         default: break;
-                     }
-                 }
-             }
-         }
-         $data_supplier = array();
-         $i = 0;
-         $pax = '-';
-         $qty = '1';
-         $lounge = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         $service = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         foreach ($reservationLounges as $item){
-             if (($typeBase == 'I') or $typeBase == 'R') {
-                 $iva = $item->getLngIva();
-             } else {
-                 $iva = $item->getIva();
-             }
-             if(is_null($iva) || (empty($iva) && !is_numeric($iva))){
-                 $iva = 21;
-             }
-             
-             if (($typeBase == 'I') or ($typeBase == 'R')) {
-                 if (is_null($item->getLngServicePrice()) or empty($item->getLngServicePrice())){
-                     $subtotal = 0;
-                     $neto = 0;
-                     $subnetoMounting = 0;
-                     $subtotalLounge = 0;
-                     $subnetoRemoval = 0;
-                 } else {
- //                    $subtotalLounge = $item->getLngServicePrice() * 1.21;
-                     $subtotalLounge = $item->getLngServicePrice() * (1 + ($iva / 100));
-                     $subneto = $item->getLngServicePrice();
-                     $subtotal =  $subtotalLounge;
-                     $neto =  $subneto;
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                     $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                     $neto = round($neto,2,PHP_ROUND_HALF_UP);
-                     $arrayItems[] = array(
-                         'type' => 'Lounge',
-                         'name' => $item->getLngLoungeName(),
-                         'amount' => $neto,
-                         'iva' => $iva,
-                         'total' => $subtotal,
-                     );
-                 }
-             } else {
-                 // Es proforma
-                 if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
-                     $subtotal = 0;
-                     $neto = 0;
-                     $subnetoMounting = 0;
-                     $subtotalLounge = 0;
-                     $subnetoRemoval = 0;
-                 } else {
- //                    $subtotalLounge = $item->getServicePrice() * 1.21;
-                     $subtotalLounge = $item->getServicePrice() * (1 + ($iva / 100));
-                     $subneto = $item->getServicePrice();
-                     $subtotal =  $subtotalLounge;
-                     $neto =  $subneto;
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
-                     $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
-                     $neto = round($neto,2,PHP_ROUND_HALF_UP);
-                     $arrayItems[] = array(
-                         'type' => 'Lounge',
-                         'name' => $item->getLoungeName(),
-                         'amount' => $neto,
-                         'iva' => $iva,
-                         'total' => $subtotal,
-                     );
-                 }
-             }
-             // Acumula netos totales e IVA
-             $totales_neto_all = $totales_neto_all + $neto;
- //            $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21);
-             switch ($iva){
-                 case 21: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
-                 case 10: $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * 0.1); break;
-                 case 0: break;
-                 default: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
-             }
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
-             // Acumula netos totales e IVA
-             $lounge['neto'] = $lounge['neto'] + $neto;
-             $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
-             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-             $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
-             $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
-             if (($typeBase == 'I') or ($typeBase == 'R')) {
-                 $data_supplier['lounge'][$i] = array(
-                     'id' => $item->getId(),
-                     'loungeName' => $item->getLngLoungeName(),
-                     'idLounge' => $item->getLngIdLounge(),
-                     'dateStart' => $item->getLngDateStart(),
-                     'dateEnd' => $item->getLngDateEnd(),
-                     'servicePrice' => $item->getLngServicePrice(),
-                     'subtotalLounge' => $subtotalLounge,
-                     'iva' => $iva,
-                     'pax' => $pax,
-                     'qty' => $qty,
-                     'type' => $item->getLngType(),
-                     'subtotal' => $subtotal,
-                 );
-             } else {
-                 // Es proforma
-                 $data_supplier['lounge'][$i] = array(
-                     'id' => $item->getId(),
-                     'loungeName' => $item->getLoungeName(),
-                     'idLounge' => $item->getIdLounge(),
-                     'dateStart' => $item->getDateStart(),
-                     'dateEnd' => $item->getDateEnd(),
-                     'servicePrice' => $item->getServicePrice(),
-                     'subtotalLounge' => $subtotalLounge,
-                     'iva' => $iva,
-                     'pax' => $pax,
-                     'qty' => $qty,
-                     'type' => $item->getType(),
-                     'subtotal' => $subtotal,
-                 );
-             }
-             $i++;
-         }
-         $data_supplier['loungeSubTotal'] = array(
-             'neto' => $lounge['neto'],
-             'sumSubT' => $lounge['sumSubT'],
-         );
-         $payment = array(
-             'neto' => 0,
-             'sumSubT' => 0,
-         ); // Acumula sumatoria de netos y sumantoria de subtotales
-         $i = 0;
-         foreach ($payments as $item){
-             if (($typeBase == 'I') or ($typeBase == 'R')) {
-                 $ivaPayment = $item->getPayVat();
-                 if(is_null($ivaPayment) || (empty($ivaPayment) && !is_numeric($ivaPayment))){
-                     $ivaPayment = 21;
-                 }
-                 if ($typeBase == 'I') {
-                     $payment['neto'] = $payment['neto'] + ($item->getPayAmount() * (-1));
-                     $payment['sumSubT'] = $payment['sumSubT'] + ($item->getPayAmountTotal() * (-1));
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
-                     $payment['neto'] = round($payment['neto'], 2, PHP_ROUND_HALF_UP);
-                     // Acumula netos totales e IVA
-                     $totales_neto_all = $totales_neto_all + ($item->getPayAmount() * (-1));
-                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($item->getPayAmount() * (-($ivaPayment / 100)));
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $totales_neto_all = round($totales_neto_all, 2, PHP_ROUND_HALF_UP);
-                     $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2, PHP_ROUND_HALF_UP);
-                     // Acumula netos totales e IVA
-                     $data_supplier['payment'][$i] = array(
-                         'id' => $item->getId(),
-                         'amount' => $item->getPayAmount() * (-1),
-                         'amountTotal' => $item->getPayAmountTotal() * (-1),
-                         'vat' => $item->getPayVat(),
-                         'datePayAt' => $item->getPayDatePayAt(),
-                         'wayToPay' => $item->getPayWayToPay(),
-                     );
-                     $arrayItems[] = array(
-                         'type' => 'Payment',
-                         'name' => $item->getPayWayToPay(),
-                         'amount' => $item->getPayAmount() * (-1),
-                         'total' => $item->getPayAmountTotal() * (-1),
-                         'iva' => $item->getPayVat(),
- //                    'iva' => '',
- //                    'total' => $item->getPayAmount(),
-                     );
-                 } else {
-                     //Es una rectificativa
-                     $payment['neto'] = $payment['neto'] + ($item->getPayAmount());
-                     $payment['sumSubT'] = $payment['sumSubT'] + ($item->getPayAmountTotal());
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
-                     $payment['neto'] = round($payment['neto'], 2, PHP_ROUND_HALF_UP);
-                     // Acumula netos totales e IVA
-                     $totales_neto_all = $totales_neto_all + ($item->getPayAmount());
-                     $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($item->getPayAmount()*($ivaPayment / 100));
-                     // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                     $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
-                     $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
-                     // Acumula netos totales e IVA
-                     $data_supplier['payment'][$i] = array(
-                         'id' => $item->getId(),
-                         'amount' => $item->getPayAmount(),
-                         'amountTotal' => $item->getPayAmountTotal(),
-                         'vat' => $item->getPayVat(),
-                         'datePayAt' => $item->getPayDatePayAt(),
-                         'wayToPay' => $item->getPayWayToPay(),
-                     );
-                     $arrayItems[] = array(
-                         'type' => 'Payment',
-                         'name' => $item->getPayWayToPay(),
-                         'amount' => $item->getPayAmount(),
-                         'total' => $item->getPayAmountTotal(),
-                         'iva' => $item->getPayVat(),
- //                    'iva' => '',
- //                    'total' => $item->getPayAmount(),
-                     );
-                 }
-             } else {
-                 $ivaPayment = $item->getVat();
-                 if(is_null($ivaPayment) || (empty($ivaPayment) && !is_numeric($ivaPayment))){
-                     $ivaPayment = 21;
-                 }
-                 // Es una proforma
-                 $payment['neto'] = $payment['neto'] + ($item->getAmount()*(-1));
-                 $payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal()*(-1);
-                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                 $payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
-                 $payment['neto'] = round($payment['neto'], 2, PHP_ROUND_HALF_UP);
-                 // Acumula netos totales e IVA
-                 $totales_neto_all = $totales_neto_all + ($item->getAmount()*(-1));
-                 $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($item->getAmount()*(-($ivaPayment / 100)));
-                 // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
-                 $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
-                 $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
-                 // Acumula netos totales e IVA
-                 $data_supplier['payment'][$i] = array(
-                     'id' => $item->getId(),
-                     'amount' => $item->getAmount()*(-1),
-                     'amountTotal' => $item->getAmountTotal()*(-1),
-                     'vat' => $item->getVat(),
-                     'datePayAt' => $item->getDatePayAt(),
-                     'wayToPay' => $item->getWayToPay(),
-                 );
-                 $arrayItems[] = array(
-                     'type' => 'Payment',
-                     'name' => $item->getWayToPay(),
-                     'amount' => $item->getAmount()*(-1),
-                     'total' => $item->getAmountTotal()*(-1),
-                     'iva' => $item->getVat(),
- //                    'iva' => '',
- //                    'total' => $item->getAmount(),
-                 );
-             }
-             $i++;
-         }
-         if (!empty($payments)) {
-             $data_supplier['paymentSubTotal'] = array(
-                 'neto' => $payment['neto'],
-                 'sumSubT' => $payment['sumSubT'],
-             );
-         }
-         foreach ($services as $item) {
-             // Inicialización de variables basadas en typeBase
-             if ($typeBase === 'I' || $typeBase === 'R') {
-                 $price = $item->getSrvPrice();
-                 $opCommission = $item->getSrvOpCommission();
-                 $commission = $item->getSrvCommission();
-                 $opOver = $item->getSrvOpOver();
-                 $over = $item->getSrvOver();
-                 $opIva = $item->getSrvOpIva();
-                 $iva = $item->getSrvIva();
-                 $serviceCatId = $item->getSrvServiceCatId();
-                 $dateInAt = $item->getSrvDateInAt();
-                 $dateOutAt = $item->getSrvDateOutAt();
-                 $units = $item->getSrvUnits();
-                 $name = $item->getSrvName();
-                 $id = $item->getId();
-                 $pax = $item->getSrvPax(); // Valor predeterminado para Alojamiento
-             } else {
-                 // Proforma
-                 $price = $item->getPrice();
-                 $opCommission = $item->getOpCommission();
-                 $commission = $item->getCommission();
-                 $opOver = $item->getOpOver();
-                 $over = $item->getOver();
-                 $opIva = $item->getOpIva();
-                 $iva = $item->getIva();
-                 $serviceCatId = $item->getServiceCatId();
-                 $dateInAt = $item->getDateInAt();
-                 $dateOutAt = $item->getDateOutAt();
-                 $units = $item->getUnits();
-                 $name = $item->getName();
-                 $id = $item->getId();
-                 $pax = $item->getPax();
-             }
-             // Verificación de precio nulo o vacío
-             if (is_null($price)) {
-                 $subtotal = 0;
-                 $neto = 0;
-                 $subtotalService = 0;
-             } else {
-                 // Procesamiento del precio
- //                $subtotalService = floatval(str_replace(',', '.', $price));
- //                $subneto = floatval(str_replace(',', '.', $price));
-                 // Manejar Comision y Over en precio unitario
-                 $priceExtra = ($typeBase == 'P') ? (float)$item->getPrice() : (float)$item->getSrvPrice();
-                 $commissionExtra = ($typeBase == 'P') ? (float)$item->getCommission() : (float)$item->getSrvCommission();
-                 if ($typeBase == 'P') {
-                     $subnetoUnitExtra = ($item->getOpCommission() == '1')
-                         ? ($priceExtra + ($priceExtra * $commissionExtra / 100))
-                         : ($priceExtra - ($priceExtra * $commissionExtra / 100));
-                 } else {
-                     $subnetoUnitExtra = ($item->getSrvOpCommission() == '1')
-                         ? ($priceExtra + ($priceExtra * $commissionExtra / 100))
-                         : ($priceExtra - ($priceExtra * $commissionExtra / 100));
-                 }
-                 if ($typeBase == 'P') {
-                     $subnetoUnitExtra = ($item->getOpOver() == '1') ? ($subnetoUnitExtra + $item->getOver()) : ($subnetoUnitExtra - $item->getOver());
-                 } else {
-                     $subnetoUnitExtra = ($item->getSrvOpOver() == '1') ? ($subnetoUnitExtra + $item->getSrvOver()) : ($subnetoUnitExtra - $item->getSrvOver());
-                 }
-                 $subneto = $subnetoUnitExtra;
-                 $subtotalService = $subnetoUnitExtra;
-         
-                 // Cálculo de Comisión
- //                if ($opCommission === '1') {
- //                    $subtotalService *= (1 + ($commission / 100));
- //                    $subneto *= (1 + ($commission / 100));
- //                } else {
- //                    $subtotalService *= (1 - ($commission / 100));
- //                    $subneto *= (1 - ($commission / 100));
- //                }
-         
-                 
-         
-                 // Mapeo de serviceCatId a serviceType
-                 $serviceTypes = [
-                     1 => 'Hotel',
-                     2 => 'Actividad',
-                     3 => 'AV',
-                     4 => 'Creativo',
-                     5 => 'Crucero',
-                     6 => 'Entretenimiento',
-                     7 => 'Regalos',
-                     8 => 'Guía',
-                     9 => 'Itinerarios',
-                     10 => 'Lounge', // No Aplica
-                     11 => 'Catering',
-                     12 => 'Otros',
-                     13 => 'Transporte',
-                     14 => 'Tecnología',
-                     15 => 'Asistente',
-                     16 => 'DDR',
-                     17 => 'Seguridad',
-                     18 => 'WiFi',
-                     19 => 'Mobiliario',
-                     20 => 'Parking',
-                     21 => 'Limpieza',
-                 ];
-         
-                 $serviceType = isset($serviceTypes[$serviceCatId]) ? $serviceTypes[$serviceCatId] : 'Otros';
-         
-                 // Cálculos específicos según serviceCatId
-                 if ($serviceCatId === 1) { // Alojamiento
-                     $numNoches = $dateOutAt->diff($dateInAt)->days;
-                     $subtotal = $subtotalService * $numNoches * $units;
-                     $subnetoUnit = $subneto;
-                     $subneto *= $numNoches * $units;
-                     $dateServ = $dateInAt->format('d/m/Y') . ' - ' . $dateOutAt->format('d/m/Y');
-                     $paxDisplay = '-';
-                     $qty = $units;
-                 } else {
-                     // Para otros tipos de servicio
-                     $pax = (empty($pax) || $pax == "0" ? 1 : $pax);
-                     $days = in_array($serviceCatId, [5, 7, 14]) ? (($serviceCatId === 5) ? $dateOutAt->diff($dateInAt)->days : 1) : ($dateOutAt->diff($dateInAt)->days + 1);
-                     $dateServ = ($days > 1) ? $dateInAt->format('d/m/Y') . ' - ' . $dateOutAt->format('d/m/Y') : $dateInAt->format('d/m/Y');
-                     $unitsServ = empty($units) || $units == "0" ? 1 : $units;
-                     $subtotal = $subtotalService * $days * $unitsServ * (($pax !== '-') ? $pax : 1);
-                     $subnetoUnit = $subneto;
-                     $subneto *= $days * $unitsServ * (($pax !== '-') ? $pax : 1);
-                     $paxDisplay = ($serviceCatId !== 1) ? $pax : '-';
-                     $qty = $unitsServ;
-                 }
-                 // Cálculo de Over
- //                if ($opOver === '1') {
- //                    $subtotal += $over;
- //                    $subneto += $over;
- //                } else {
- //                    $subtotal -= $over;
- //                    $subneto -= $over;
- //                }
-                 // Asignación de datos al array data_supplier
-                 $data_supplier['service'][$i] = [
-                     'id' => $id,
-                     'serviceCatId' => $serviceCatId,
-                     'serviceName' => $name,
-                     'serviceType' => $serviceType,
-                     'date' => $dateServ,
-                     'qty' => $qty,
-                     'iva' => $iva,
-                     'pax' => $paxDisplay,
-                     'precioUnit' => $subnetoUnitExtra,
-                     'subneto' => $subneto,
-                     'subtotal' => round($subtotal, 2, PHP_ROUND_HALF_UP),
-                 ];
-                 // Aplicar IVA
-                 if ($typeBase == 'P') {
-                     if ($item->getOpIva() == '1') {
-                         $subtotal *= (1 + ($item->getIva() / 100));
-                     } else {
-                         $subtotal = ($item->getPrice() * 100) / (100 + $item->getIva());
-                         $subneto = ($subneto * 100) / (100 + $item->getIva());
-                     }
-                 } else {
-                     if ($item->getSrvOpIva() == '1') {
-                         $subtotal *= (1 + ($item->getSrvIva() / 100));
-                     } else {
-                         $subtotal = ($item->getSrvPrice() * 100) / (100 + $item->getSrvIva());
-                         $subneto = ($subneto * 100) / (100 + $item->getSrvIva());
-                     }
-                 }
-                 // Actualizar subtotal y subneto en data_supplier
-                 $data_supplier['service'][$i]['subneto'] = $subneto;
-                 $data_supplier['service'][$i]['subtotal'] = $subtotal;
-                 // Acumular subtotales
-                 $subtotal = round($subtotal, 2, PHP_ROUND_HALF_UP);
-                 $neto = round($subneto, 2, PHP_ROUND_HALF_UP);
-         
-                 // Redondeo de valores
-                 $subtotal = round($subtotal, 2, PHP_ROUND_HALF_UP);
-                 $neto = round($subneto, 2, PHP_ROUND_HALF_UP);
-         
-                 // Asignación a arrayItems
-                 $arrayItems[] = [
-                     'type' => 'Service',
-                     'name' => $name,
-                     'amount' => $neto,
-                     'iva' => $iva,
-                     'total' => $subtotal,
-                 ];
-             }
-         
-             // Acumulación de IVA
-             switch ($iva) {
-                 case 21:
-                     $data_iva['ivaMontoVeintiUno'] += ($neto * ($iva / 100));
-                     break;
-         
-                 case 10:
-                     $data_iva['ivaMontoDiez'] += ($neto * ($iva / 100));
-                     break;
-         
-                 case 0:
-                 default:
-                     break;
-             }
-         
-             // Acumulación de totales
-             $totales_neto_all += $neto;
-             $totales_neto_all = round($totales_neto_all, 2, PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'], 2, PHP_ROUND_HALF_UP);
-             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'], 2, PHP_ROUND_HALF_UP);
-         
-             $service['neto'] += $neto;
-             $service['sumSubT'] += $subtotal;
-             $service['neto'] = round($service['neto'], 2, PHP_ROUND_HALF_UP);
-             $service['sumSubT'] = round($service['sumSubT'], 2, PHP_ROUND_HALF_UP);
-         
-             $i++;
-         }
-         $data_supplier['serviceSubTotal'] = array(
-             'neto' => $service['neto'],
-             'sumSubT' => $service['sumSubT'],
-         );
-         $currency = '€';
-         $totales_total = $totales_neto_all + $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
-         if (!empty($payments)) {
-             $amount_pay = $data_supplier['paymentSubTotal']['sumSubT'];
-         } else {
-             $amount_pay = 0;
-         }
-         $totales_all = $totales_total - $amount_pay;
-         if (empty($dateDocument)){
-             $dateDocument = new DateTime('now');
-         }
-         $data = array(
-             'id' => $reservationId,
-             'type' => $type,
-             'number' => $number,
-             'prefix' => 'GP-'.(new DateTime('now'))->format('dmy').'-',
-             'date' => $dateDocument,
-             'reservation' => $reservation,
-             'token' => $reservation->getAccessKey(),
-             'company' => $company,
-             'clients' => $client,
-             'arrayItems' => $arrayItems,
-             'datasupplier' => $data_supplier,
-             'currency' => $currency,
-             'totales_neto' => $totales_neto_all,
-             'bases_imponibles' => $data_iva,
-             'totales' => $totales_total,
-             'balance' => $totales_all,
-             'paymentInvoice' => $amount_pay,
-         );
-         return $data;
-     }
-     /**
-      * @Route("/reservations/newinvoicedeposit/proforma/{id}",  name="reservation_new_invoice_deposit_proforma")
-      */
-     public function detailsNewProformaInvoiceDepositAction($id, Request $request){
-         // Generamos Proforma de deposito
-        $proformaDeposit = $request->request->get('invoicedep');
-        if (empty($proformaDeposit['name']) or empty($proformaDeposit['amount'])){
-            // Se necesitan todos los datos
-            return $this->redirectToRoute('reservations_payment', array( 'id' => $id ) );
-        }
-         $em = $this->getDoctrine()->getManager();
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         // Obtenemos el Id a asignar a la proforma de deposito y se guarda en Number
-         $allInvoicedeposititems = $em->getRepository(ReservationProformaDeposit::class)->findAll();
-         if (!empty($allInvoicedeposititems)){
-             $number = end($allInvoicedeposititems)->getId() + 1;
-         } else {
-             $number = 1;
-         }
-         $total = floatval(str_replace( ',', '.', $proformaDeposit['amount'])) + ((floatval(str_replace( ',', '.', $proformaDeposit['amount'])) * $proformaDeposit['iva'])/100);
-         $total = round($total, 2);
-         $ivaNew = (empty($proformaDeposit['iva'])) ? 0 : $proformaDeposit['iva'];
-         $newProformaDeposit = new ReservationProformaDeposit();
-         $newProformaDeposit->setDateAt(new DateTime('now'));
-         $newProformaDeposit->setReservationId($id);
-         $newProformaDeposit->setName($proformaDeposit['name']);
-         $newProformaDeposit->setAmount(str_replace( ',', '.', $proformaDeposit['amount']));
-         $newProformaDeposit->setIva($ivaNew);
-         $newProformaDeposit->setNumber($number);
-         $newProformaDeposit->setTotal($total);
-         $newProformaDeposit->setPrefix('IFD-');
-         $newProformaDeposit->setCreatedId($user_id);
-         $newProformaDeposit->setUpdatedId($user_id);
-         $newProformaDeposit->setCreatedAt(new DateTime('now'));
-         $newProformaDeposit->setUpdatedAt(new DateTime('now'));
-         $em->persist($newProformaDeposit);
-         $em->flush();
-         $invoicedeposititems = $em->getRepository(ReservationProformaDeposit::class)->findBy(
-             array(
-                 'reservationId' => $id,
-                 'number' => $number,
-             )
-         );
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         // Buscamos el cliente
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Buscamos el cliente
-         $allInvoiceDeposit = $em->getRepository(ReservationProformaDeposit::class)->findBy(
-             array(
-                 'reservationId' => $id,
-             )
-         );
-         $totales_iva = (str_replace( ',', '.', $proformaDeposit['amount']) * $proformaDeposit['iva'])/100;
-         $totales = str_replace( ',', '.', $proformaDeposit['amount']) + $totales_iva;
-         $boolToRec = false;
-         return $this->redirectToRoute('reservation_view_new_invoice_deposit_proforma',array('id' => $newProformaDeposit->getId()));
-     }
-     /**
-      * @Route("/reservations/newinvoicedeposit/viewproforma/{id}",  name="reservation_view_new_invoice_deposit_proforma")
-      */
-     public function detailsViewNewProformaInvoiceDepositAction($id, Request $request){
-         // Visualizar Proforma de Deposito
-         $em = $this->getDoctrine()->getManager();
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $newProformaDeposit = $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
-         $total = $newProformaDeposit->getAmount() + (($newProformaDeposit->getAmount() * $newProformaDeposit->getIva())/100);
-         $invoicedeposititems = $em->getRepository(ReservationProformaDeposit::class)->findBy(
-             array(
-                 'reservationId' => $newProformaDeposit->getReservationId(),
-                 'number' => $id,
-             )
-         );
-         $invoiceDeposit = $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         // Buscamos el cliente
-         $reservation = $em->getRepository(Reservation::class)->findOneById($invoiceDeposit->getReservationId());
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Buscamos el cliente
-         $allInvoiceDeposit = $em->getRepository(ReservationProformaDeposit::class)->findBy(
-             array(
-                 'reservationId' => $invoiceDeposit->getReservationId(),
-             )
-         );
-         $totales_iva = ($newProformaDeposit->getAmount() * $newProformaDeposit->getIva())/100;
-         $totales = $newProformaDeposit->getAmount() + $totales_iva;
-         $boolToRec = false; // Una proforma no se va a rectificar
-         $reservaEquis = $em->getRepository(Reservation::class)->findOneById($invoiceDeposit->getReservationId());
- //                if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-         if(true){ $newInvoice = $this->clientDataToInvoice(null, 'Client', $reservaEquis->getClient(), $reservaEquis->getId()); }
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
-             array(
-                 'id' => $invoiceDeposit->getReservationId(),
-                 'cid' => '',
-                 'fid' => $newProformaDeposit->getId(),
-                 'invoice' => '',
-                 'numberadmin' => $newProformaDeposit->getId(),
-                 'type' => 'Proforma Deposit',
-                 'number' => $newProformaDeposit->getId(),
-                 'prefix' => '',
-                 'date' => '',
-                 'token' =>  '',
-                 'company' => $company,
-                 'clients' => $client,
-                 'user' => $user_logueado,
-                 'boolToRec' => $boolToRec,
-                 'invoicedeposititems' => $invoicedeposititems,
-                 'allProformaDeposit' => $allInvoiceDeposit,
-                 'totales_neto' => $newProformaDeposit->getAmount(),
-                 'totales_iva' => $totales_iva,
-                 'totales' => $totales,
-                 'bases_imponibles' => $newProformaDeposit->getIva(),
-                 'currency' => '€',
-                 'clientName' => $newInvoice->getClientName(),
-                 'clientAddress' => $newInvoice->getClientAddress(),
-                 'clientDocument' => $newInvoice->getClientDocument(),
- //                'mcp' => $proposal->getMcp(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/newinvoicedeposit/invoice/{id}",  name="reservation_new_invoice_deposit_invoice")
-      */
-     public function detailsNewInvoiceDepositAction($id, Request $request){
-         // Generamos la nueva factura de deposito
-         $em = $this->getDoctrine()->getManager();
-         $proformaDeposit = $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
-         $vat = ($proformaDeposit->getAmount() * $proformaDeposit->getIva())/100;
-         $vat = round($vat,2);
-         $totalInvoiceDep = $proformaDeposit->getAmount() + $vat;
-         $totalInvoiceDep = round($totalInvoiceDep, 2);
-         $balanceInvoiceDep = $totalInvoiceDep * (-1);  // una factura de deposito es ingreso a caja por eso multiplicamos por -1
-         if (empty($proformaDeposit->getName()) or empty($proformaDeposit->getAmount())){
-             // Se necesitan todos los datos
-             return $this->redirectToRoute('reservations_payment', array( 'id' => $proformaDeposit->getReservationId()));
-         }
-         // INICIO: Verificamos la linea de facturacion
-         $parameters = array( 'id' => $proformaDeposit->getReservationId(), );
-         $dql = 'SELECT p
-                 FROM GreenPatioBundle:ReservationLoungeSimple p
-                 WHERE p.idReservation = :id AND p.idLounge > 21';
-         $query = $em->createQuery($dql)->setParameters($parameters);
-         $loungesSimples = $query->getResult();
-         if (!empty($loungesSimples)){
-             // Redirigir a Covarrubias
- //            return $this->redirectToRoute('reservation_new_invoice_deposit_invoice_cvr', array( 'id' => $id, ) );
-         }
-         // FIN: Verificamos la linea de facturacion
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         // INICIO: Generamos la factura
-         $invoice = new ReservationInvoice();
-         $invoice->setNumber('GPF-'.date('d').date('m').substr(date('Y'),-2).'-'.$proformaDeposit->getReservationId());
-         $invoice->setPrefix(null);
-         $invoice->setDateAt(new DateTime('now'));
-         $invoice->setType('Invoice Deposit');
-         $invoice->setReservationId($proformaDeposit->getReservationId());;
-         $invoice->setTotalNet($proformaDeposit->getAmount());
-         $invoice->setVat($vat);
-         $invoice->setTotal($totalInvoiceDep);
-         $invoice->setBalance($balanceInvoiceDep);
-         $invoice->setMaster('master');
-         $invoice->setCreatedAt(new DateTime('now'));
-         $invoice->setUpdatedAt(new DateTime('now'));
-         $invoice->setCreatedId($user_id);
-         $invoice->setUpdatedId($user_id);
-         $reservaEquis = $em->getRepository(Reservation::class)->findOneById($proformaDeposit->getReservationId());
-         if(true){ $invoice = $this->clientDataToInvoice($invoice, 'Client', $reservaEquis->getClient(), $reservaEquis->getId()); }
-         $em->persist($invoice);
-         $em->flush();
-         // FIN: Generamos la factura
-         // INICIO: Generamos el invoice deposit Control
-         $control = new ReservationInvoiceDepositControl();
-         $control->setPrefix('IFD-');
-         $control->setNumber($invoice->getId());
-         $control->setDateAt(new DateTime('now'));
-         $control->setReservationId($proformaDeposit->getReservationId());
-         $control->setCreatedAt(new DateTime('now'));
-         $control->setUpdatedAt(new DateTime('now'));
-         $control->setCreatedId($user_id);
-         $control->setUpdatedId($user_id);
-         $em->persist($control);
-         $em->flush();
-         // FIN: Generamos el invoice deposit Control
-         // INICIO: Generamos el invoice deposit item
-         $invDepositItem = new ReservationInvoiceDepositItems();
-         $invDepositItem->setControlId($control->getId());
-         $invDepositItem->setName($proformaDeposit->getName());
-         $invDepositItem->setAmount($proformaDeposit->getAmount());
-         $invDepositItem->setIva($proformaDeposit->getIva());
-         $invDepositItem->setReservationId($proformaDeposit->getReservationId());
-         $invDepositItem->setCreatedAt(new DateTime('now'));
-         $invDepositItem->setUpdatedAt(new DateTime('now'));
-         $invDepositItem->setCreatedId($user_id);
-         $invDepositItem->setUpdatedId($user_id);
-         $em->persist($invDepositItem);
-         $em->flush();
-         // FIN: Generamos el invoice deposit item
-         // INICIO: Generamos el pago asociado
-         // Por solicitud de Esteban Rincon se genera de forma automatica un pago para representar en la factura final el descuento por concepto de factura de deposito
-         $payment = new ReservationPaymentsClient();
-         $payment->setDatePayAt(new DateTime('now'));
-         $payment->setAmount($proformaDeposit->getAmount());
-         $payment->setVat($proformaDeposit->getIva());
-         $payment->setAmountTotal($proformaDeposit->getAmount() + ($proformaDeposit->getAmount() * $proformaDeposit->getIva())/100);
-         $payment->setWayToPay('FACTURA DE DEPOSITO');
-         $payment->setReservationId($proformaDeposit->getReservationId());;
-         $payment->setInvoiceId($invoice->getId());
-         $payment->setCreatedAt(new DateTime('now'));
-         $payment->setUpdatedAt(new DateTime('now'));
-         $payment->setCreatedId($user_id);
-         $payment->setUpdatedId($user_id);
-         $em->persist($payment);
-         $em->flush();
-         $payment->setWayToPay($payment->getWayToPay().' - '.$invoice->getId());
-         $em->persist($payment);
-         $em->flush();
-         // INICIO: Generamos el pago asociado
-         $total = $totalInvoiceDep;
-         $invoicedeposititems = array();
-         $invoicedeposititems[] = $invDepositItem;
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         // Buscamos el cliente
-         $reservation = $em->getRepository(Reservation::class)->findOneById($proformaDeposit->getReservationId());
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Buscamos el cliente
-         $allInvoiceDeposit = $em->getRepository(ReservationInvoice::class)->findBy(
-             array(
-                 'reservationId' => $invoice->getReservationId(),
-             )
-         );
-         $totales_iva = $vat;
-         $totales = $invoice->getTotalNet() + $totales_iva;
-         // Una factura solo se puede rectificar una vez
-         $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $invoice->getId()));
-         $boolToRec = empty($rectf);
-         return $this->redirectToRoute('reservation_view_new_invoice_deposit',array('id' => $invoice->getId()));
-     }
-     /**
-      * @Route("/reservations/newinvoicedeposit/viewinvoicedeposit/{id}",  name="reservation_view_new_invoice_deposit")
-      */
-     public function detailsViewNewInvoiceDepositAction($id, Request $request){
-         // Visualizar Factura de Deposito
-         $em = $this->getDoctrine()->getManager();
-         $dateDocument = null;                                           // Fecha del documento
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $newProformaDeposit = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-         if(!empty($newProformaDeposit)){ $dateDocument = $newProformaDeposit->getDateAt(); }
-         $total = $newProformaDeposit->getTotal();
-         $controlInvDep = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneByNumber($id);
-         $invoicedeposititems = $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
-             array(
-                 'reservationId' => $newProformaDeposit->getReservationId(),
-                 'controlId' => $controlInvDep->getId(),
-             )
-         );
-         if (!empty($invoicedeposititems)){$bases_imponibles = $invoicedeposititems[0]->getIva();} else {$bases_imponibles = '';}
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         // Buscamos el cliente
-         $reservation = $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Buscamos el cliente
-         $allInvoiceDeposit = $em->getRepository(ReservationInvoice::class)->findBy(
-             array(
-                 'reservationId' => $newProformaDeposit->getReservationId(),
-             )
-         );
-         $totales_iva = $newProformaDeposit->getVat();
-         $totales = $newProformaDeposit->getTotal();
-         // Una factura solo se puede rectificar una vez
-         $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $newProformaDeposit->getId()));
-         $boolToRec = empty($rectf);
-         $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
-         if(empty($newProformaDeposit->getClientName()) and empty($newProformaDeposit->getClientAddress()) and empty($newProformaDeposit->getClientDocument())){
-             $newProformaDeposit = $this->clientDataToInvoice($newProformaDeposit, 'Client', $reservaEquis->getClient(), $newProformaDeposit->getReservationId());
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
-             array(
-                 'id' => $newProformaDeposit->getReservationId(),
-                 'cid' => '',
-                 'fid' => $newProformaDeposit->getId(),
-                 'invoice' => '',
-                 'numberadmin' => $newProformaDeposit->getId(),
-                 'type' => 'Invoice Deposit',
-                 'number' => $newProformaDeposit->getId(),
-                 'prefix' => '',
-                 'date' => $dateDocument,
-                 'token' =>  '',
-                 'company' => $company,
-                 'clients' => $client,
-                 'user' => $user_logueado,
-                 'boolToRec' => $boolToRec,
-                 'invoicedeposititems' => $invoicedeposititems,
-                 'allProformaDeposit' => $allInvoiceDeposit,
-                 'totales_neto' => $newProformaDeposit->getTotalNet(),
-                 'totales_iva' => $totales_iva,
-                 'totales' => $totales,
-                 'bases_imponibles' => $bases_imponibles,
-                 'currency' => '€',
-                 'clientName' => $newProformaDeposit->getClientName(),
-                 'clientAddress' => $newProformaDeposit->getClientAddress(),
-                 'clientDocument' => $newProformaDeposit->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/newinvoicedeposit/invoicerec/{id}",  name="reservation_new_invoice_deposit_invoicerec")
-      */
-     public function detailsNewInvoiceDepositRecAction($id, Request $request){
-         // Generamos la factura de deposito rectificativa
-         $em = $this->getDoctrine()->getManager();
-         if (true){
-             // Verificamos que no exista una factura rectificativa previa sobre la misma factura
-             $previusInvoiceRec = $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($id);
-             if (!empty($previusInvoiceRec)){ return $this->redirectToRoute('reservation_view_new_invoice_deposit_rec', array('id' => $previusInvoiceRec->getId())); }
-         }
-         $proformaDeposit = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-         $vat = $proformaDeposit->getVat() * (-1);                   // En una rectificativa Esteban ha pedido todos los valores en negativo
-         $totalInvoiceDep = $proformaDeposit->getTotal() * (-1);
-         $balanceInvoiceDep = $proformaDeposit->getBalance() * (-1);  //una factura de deposito rectificativa  es egreso a caja por eso multiplicamos por -1 lo que teniamos como ingreso
-         // Buscamos el Id del deposit item a partir de la factura
-         $resDepControl = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneByNumber($id);
-         $resInvDepItem = $em->getRepository(ReservationInvoiceDepositItems::class)->findOneByControlId($resDepControl->getId());
-         $equisInv = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         // INICIO: Generamos la factura de deposito rectificativa
-         $invoice = new ReservationInvoiceRec();
-         $invoice->setNumber('REC-GPFD-'.date('d').date('m').substr(date('Y'),-2).'-'.$proformaDeposit->getReservationId());
-         $invoice->setPrefix(null);
-         $invoice->setDateAt(new DateTime('now'));
-         $invoice->setType('Invoice Deposit Rec');
-         $invoice->setInvoiceToRec($id);
-         $invoice->setReservationId($proformaDeposit->getReservationId());;
-         $invoice->setTotalNet($proformaDeposit->getTotalNet()*(-1));
-         $invoice->setVat($vat);
-         $invoice->setTotal($totalInvoiceDep);
-         $invoice->setBalance($balanceInvoiceDep);
-         $invoice->setMaster('master');
-         $invoice->setCreatedAt(new DateTime('now'));
-         $invoice->setUpdatedAt(new DateTime('now'));
-         $invoice->setCreatedId($user_id);
-         $invoice->setUpdatedId($user_id);
-         $invoice->setClientName($equisInv->getClientName());
-         $invoice->setClientAddress($equisInv->getClientAddress());
-         $invoice->setClientDocument($equisInv->getClientDocument());
-         $invoice->setClientType($equisInv->getClientType());
-         $em->persist($invoice);
-         $em->flush();
-         // FIN: Generamos la factura de deposito rectificativa
-         // INICIO: Generamos el invoice rec item
-         $invDepositItem = new ReservationInvoiceRecItems();
-         $invDepositItem->setDepControlId($resInvDepItem->getId());
-         $invDepositItem->setDepName($resInvDepItem->getName());
-         $invDepositItem->setDepAmount($resInvDepItem->getAmount() * (-1));              // Esteban ha pedido todos los datos de la rectificativa en negativo
-         $invDepositItem->setDepIva($resInvDepItem->getIva());
-         $invDepositItem->setDepDateAt($resDepControl->getDateAt());
-         $invDepositItem->setReservationId($proformaDeposit->getReservationId());
-         $invDepositItem->setCreatedAt(new DateTime('now'));
-         $invDepositItem->setUpdatedAt(new DateTime('now'));
-         $invDepositItem->setCreatedId($user_id);
-         $invDepositItem->setUpdatedId($user_id);
-         $invDepositItem->setInvoiceId($id);
-         $invDepositItem->setItemType('DEPOSIT');
-         $invDepositItem->setInvoiceRecId($invoice->getId());
-         $em->persist($invDepositItem);
-         $em->flush();
-         // FIN: Generamos el invoice deposit item
-         // INICIO: Buscamos Pagos asociados a la factura de deposito (se crean de forma automatica, se van a eliminar de forma automatica)
-         $payToDelete = $em->getRepository(ReservationPaymentsClient::class)->findOneByInvoiceId($id);
-         if (!empty($payToDelete)){
-             $em->remove($payToDelete);
-             $em->flush();
-         }
-         // FIN: Buscamos Pagos asociados a la factura de deposito (se crean de forma automatica, se van a eliminar de forma automatica)
-         $total = $totalInvoiceDep;
-         $invoicedeposititems = array();
-         $invoicedeposititems[] = $invDepositItem;
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         // Buscamos el cliente
-         $reservation = $em->getRepository(Reservation::class)->findOneById($proformaDeposit->getReservationId());
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Buscamos el cliente
-         $allInvoiceDeposit = $em->getRepository(ReservationProformaDeposit::class)->findBy(
-             array(
-                 'reservationId' => $id,
-             )
-         );
-         $totales_iva = $vat;
- //        $totales = ($invoice->getTotalNet() * (-1)) + $totales_iva;
-         $totales = $invoice->getTotalNet() + $totales_iva;
-         // Una factura solo se puede rectificar una vez
- //        $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $invoice->getId()));
-         $boolToRec = false;
-         $invoicedeposititemsTemp = array(
-             'name' => $invoicedeposititems[0]->getDepName(),
-             'amount' => $invoicedeposititems[0]->getDepAmount(),
-             'iva' => $invoicedeposititems[0]->getDepIva(),
-         );
-         $invoicedeposititems = array();
-         $invoicedeposititems[] = $invoicedeposititemsTemp;
-         return $this->redirectToRoute('reservation_view_new_invoice_deposit_rec',array('id' => $invoice->getId()));
-     }
-     /**
-      * @Route("/reservations/newinvoicedeposit/viewinvoicedepositrec/{id}",  name="reservation_view_new_invoice_deposit_rec")
-      */
-     public function detailsViewNewInvoiceDepositRecAction($id, Request $request){
-         // Visualizar Factura de Deposito Rectificativa
-         $em = $this->getDoctrine()->getManager();
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $newProformaDeposit = $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
-         $total = $newProformaDeposit->getTotal();
-         $invoicedeposititems = $em->getRepository(ReservationInvoiceRecItems::class)->findBy(
-             array(
-                 'reservationId' => $newProformaDeposit->getReservationId(),
-                 'invoiceRecId' => $id,
-             )
-         );
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         // Buscamos el cliente
-         $reservation = $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
-         $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-         if (!empty($client)){
-             $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-             $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-             $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-             $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-         } else {
-             $client[0] = new Client();
-             $client[0]->setName('');
-             $client[0]->setTitle('');
-             $client[0]->setIdDocument('');
-             $client[0]->setPopulation('');
-             $client[0]->setRegion('');
-             $client[0]->setCountry('');
-         }
-         // Buscamos el cliente
-         $allInvoiceDeposit = $em->getRepository(ReservationProformaDeposit::class)->findBy(
-             array(
-                 'reservationId' => $newProformaDeposit->getReservationId(),
-             )
-         );
-         $totales_iva = $newProformaDeposit->getVat();
-         $totales = $newProformaDeposit->getTotal();
-         // Una factura solo se puede rectificar una vez
- //        $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('invoiceToRec' => $newProformaDeposit->getId()));
-         $boolToRec = false;
-         $invoicedeposititemsTemp = array(
-             'name' => $invoicedeposititems[0]->getDepName(),
-             'amount' => $invoicedeposititems[0]->getDepAmount(),
-             'iva' => $invoicedeposititems[0]->getDepIva(),
-         );
-         $invoicedeposititems = array();
-         $invoicedeposititems[] = $invoicedeposititemsTemp;
-         $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newProformaDeposit->getReservationId());
-         if(empty($newProformaDeposit->getClientName()) and empty($newProformaDeposit->getClientAddress()) and empty($newProformaDeposit->getClientDocument())){
-             $newProformaDeposit = $this->clientDataToInvoice($newProformaDeposit, 'Client', $reservaEquis->getClient(), $newProformaDeposit->getReservationId());
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
-             array(
-                 'id' => $newProformaDeposit->getReservationId(),
-                 'cid' => '',
-                 'fid' => $newProformaDeposit->getId(),
-                 'invoice' => '',
-                 'numberadmin' => null,
-                 'type' => 'Invoice Deposit Rec',
-                 'number' => $id,
-                 'prefix' => '',
-                 'date' => $newProformaDeposit->getDateAt(),
-                 'token' =>  '',
-                 'company' => $company,
-                 'clients' => $client,
-                 'user' => $user_logueado,
-                 'boolToRec' => $boolToRec,
-                 'invoiceIdToRec' => $newProformaDeposit->getInvoiceToRec(),
-                 'invoicedeposititems' => $invoicedeposititems,
-                 'allProformaDeposit' => $allInvoiceDeposit,
-                 'totales_neto' => $newProformaDeposit->getTotalNet(),
-                 'totales_iva' => $totales_iva,
-                 'totales' => $totales,
-                 'balance' => (-1) * $newProformaDeposit->getBalance(),
-                 'bases_imponibles' => '',
-                 'currency' => '€',
-                 'clientName' => $newProformaDeposit->getClientName(),
-                 'clientAddress' => $newProformaDeposit->getClientAddress(),
-                 'clientDocument' => $newProformaDeposit->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoice/invoicedeposit-proforma/print/{type}/{id}",  name="reservations_invoicedepositproforma_print")
-      */
-     public function detailsInvoiceDepositProformaPrintAction($type, $id, Request $request)
-     {
-         // Pantalla para imprimir Proformas, Facturas y Facturas Rectificativas de Deposito
-         $data = array();
-         $em = $this->getDoctrine()->getManager();
-         // Si el ID de factura viene vacio regresamos a ver facturas
-         if (empty($type)){
-             return $this->redirectToRoute('reservations_viewreservation_invoices',array('id' => $id));
-         }
-         //Acumuladores de datos globales de la factura o proforma
-         $valorTotalNet = 0;
-         $valorVat = 0;
-         if ($type == 'I'){
-             // El tipo es una factura de deposito
-             $data['type'] = 'Invoice Deposit';
-             $data['number'] = $id;
-             $proDepositNet = 0;
-             $proDepositIva = 0;
-             $proDepositTotal = 0;
-             $ivaPorcentaje = 0;
-             $monto = 0;
-             $concepto ='';
-             //INICIO: Buscamos los items de la factura
-             $controlInvDep = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneByNumber($id);
-             $arrayInvoicedItems = $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($controlInvDep->getId());
-             if (!empty($arrayInvoicedItems)) {
-                 foreach ($arrayInvoicedItems as $itemInvoice) {
-                     if (is_numeric($itemInvoice->getAmount()) and is_numeric($itemInvoice->getIva())) {
-                         $proDepositNet = $itemInvoice->getAmount();
-                         $proDepositIva = ($itemInvoice->getAmount()*$itemInvoice->getIva())/100;
-                         $proDepositTotal = $itemInvoice->getAmount() + $proDepositIva;
-                         $ivaPorcentaje = $itemInvoice->getIva();
-                         $monto = $itemInvoice->getAmount();
-                         $concepto = $itemInvoice->getName();
-                         //Acumulamos neto e iva para la factura
-                         $valorTotalNet = $valorTotalNet + $proDepositNet;
-                         $valorVat = $valorVat + round($proDepositTotal,2,PHP_ROUND_HALF_UP);
-                     }
-                 }
-             }
-             $valorTotal = $valorTotalNet + $valorVat;
-             //INICIO: Creamos la factura
-             $newInvoice = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-             //FIN: Creamos la factura
-             $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-             // Buscamos el cliente
-             $reservation = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-             $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-             if (!empty($client)){
-                 $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-                 $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-                 $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-                 $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-             } else {
-                 $client[0] = new Client();
-                 $client[0]->setName('');
-                 $client[0]->setTitle('');
-                 $client[0]->setIdDocument('');
-                 $client[0]->setPopulation('');
-                 $client[0]->setRegion('');
-                 $client[0]->setCountry('');
-             }
-             // Buscamos el cliente
-             $invoiceIdToRec = null;
-             $data['prefix'] = $newInvoice->getPrefix();
-             $data['date'] = $newInvoice->getDateAt();
-             $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-             $data['totales_neto'] = $proDepositNet;
-             $data['totales'] = $proDepositTotal;
-             $data['balance'] = $proDepositTotal;
-             $data['currency'] = '€';
-             $data['datasupplier'] = $newInvoice;
-             $data['bases_imponibles'] = array(
-                 'iva' => $ivaPorcentaje,
-                 'ivaAmount' => ($monto * $ivaPorcentaje)/100
-             );
-             $data['paymentInvoice'] = $newInvoice;
-             $dataTemp = array(
-                 'balance' => $data['datasupplier']->getBalance(),
-                 'dateAt' => $data['datasupplier']->getDateAt(),
-                 'id' => $data['datasupplier']->getId(),
-                 'reservationId' => $data['datasupplier']->getReservationId(),
-                 'total' => $data['datasupplier']->getTotal(),
-                 'amount' => $data['datasupplier']->getTotalNet(),
-                 'type' => $data['datasupplier']->getType(),
-                 'vat' => $data['datasupplier']->getVat(),
-                 'name' => $concepto
-             );
-             $data['datasupplier'] = $dataTemp;
-             //Es una proforma
-             $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-             $invoiceIdToRec = null;
-             $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-             if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-                 $newInvoice = $this->clientDataToInvoice($newInvoice, 'Client', $reservaEquis->getClient(), $newInvoice->getReservationId());
-             }
-         } else {
-             if ($type == 'R'){
-                 //El tipo es una factura rectificativa
-                 //INICIO: Creamos los items de la factura rectficativa
-                 $arrayInvoicedItems = $em->getRepository(ReservationInvoiceRecItems::class)->findByInvoiceRecId($id);
-                 $vatItem = 0;
-                 $concepto ='';
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if ($itemInvoice->getItemType() == 'DEPOSIT') {
-                             //Acumulamos neto e iva para la factura rectificativa
-                             $valorTotalNet = $valorTotalNet + $itemInvoice->getDepAmount();
-                             $valorVat = $valorVat + round((($itemInvoice->getDepAmount() * $itemInvoice->getDepIva())/100),2,PHP_ROUND_HALF_UP);
-                             $vatItem = $itemInvoice->getDepIva();
-                             $concepto = $itemInvoice->getDepName();
-                         }
-                     }
-                 }
-                 $valorTotal = $valorTotalNet + $valorVat;
-                 //INICIO: Creamos la factura rectificativa
-                 $newInvoice = $em->getRepository(ReservationInvoiceRec::class)->findOneById($id);
-                 //FIN: Creamos la factura rectificativa
-                 $paymentsClient = new ReservationPaymentsClient();
-                 $paymentsClient->setReservationId($id);
-                 $reservaInv = new ReservationInvoice();
-                 $reservaInv->setReservationId($id);
-                 $idLounges = array();
-                 $loungesBoolToInvoice = array();
-                 $idPayments = array();
-                 $paymentsBoolToInvoice = array();
-                 $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-                 //Es una proforma
-                 $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-                 // Buscamos el cliente
-                 $reservation = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-                 $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-                 if (!empty($client)){
-                     $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-                     $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-                     $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-                     $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-                 } else {
-                     $client[0] = new Client();
-                     $client[0]->setName('');
-                     $client[0]->setTitle('');
-                     $client[0]->setIdDocument('');
-                     $client[0]->setPopulation('');
-                     $client[0]->setRegion('');
-                     $client[0]->setCountry('');
-                 }
-                 // Buscamos el cliente
-                 $invoiceIdToRec = $newInvoice->getInvoiceToRec();
-                 $data['number'] = $id;
-                 $data['balance'] = $newInvoice->getBalance();
-                 $data['type'] = 'Invoice Deposit Rec';
-                 $data['prefix'] = 'R';
-                 $data['date'] = $newInvoice->getDateAt();
-                 $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-                 $data['totales_neto'] = $newInvoice->getTotalNet();
-                 $data['totales'] = $newInvoice->getTotal();
-                 $data['balance'] = $newInvoice->getBalance();
-                 $data['currency'] = '€';
-                 $data['datasupplier'] = $newInvoice;
-                 $data['bases_imponibles'] = array(
-                     'iva' => $vatItem,
-                     'ivaAmount' => $newInvoice->getVat()
-                 );
-                 $data['paymentInvoice'] = $newInvoice;
-                 $dataTemp = array(
-                     'balance' => $data['datasupplier']->getBalance(),
-                     'dateAt' => $data['datasupplier']->getDateAt(),
-                     'id' => $data['datasupplier']->getId(),
-                     'reservationId' => $data['datasupplier']->getReservationId(),
-                     'total' => $data['datasupplier']->getTotal(),
-                     'amount' => $data['datasupplier']->getTotalNet(),
-                     'type' => $data['datasupplier']->getType(),
-                     'vat' => $data['datasupplier']->getVat(),
-                     'name' => $concepto
-                 );
-                 $data['datasupplier'] = $dataTemp;
-                 //Es una proforma
-                 $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-                 $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-                 if(empty($newInvoice->getClientName()) and empty($newInvoice->getClientAddress()) and empty($newInvoice->getClientDocument())){
-                     $newInvoice = $this->clientDataToInvoice($newInvoice, 'Client', $reservaEquis->getClient(), $newInvoice->getReservationId());
-                 }
-             } else {
-                 // El tipo es una proforma de deposito
-                 $data['type'] = 'Proforma Deposit';
-                 $data['number'] = $id;
-                 $proDepositNet = 0;
-                 $proDepositIva = 0;
-                 $proDepositTotal = 0;
-                 //INICIO: Creamos los items de la proforma
-                 $arrayInvoicedItems = $em->getRepository(ReservationProformaDeposit::class)->findById($id);
-                 if (!empty($arrayInvoicedItems)) {
-                     foreach ($arrayInvoicedItems as $itemInvoice) {
-                         if (is_numeric($itemInvoice->getAmount()) and is_numeric($itemInvoice->getIva())) {
-                             $proDepositNet = $itemInvoice->getAmount();
-                             $proDepositIva = ($itemInvoice->getAmount()*$itemInvoice->getIva())/100;
-                             $proDepositTotal = $itemInvoice->getAmount() + (($itemInvoice->getAmount()*$itemInvoice->getIva())/100);
-                             //Acumulamos neto e iva para la factura
-                             $valorTotalNet = $valorTotalNet + $proDepositNet;
-                             $valorVat = $valorVat + round($proDepositTotal,2,PHP_ROUND_HALF_UP);
-                         }
-                     }
-                 }
-                 $valorTotal = $valorTotalNet + $valorVat;
-                 //INICIO: Creamos la factura
-                 $newInvoice = $em->getRepository(ReservationProformaDeposit::class)->findOneById($id);
-                 //FIN: Creamos la factura
-                 $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-                 // Buscamos el cliente
-                 $reservation = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-                 $client = $em->getRepository(Client::class)->findById($reservation->getClient());
-                 if (!empty($client)){
-                     $city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
-                     $region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
-                     $country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
-                     $client['city'] = $city; $client['region'] = $region; $client['country'] = $country;
-                 } else {
-                     $client[0] = new Client();
-                     $client[0]->setName('');
-                     $client[0]->setTitle('');
-                     $client[0]->setIdDocument('');
-                     $client[0]->setPopulation('');
-                     $client[0]->setRegion('');
-                     $client[0]->setCountry('');
-                 }
-                 // Buscamos el cliente
-                 $invoiceIdToRec = null;
-                 $data['prefix'] = $newInvoice->getPrefix();
-                 $data['date'] = $newInvoice->getDateAt();
-                 $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-                 $data['totales_neto'] = $proDepositNet;
-                 $data['totales'] = $proDepositTotal;
-                 $data['balance'] = $proDepositTotal;
-                 $data['currency'] = '€';
-                 $data['datasupplier'] = $newInvoice;
-                 $data['bases_imponibles'] = array(
-                     'iva' => $newInvoice->getIva(),
-                     'ivaAmount' => ($newInvoice->getAmount() * $newInvoice->getIva())/100
-                 );
-                 $data['paymentInvoice'] = $newInvoice;
-                 $reservaEquis = $em->getRepository(Reservation::class)->findOneById($newInvoice->getReservationId());
-                 if(true){ $newInvoice = $this->clientDataToInvoice(null, 'Client', $reservaEquis->getClient(), $reservaEquis->getId()); }
-             }
-         }
-         if (!empty($data['bases_imponibles']['iva'])){$bases_imponibles = $data['bases_imponibles']['iva'];} else {$bases_imponibles = '';}
-         return $this->render('MDS/GreenPatioBundle/reservations/services-proforma-deposit-print-reservation.html.twig',
-             array(
-                 'id' => $id,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'invoiceIdToRec' => $invoiceIdToRec,
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => null,
-                 'company' => $data['company'],
-                 'clients' => $client,
-                 'datasupplier' => $data['datasupplier'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'currency' => $data['currency'],
-                 'iva' => $bases_imponibles,
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'clientName' => $newInvoice->getClientName(),
-                 'clientAddress' => $newInvoice->getClientAddress(),
-                 'clientDocument' => $newInvoice->getClientDocument(),
-             )
-         );
-     }
-     /**
-      * @Route("/instantUpdateInvoice", name="instant_update_invoice")
-      */
-     public function instantUpdateInvoiceAction(Request $request) {
-         $codProfile = $_POST['idprofile'];
- //        $codProfile = "1";
- //        $codProfile = $request->request->get('idProfile');
- //        $codProfile = $idProfile;
-         $em = $this->getDoctrine()->getManager();
-         $salasPorPerfil = $em->getRepository(ReservationLoungeProfile::class)->findBy(
-             array(
-                 'periodId' => $codProfile
-             )
-         );
-         $datos = array();
-         if (!empty($salasPorPerfil)){
-             foreach($salasPorPerfil as $sala){
-                 $datos[] = array(
-                     "id" => $sala->getId(),
-                     "idlounge" => $sala->getLoungeId(),
-                     "nameDescription" => $sala->getDescription(),
-                     "price" => $sala->getPrice(),
-                 );
-             }
-         }
-         $return = array(
-             'salasPerfil' => $datos,
-             'id' => $codProfile,
-         );
-         $response = new JsonResponse($return);
-         return $response;
-     }
-     /**
-      * @Route("/invoicerec/{id}",  name="reservations_invoice_rec")
-      */
-     public function generateReservationInvoiceRecAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $invoice = $em->getRepository(ReservationInvoice::class)->findOneById($id);
-         if (true){
-             // Verificamos que no exista una factura rectificativa previa sobre la misma factura
-             $previusInvoiceRec = $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($id);
-             if (!empty($previusInvoiceRec)){ return $this->redirectToRoute('reservations_viewrec_invoice', array('id' => $previusInvoiceRec->getId())); }
-         }
-         $now = new DateTime();
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $invoiceRec = new ReservationInvoiceRec();
-         $invoiceRec->setInvoiceToRec($id);
-         $invoiceRec->setCreatedAt($now);
-         $invoiceRec->setUpdatedAt($now);
-         $invoiceRec->setCreatedId($user_id);
-         $invoiceRec->setUpdatedId($user_id);
-         $invoiceRec->setDateAt($now);
-         $invoiceRec->setMaster($invoice->getMaster());
-         $invoiceRec->setNumber('REC-'.$invoice->getNumber());
-         $invoiceRec->setPrefix('R');
-         $invoiceRec->setReservationId($invoice->getReservationId());
-         $invoiceRec->setTotal($invoice->getTotal()*(-1));
-         $invoiceRec->setTotalNet($invoice->getTotalNet()*(-1));
-         $invoiceRec->setType('Invoice Rec');
-         $invoiceRec->setVat($invoice->getVat()*(-1));
-         $invoiceRec->setBalance($invoice->getBalance()*(-1));
-         $invoiceRec->setClientName($invoice->getClientName());
-         $invoiceRec->setClientAddress($invoice->getClientAddress());
-         $invoiceRec->setClientDocument($invoice->getClientDocument());
-         $invoiceRec->setClientType($invoice->getClientType());
-         $em->persist($invoiceRec);
-         $em->flush();
-         $invoiceItems = $em->getRepository(ReservationInvoiceItems::class)->findByInvoiceId($id);
-         // Cada elemento se duplica en ItemsRec y se libera asignando ID = 0
-         foreach ($invoiceItems as $item){
-             $itemRec = new ReservationInvoiceRecItems();
-             $itemRec->setReservationId($item->getReservationId());
-             $itemRec->setInvoiceId($item->getInvoiceId());
-             $itemRec->setItemType($item->getItemType());
-             $itemRec->setInvoiceRecId($invoiceRec->getId());                    //   VERIFICAR ESTE INDICE   *-+*-+*-+*-+*-+
-             $itemRec->setLngControlId($item->getLngControlId());
-             $itemRec->setLngLoungeName($item->getLngLoungeName());
-             $itemRec->setLngIdLounge($item->getLngIdLounge());
-             $itemRec->setLngIdLounge($item->getLngIdLounge());
-             $itemRec->setLngDateStart($item->getLngDateStart());
-             $itemRec->setLngDateEnd($item->getLngDateEnd());
-             $itemRec->setLngServicePrice($item->getLngServicePrice()*(-1));
-             $itemRec->setLngPax($item->getLngPax());
-             $itemRec->setLngType($item->getLngType());
-             $itemRec->setLngHourStart($item->getLngHourStart());
-             $itemRec->setLngMinStart($item->getLngMinStart());
-             $itemRec->setLngHourEnd($item->getLngHourEnd());
-             $itemRec->setLngMinEnd($item->getLngMinEnd());
-             $itemRec->setLngIva($item->getLngIva());
-             $itemRec->setLngOpIva($item->getLngOpIva());
-             $itemRec->setSrvControlId($item->getSrvControlId());
-             $itemRec->setSrvSupplierId($item->getSrvSupplierId());
-             $itemRec->setSrvServiceId($item->getSrvServiceId());
-             $itemRec->setSrvServiceCatId($item->getSrvServiceCatId());
-             $itemRec->setSrvServiceCatName($item->getSrvServiceCatName());
-             $itemRec->setSrvPrice($item->getSrvPrice()*(-1));
-             $itemRec->setSrvCurrency($item->getSrvCurrency());
-             $itemRec->setSrvUnits($item->getSrvUnits());
-             $itemRec->setSrvOpCommission($item->getSrvOpCommission());
-             $itemRec->setSrvCommission($item->getSrvCommission());
-             $itemRec->setSrvOpOver($item->getSrvOpOver());
-             $itemRec->setSrvOver($item->getSrvOver()*(-1));
-             $itemRec->setSrvOpIva($item->getSrvOpIva());
-             $itemRec->setSrvIva($item->getSrvIva());
-             $itemRec->setSrvPax($item->getSrvPax());
-             $itemRec->setSrvHour($item->getSrvHour());
-             $itemRec->setSrvDateInAt($item->getSrvDateInAt());
-             $itemRec->setSrvDateOutAt($item->getSrvDateOutAt());
-             $itemRec->setSrvContcolor($item->getSrvContcolor());
-             $itemRec->setSrvRank($item->getSrvRank());
-             $itemRec->setSrvAssistantId($item->getSrvAssistantId());
-             $itemRec->setSrvActivityId($item->getSrvActivityId());
-             $itemRec->setSrvPay($item->getSrvPay());
-             $itemRec->setSrvName($item->getSrvName());
-             $itemRec->setPayControlId($item->getPayControlId());
- //            $itemRec->setPayAmount($item->getPayAmount()*(-1));
-             $itemRec->setPayAmount($item->getPayAmount());          // Los pagos han pasado a ser las facturas de deposito, en la tabla su amount se encuentra en positivo, en la rectificativa, este valor lo necesitamos en positivo
-             $itemRec->setPayDatePayAt($item->getPayDatePayAt());
-             $itemRec->setPayWayToPay($item->getPayWayToPay());
- //            $itemRec->setPayAmountTotal($item->getPayAmountTotal()*(-1));
-             $itemRec->setPayAmountTotal($item->getPayAmountTotal());    // Los pagos han pasado a ser las facturas de deposito, en la tabla su amount se encuentra en positivo, en la rectificativa, este valor lo necesitamos en positivo
-             $itemRec->setPayVat($item->getPayVat());
-             $itemRec->setCreatedId($user_id);
-             $itemRec->setCreatedAt(new DateTime('now'));
-             $itemRec->setUpdatedId($user_id);
-             $itemRec->setUpdatedAt(new DateTime('now'));
-             $em->persist($itemRec);
-             $em->flush();
-             // Se libera asignando ID = 0
-             $item->setLngControlId(0);
-             $item->setSrvControlId(0);
-             $item->setPayControlId(0);
-             $em->persist($item);
-             $em->flush();
-         }
-         $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($invoice->getReservationId());
-         $allInvoicesRec = $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($invoice->getReservationId());
-         foreach ($allInvoicesRec as $item){ array_push($allInvoices, $item); }
-         $reservation = $em->getRepository(Reservation::class)->findOneById($invoice->getReservationId());
-         $client = $em->getRepository(Client::class)->findOneById($reservation->getClient());
-         $data = array();
-         $data['clients'][0] = $client;
-         $data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $data['datasupplier'] = '';
-         $data['totales_neto'] = '';
-         $data['totales'] = '';
-         $data['bases_imponibles'] = '';
-         $data['balance'] = '';
-         $data['paymentInvoice'] = '';
-         $data['currency'] = '';
-         // Una factura solo se puede rectificar una vez
-         $rectf = $em->getRepository(ReservationInvoiceRec::class)->findBy( array('number' => 'REC-'.$invoice->getNumber()));
-         $boolToRec = empty($rectf);
-         return $this->redirectToRoute('reservations_viewrec_invoice', array('id' => $invoiceRec->getId()));
-     }
-     /**
-      * @Route("/reservations/invoicedeposit/proforma/{id}",  name="reservation_invoice_deposit_proforma")
-      */
-     public function detailsProformaAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $invoicedepositcontrol = $em->getRepository(ReservationInvoiceDepositControl::class)->findByReservationId($id);
-         $invoicedeposit = new ReservationInvoiceDepositItems();
-         $invoicedeposit->setReservationId($id);
-         $form = $this->createReservationInvoiceDepositItemsForm($invoicedeposit);
-         $controlId = null;
-         $type = "Proforma";
-         $prefix = "PFD-";
-         $date = new \DateTime('now');
-         $data = $this->baseInvoiceDepositReservation($id, $controlId, $type, $id, $prefix, $date, $request);
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-proforma.html.twig',
-             array(
-                 'id' => $id,
-                 'cid' => $data['cid'],
-                 'numberadmin' => null,
-                 'type' => $data['type'],
-                 'invoice' => $invoicedepositcontrol,
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' =>  $data['token'],
-                 'reservation' => $data['reservation'],
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'invoicedeposititems' => $data['invoicedeposititems'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => $data['totales_iva'],
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['ivas'],
-                 'currency' => $data['currency'],
-                 'form' => $form->createView(),
- //                'mcp' => $proposal->getMcp(),
-             )
-         );
-     }
-     private function createReservationInvoiceDepositItemsForm(ReservationInvoiceDepositItems $entity)
-     {
-         $form = $this->createForm(ReservationInvoiceDepositItemsType::class, $entity, array(
-             'action' => $this->generateUrl('reservation_invoice_Deposit_proforma_add'),
-             'method' => 'POST'
-         ));
-         return $form;
-     }
-     private function baseInvoiceDepositReservation($id, $controlId, $type, $number, $prefix, $date, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $company = $em->getRepository(SettingsCompany::class)->findOneByPriority('2');
-         $parameters = array(
-             'id' => $reservation->getClient(),
-         );
-         $dql = 'SELECT cl,  c.country, re.region, p.name, r.city
-                 FROM App:Client cl
-                 INNER JOIN App:Country c WITH c.id = cl.country
-                 INNER JOIN App:Regions re WITH re.id = cl.region
-                 INNER JOIN App:Provinces p WITH p.id = cl.province
-                 INNER JOIN App:Cities r WITH r.id = cl.population
-                 WHERE cl.id = :id';
-         $query = $em->createQuery($dql)->setParameters($parameters);
-         $client = $query->getResult();
-         if (!is_null($controlId)){
-             $invoicecontrol = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneById($controlId);
-             if (!is_null($invoicecontrol->getNumber())){
-                 $numberadmin = $invoicecontrol->getNumber();
-             }else{
-                 $numberadmin = null;
-             }
-         }else{
-             $numberadmin = null;
-         }
-         $invoicedeposititems = $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
-             array(
-                 'reservationId' => $id,
-                 'controlId' => $controlId,
-             )
-         );
-         $totales_neto_all = "0";
-         $totales_iva_all = "0";
-         $totales_con_iva_all = "0";
-         $data_iva = array();
-         $data_deposititems = array();
-         foreach($invoicedeposititems as $deposititems){
-             $amount = $deposititems->getAmount();
-             $iva_base = $deposititems->getIva();
-             $iva = $iva_base / 100;
-             if($iva_base !='0'){
-                 $amount_iva = $amount * $iva;
-             }else{
-                 $amount_iva = "0";
-             }
-             $amount_con_iva = $amount + $amount_iva;
-             $totales_neto_all += $amount;
-             $totales_iva_all += $amount_iva;
-             $totales_con_iva_all += $amount_con_iva;
-             if (empty($totales_ivas_all[$iva_base])){
-                 $totales_ivas_all[$iva_base]= 0;
-             }
-             $totales_ivas_all[$iva_base] += $amount_iva;
-             $data_iva[$iva_base] = array(
-                 'iva' => $iva_base,
-                 'ivas' => $totales_ivas_all[$iva_base],
-             );
-             $data_deposititems[] = array(
-                 'id' => $deposititems->getId(),
-                 'name' => $deposititems->getName(),
-                 'amount' => $amount,
-                 'iva' => $iva_base,
-                 'total' => $amount_con_iva
-             );
-         }
-         $currency ="€";
-         $data = array(
-             'id' => $id,
-             'cid' => $controlId,
-             'type' => $type,
-             'number' => $number,
-             'prefix' => $prefix,
-             'numberadmin' => $numberadmin,
-             'date' => $date,
-             'token' => $reservation->getAccessKey(),
-             'reservation' => $reservation,
-             'company' => $company,
-             'clients' => $client,
-             'invoicedeposititems' => $data_deposititems,
-             'totales_neto' => $totales_neto_all,
-             'totales_iva' => $totales_iva_all,
-             'totales' => $totales_con_iva_all,
-             'ivas' => $data_iva,
-             'currency' => $currency,
-         );
-         return $data;
-     }
-     /**
-      * @Route("/reservations/invoicedeposit/add", name="reservation_invoice_Deposit_proforma_add")
-      */
-     public function createDepositAction(Request $request)
-     {
-         $invoicedeposit = new ReservationInvoiceDepositItems();
-         $form = $this->createReservationInvoiceDepositItemsForm($invoicedeposit);
-         $form->handleRequest($request);
-         if($form->isValid())
-         {
-             $em = $this->getDoctrine()->getManager();
-             /* Obtengo usuario logueado */
-             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-             $user_id = $user_logueado->getId();
-             $invoicedeposit->setCreatedId($user_id);
-             $invoicedeposit->setUpdatedId($user_id);
-             /* Gestión de eventos en Log */
-             $user_lastname = $user_logueado->getLastname();
-             $user_name = $user_logueado->getName();
-             $user_email = $user_logueado->getEmail();
-             $user_rol = $user_logueado->getRoles();
-             $event_url = $request->getPathInfo();
-             $event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
-             $em->persist($invoicedeposit);
-             $em->flush();
-             $event = 'the Items was registered';
-             $successMessage = $this->translator->trans($event);
-             $this->addFlash('mensajeinvoicedepositservices', $successMessage);
-             return $this->redirectToRoute('reservation_invoice_deposit_proforma',
-                 array(
-                     'id' => $invoicedeposit->getReservationId()
-                 ));
-         } else {
-             $errorMessage = $this->translator->trans('Error, some fields are empty');
-             $this->addFlash('mensajeinvoicedepositserviceserror', $errorMessage);
-         }
-         return $this->redirectToRoute('reservation_invoice_deposit_proforma', array('id' => $invoicedeposit->getReservationId()));
-     }
-     /**
-      * @Route("/reservations/invoicedeposit/invoice/{id}/{fid}", defaults={"fid" = ""}, name="reservation_invoice_deposit")
-      */
-     public function detailsInvoiceDepositAction($id, $fid, Request $request)
-     {
-         $data = array();
-         $em = $this->getDoctrine()->getManager();
-         $reservation = $em->getRepository(Reservation::class)->findOneById($id);
-         $invoicecontrol = $em->getRepository(ReservationInvoiceDepositControl::class)->findByReservationId($id);
- //        $number = $invoicecontrol->getNumber();
-         $prefix = "IFD-";
-         if (empty($fid)){
-             $invoicedeposititems = $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
-                 array(
-                     'reservationId' => $id,
-                     'controlId' => null,
-                 )
-             );
-             if (!empty($invoicedeposititems)){
-                 /* Obtengo usuario logueado */
-                 $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-                 $user_id = $user_logueado->getId();
-                 $invoicedeposit = new ReservationInvoice();
-                 $invoicedeposit->setDateAt(new \DateTime());
-                 $invoicedeposit->setMaster('0');
-                 $invoicedeposit->setNumber('0');
-                 $invoicedeposit->setType('Invoice Deposit');
-                 $invoicedeposit->setReservationId($id);
-                 $invoicedeposit->setPrefix('');
-                 $invoicedeposit->setTotal('0');
-                 $invoicedeposit->setTotalNet('0');
-                 $invoicedeposit->setVat('0');
-                 $invoicedeposit->setCreatedId($user_id);
-                 $invoicedeposit->setUpdatedId($user_id);
-                 $invoicedeposit->setCreatedAt(new \DateTime());
-                 $invoicedeposit->setUpdatedAt(new \DateTime());
-                 $em->persist($invoicedeposit);
-                 $em->flush();
-                 $number = $invoicedeposit->getId();
-                 $invoicedepositcontrol = new ReservationInvoiceDepositControl();
-                 $invoicedepositcontrol->setReservationId($id);
-                 $invoicedepositcontrol->setNumber($invoicedeposit->getId());
-                 $invoicedepositcontrol->setDateAt(new \DateTime("now"));
-                 $invoicedepositcontrol->setPrefix($prefix);
-                 $invoicedepositcontrol->setCreatedId($user_id);
-                 $invoicedepositcontrol->setUpdatedId($user_id);
-                 $em->persist($invoicedepositcontrol);
-                 $em->flush();
-                 $invoiceSQL = $em->getRepository(ReservationInvoice::class)->findOneById($invoicedeposit->getId());
-                 $invoiceSQL->setMaster($invoicedepositcontrol->getId());
-                 $invoiceSQL->setNumber($invoicedepositcontrol->getId());
-                 $em->persist($invoiceSQL);
-                 $em->flush();
-                 $controlId = $invoicedepositcontrol->getId();
-                 $date = $invoicedepositcontrol->getDateAt();
-                 foreach($invoicedeposititems as $invoicedeposit){
-                     $invoicedeposit->setControlId($controlId);
-                     $em->persist($invoicedeposit);
-                 }
-                 $em->flush();
-                 return $this->redirectToRoute('reservation_invoice_deposit',
-                     array(
-                         'id' => $id,
-                         'fid' => $invoicedepositcontrol->getId(),
-                     )
-                 );
-             }else{
-                 return $this->redirectToRoute('reservation_invoice_deposit_proforma',
-                     array(
-                         'id' => $id
-                     )
-                 );
-             }
-         }else{
-             $invoicedepositcontrolconsulta = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneBy(
-                 array(
-                     'reservationId' => $id,
-                     'id' => $fid
-                 )
-             );
-             $controlId = $invoicedepositcontrolconsulta->getId();
-             $date = $invoicedepositcontrolconsulta->getDateAt();
-         }
-         $number = $id;
-         $type = "Invoice";
-         $data = $this->baseInvoiceDepositReservation($id, $controlId, $type, $number, $prefix, $date, $request);
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         if ($reservation->getStatus() != 'Invoiced'){
-             $reservation->setStatus('Confirmed');
-             $em->persist($reservation);
-             $em->flush();
-         }
-         // Una factura solo se puede rectificar una vez
-         $rectf = $em->getRepository(ReservationInvoiceRec::class)->findByInvoiceToRec($number);
-         $boolToRec = empty($rectf);
-         $newclient[] = $data['clients'];
-         return $this->render('MDS/GreenPatioBundle/reservations/invoice-deposit-invoice.html.twig',
-             array(
-                 'id' => $id,
-                 'cid' => $data['cid'],
-                 'fid' => $controlId,
-                 'invoice' => $invoicecontrol,
-                 'numberadmin' => $data['numberadmin'],
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' =>  $data['token'],
-                 'reservation' => $data['reservation'],
-                 'company' => $data['company'],
-                 'clients' => $newclient,
-                 'user' => $user_logueado,
-                 'boolToRec' => $boolToRec,
-                 'invoicedeposititems' => $data['invoicedeposititems'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => $data['totales_iva'],
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['ivas'],
-                 'currency' => $data['currency'],
- //                'mcp' => $proposal->getMcp(),
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoicedeposit/number/updated/{cid}/{id}", name="reservation_invoicedeposit_number_update")
-      */
-     public function InvoiceEmptyNumberInvoiceDepositUpdateAction($cid, $id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $invoice = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneById($id);
-         $numberinvoice = $request->request->get('invoice')['number'];
-         if(!empty($numberinvoice) and !is_null($invoice))
-         {
-             $invoice->setNumber($numberinvoice);
-             /* Obtengo usuario logueado */
-             $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-             $user_id = $user_logueado->getId();
-             $invoice->setUpdatedId($user_id);
-             $em->persist($invoice);
-             $em->flush();
-             $event = 'The Invoice Deposit has been Updated.';
-             $successMessage = $this->translator->trans($event);
-             $this->addFlash('mensajeinvoicedepositservices', $successMessage);
-         }else{
-             $errorMessage = $this->translator->trans('Error, some fields are empty');
-             $this->addFlash('mensajeinvoicedepositserviceserror', $errorMessage);
-         }
-         return $this->redirectToRoute('reservation_invoice_deposit',
-             array(
-                 'id' => $cid,
-                 'fid' => $id,
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoicedepositdelete/invoice/{id}/{fid}", defaults={"fid" = ""}, name="reservation_invoice_deposit_delete")
-      */
-     public function deleteInvoiceDepositAction($id, $fid, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         // INICIO: Buscamos en ITEMS los elementos que coincidan
-         $invoicedeposititems = $em->getRepository(ReservationInvoiceDepositItems::class)->findBy(
-             array(
-                 'reservationId' => $id,
-                 'controlId' => $fid
-             )
-         );
-         foreach ($invoicedeposititems as $item){
-             $em->remove($item);
-             $em->flush();
-         }
-         // FIN: Buscamos en ITEMS los elementos que coincidan
-         // INICIO: Buscamos en CONTROL los elementos que coincidan
-         $invoicedepositcontrol = $em->getRepository(ReservationInvoiceDepositControl::class)->findBy(
-             array(
-                 'reservationId' => $id,
-                 'id' => $fid
-             )
-         );
-         foreach ($invoicedepositcontrol as $item){
-             $numberDeposit = $item->getNumber();
-             $em->remove($item);
-             $em->flush();
-         }
-         // FIN: Buscamos en CONTROL los elementos que coincidan
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $now = new DateTime('now');
-         $tracingDeleteDeposit = new ReservationTracing();
-         $tracingDeleteDeposit->setDateAt($now);
-         $tracingDeleteDeposit->setCreatedAt($now);
-         $tracingDeleteDeposit->setUpdatedAt($now);
-         $tracingDeleteDeposit->setText('Ha eliminado la Factura de deposito No. '.$numberDeposit);
-         $tracingDeleteDeposit->setAgentId($user_id);
-         $tracingDeleteDeposit->setReservationId($id);
-         $tracingDeleteDeposit->setViewed('no');
-         $tracingDeleteDeposit->setCreatedId($user_id);
-         $tracingDeleteDeposit->setUpdatedId($user_id);
-         try{
-             $em->persist($tracingDeleteDeposit);
-             $em->flush();
-             $event = 'The item has been deleted.';
-             $successMessage = $this->translator->trans($event);
-             $this->addFlash('mensajereservation', $successMessage);
-         } catch (\Exception $e){
-             $event = 'An error occurred: '.$e->getMessage();
-             $errorMessage = $this->translator->trans($event);
-             $this->addFlash('mensajereservationerror', $errorMessage);
-         }
-         return $this->redirectToRoute('reservation_invoice_deposit_proforma',
-             array('id' => $id));
-     }
-     /**
-      * @Route("/reservations/invoicedeposit/print/invoice/{id}/{fid}",  name="reservation_invoice_deposit_invoice_print_externo")
-      */
-     public function printdetailsInvoicedepositAction($id, $fid, Request $request)
-     {
-         $data = array();
-         $em = $this->getDoctrine()->getManager();
-         $invoicedepositcontrolconsulta = $em->getRepository(ReservationInvoiceDepositControl::class)->findOneBy(
-             array(
-                 'reservationId' => $id,
-                 'id' => $fid
-             )
-         );
-         $type = "Invoice";
-         $controlId = $invoicedepositcontrolconsulta->getId();
-         $date = $invoicedepositcontrolconsulta->getDateAt();
-         $prefix = $invoicedepositcontrolconsulta->getPrefix();
-         $data = $this->baseInvoiceDepositReservation($id, $controlId, $type, $id, $prefix, $date, $request);
-         return $this->render('MDS/GreenPatioBundle/reservations/print-invoice-deposit-proforma.html.twig',
-             array(
-                 'id' => $id,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'numberadmin' => $data['numberadmin'],
-                 'date' => $data['date'],
-                 'token' =>  $data['token'],
-                 'reservation' => $data['reservation'],
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'invoicedeposititems' => $data['invoicedeposititems'],
-                 'totales_neto' => $data['totales_neto'],
-                 'totales_iva' => $data['totales_iva'],
-                 'totales' => $data['totales'],
-                 'bases_imponibles' => $data['ivas'],
-                 'currency' => $data['currency'],
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/invoicedeposit/deleted/items/{id}", name="reservation_invoice_deposit_invoice_deleted_items")
-      *
-      */
-     public function deleteItemsInvoiceDepositAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $delete = $em->getRepository(ReservationInvoiceDepositItems::class)->findOneById($id);
-         $em->remove($delete);
-         $em->flush();
-         $event = 'The item in the deposit proforma has been removed';
-         $successMessage = $this->translator->trans($event);
-         $this->addFlash('mensajeinvoicedepositservices', $successMessage);
-         return $this->redirectToRoute('reservation_invoice_deposit_proforma', array( 'id' => $delete->getReservationId(), ));
-     }
-     /**
-      * @Route("/reservations/invoice/list", name="reservation_invoice_list")
-      */
-     public function indexAction(Request $request) {
-         $em = $this->getDoctrine()->getManager();
-         $todayTwoYearAgo = new DateTime('now -2 year');
-         $parameters = array( 'dateStart' => $todayTwoYearAgo, );
-         $dql = 'SELECT p
-                 FROM GreenPatioBundle:ReservationInvoice p
-                 WHERE p.dateAt > :dateStart';
-         $query = $em->createQuery($dql)->setParameters($parameters);
-         $invoiced = $em->getRepository(ReservationInvoice::class)->findAll();
-         $invoiced = $query->getResult();
-         $parameters = array( 'dateStart' => $todayTwoYearAgo, );
-         $dql = 'SELECT p
-                 FROM GreenPatioBundle:ReservationInvoiceRec p
-                 WHERE p.dateAt > :dateStart';
-         $query = $em->createQuery($dql)->setParameters($parameters);
-         $invoicedRec = $em->getRepository(ReservationInvoiceRec::class)->findAll();
-         $invoicedRec = $query->getResult();
-         // Agregamos las rectificativas al arreglo de facturas con el indice "R(id)"
-         foreach ($invoicedRec as $idRecArray => $item){
-             $invoiced['R'.$item->getId()] = $item;
-         }
-         $sumatoriaTotalNet = 0;
-         $sumatoriaTotalVat = 0;
-         $sumatoriaTotal = 0;
-         foreach ($invoiced as $idArray => $item){
-             $reserva = $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
-             $invoiced[$idArray]->setNumber($reserva->getTitle());
-             $client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
-             if(!empty($client)){
-                 $invoiced[$idArray]->setPrefix($client->getName());
-             } else {
-                 $invoiced[$idArray]->setPrefix('');
-             }
-             $estaEnFactura = false;
-             $estaEnFacturaRectificativa = false;
-             if ($item->getType() == 'Invoice Deposit'){
-                 // Si la factura de deposito se encuentra en una factura sumara 0
-                 // INICIO: Verificamos factura de deposito dentro de alguna factura
-                 $payOfInvoiceDeposit = $em->getRepository(ReservationPaymentsClient::class)->findOneByInvoiceId($item->getId());
-                 if (!empty($payOfInvoiceDeposit)){
-                     // Verificamos si el deposito esta dentro de una factura
-                     $itemInvoiceOfInvoiceDeposit = $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($payOfInvoiceDeposit->getId());
-                 }
-                 if (!empty($itemInvoiceOfInvoiceDeposit)){
-                     $estaEnFactura = true;
-                 } else {
-                     // Verificamos que el control Id no haya sido seteado a 0 por rectificar la factura
-                     if (!empty($payOfInvoiceDeposit)) {
-                         $itemInvoiceOfInvoiceDeposit = $em->getRepository(ReservationInvoiceRecItems::class)->findOneByPayControlId($payOfInvoiceDeposit->getId());
-                         if (!empty($itemInvoiceOfInvoiceDeposit)) {
-                             $estaEnFactura = true;
-                         }
-                     }
-                 }
-                 if (!empty($payOfInvoiceDeposit)){
-                     // Verificamos si el deposito esta dentro de una factura rectificativa
-                     $itemInvoiceOfInvoiceDepositRec = $em->getRepository(ReservationInvoiceRecItems::class)->findOneByPayControlId($payOfInvoiceDeposit->getId());
-                 }
-                 if (!empty($itemInvoiceOfInvoiceDepositRec)){
-                     $estaEnFacturaRectificativa = true;
-                 }
-                 // FIN: Verificamos factura de deposito dentro de alguna factura
-                 $invoicedDepositItems = $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($item->getMaster());
-                 foreach ($invoicedDepositItems as $itemDep){
-                         $invoiced[$idArray]->setTotalNet($invoiced[$idArray]->getTotalNet() + $itemDep->getAmount());
-                         $invoiced[$idArray]->setVat($invoiced[$idArray]->getVat() + (($itemDep->getAmount() * $itemDep->getIva())/100));
-                         $invoiced[$idArray]->setTotal($invoiced[$idArray]->getTotal() + ($itemDep->getAmount() + (($itemDep->getAmount() * $itemDep->getIva())/100)));
-                 }
-             }
-             // Sumara cuando ambos esten en false (no esta en factura ni en fact rect) o en true en ambas (fue facturado pero luego rectificado)
-             if ((!$estaEnFactura and !$estaEnFacturaRectificativa) or ($estaEnFactura and $estaEnFacturaRectificativa)) {
-                 $sumatoriaTotalNet = $sumatoriaTotalNet + $item->getTotalNet();
-                 $sumatoriaTotalVat = $sumatoriaTotalVat + $item->getVat();
-                 $sumatoriaTotal = $sumatoriaTotal + $item->getTotal();
-             }
-         }
-         $toXls = $request->request->get('boolToXls');
-         if (!empty($toXls)){
-             $id = 0;
-             // Solicita el servicio de excel
-             $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
-             $phpExcelObject->getProperties()->setCreator("InOut Travel & Events")
-                 ->setLastModifiedBy("InOut Travel & Events")
-                 ->setTitle("InOut Travel & Events")
-                 ->setSubject("InOut Travel & Events")
-                 ->setDescription("InOut Travel & Events, generado usando clases de PHP")
-                 ->setKeywords("office 2005 openxml php")
-                 ->setCategory("Archivo de ejemplo");
-             $fill = new Fill();
-             $numberFormat = new NumberFormat();
-             $alignment = new Alignment();
-             $i = 6;
-             $indiceInicial = 7;
-             $indiceFinal = 7;
-             $activesheet = $phpExcelObject->getActiveSheet();
-             $drawingobject = $this->get('phpexcel')->createPHPExcelWorksheetDrawing();
-             $drawingobject->setName('Image name');
-             $drawingobject->setDescription('Image description');
-             $drawingobject->setPath(getcwd().'/assets/images/logo/logo_green_patio.png');
-             $drawingobject->setHeight(60);
-             $drawingobject->setOffsetY(20);
-             $drawingobject->setCoordinates('Q1');
-             $drawingobject->setWorksheet($activesheet);
-             $phpExcelObject
-                 ->getActiveSheet()
-                 ->getStyle('B3:O3')
-                 ->getFill()
-                 ->setFillType($fill::FILL_SOLID)
-                 ->getStartColor()
-                 ->setRGB('9fc4a6');
-             $phpExcelObject->setActiveSheetIndex(0)
-                 ->setCellValue('C3','LISTADO DE FACTURACION')
-             ;
-             $phpExcelObject->setActiveSheetIndex(0)
-                 ->setCellValue('B'.$i, 'Fecha')
-                 ->setCellValue('D'.$i, 'Número')
-                 ->setCellValue('F'.$i, 'Expediente')
-                 ->setCellValue('H'.$i, 'Nombre del Evento')
-                 ->setCellValue('L'.$i, 'Cliente')
-                 ->setCellValue('O'.$i, 'Tipo')
-                 ->setCellValue('Q'.$i, 'Neto')
-                 ->setCellValue('S'.$i, 'Total')
-             ;
-             $data = array();
-             $data = $invoiced;
-             foreach ($data as $item) {
-                 $time = $item->getDateAt()->format('d/m/Y');
-                 $idExp = ($item->getType() == 'Invoice Rec') ? 'R'.$item->getId() : $item->getId();
-                 $clientTypeText = ($item->getClientType() == 'Client') ? 'Cliente' : 'Proveedor';
-                 $phpExcelObject->setActiveSheetIndex(0)
-                     ->setCellValue('B' . ($i + 1), $time)
-                     ->setCellValue('D' . ($i + 1), $idExp)
-                     ->setCellValue('F' . ($i + 1), $item->getReservationId())
-                     ->setCellValue('H' . ($i + 1), $item->getNumber())
-                     ->setCellValue('L' . ($i + 1), $item->getClientName())
-                     ->setCellValue('O' . ($i + 1), $clientTypeText)
-                     ->setCellValue('Q' . ($i + 1), $item->getTotalNet())
-                     ->setCellValue('S' . ($i + 1), $item->getTotal())
-                 ;
-                 $i++;
-                 $indiceFinal++;
-             }
-             $indiceFinal--;
-             $indicesResta = $indiceFinal - $indiceInicial + 1;
-             $phpExcelObject
-                 ->getActiveSheet()
-                 ->getStyle('Q' . ($indiceFinal + 3) . ':' . 'S' . ($indiceFinal + 3))
-                 ->getFill()
-                 ->setFillType($fill::FILL_SOLID)
-                 ->getStartColor()
-                 ->setRGB('9fc4a6');
-             $phpExcelObject->setActiveSheetIndex(0)
-                 ->setCellValue('Q' . ($indiceFinal + 3), 'Total Neto')
-                 ->setCellValue('S' . ($indiceFinal + 3), 'Total');
-             $phpExcelObject->setActiveSheetIndex(0)
-                 ->setCellValue('Q' . ($indiceFinal + 4), '=SUM(' . 'Q' . $indiceInicial . ' : Q' . $indiceFinal . ')')
-                 ->setCellValue('S' . ($indiceFinal + 4), '=SUM(' . 'S' . $indiceInicial . ' : U' . $indiceFinal . ')');
-             $phpExcelObject->getActiveSheet()->setTitle('Estadísticas por sala');
-             // Define el indice de página al número 1, para abrir esa página al abrir el archivo
-             $phpExcelObject->setActiveSheetIndex(0);
-             // Creamos pagina de Datos en bruto para Esteban Rincon
-             // Add new sheet
-             $objWorkSheet = $phpExcelObject->createSheet(1); //Setting index when creating
-             $phpExcelObject->setActiveSheetIndex(1);
-             $phpExcelObject->getActiveSheet()->setTitle('Datos en bruto');
-             $x = 1;
-             $phpExcelObject->setActiveSheetIndex(1)
-                 ->setCellValue('A'.$x, 'Fecha')
-                 ->setCellValue('B'.$x, 'Número')
-                 ->setCellValue('C'.$x, 'Expediente')
-                 ->setCellValue('D'.$x, 'Nombre del Evento')
-                 ->setCellValue('E'.$x, 'Cliente')
-                 ->setCellValue('F'.$x, 'Tipo')
-                 ->setCellValue('G'.$x, 'Neto')
-                 ->setCellValue('H'.$x, 'Total')
-             ;
-             foreach ($data as $item) {
-                 $time = $item->getDateAt()->format('d/m/Y');
-                 $idExp = ($item->getType() == 'Invoice Rec') ? 'R'.$item->getId() : $item->getId();
-                 $clientTypeText = ($item->getClientType() == 'Client') ? 'Cliente' : 'Proveedor';
-                 $phpExcelObject->setActiveSheetIndex(1)
-                     ->setCellValue('A' . ($x + 1), $time)
-                     ->setCellValue('B' . ($x + 1), $idExp)
-                     ->setCellValue('C' . ($x + 1), $item->getReservationId())
-                     ->setCellValue('D' . ($x + 1), $item->getNumber())
-                     ->setCellValue('E' . ($x + 1), $item->getClientName())
-                     ->setCellValue('F' . ($x + 1), $clientTypeText)
-                     ->setCellValue('G' . ($x + 1), $item->getTotalNet())
-                     ->setCellValue('H' . ($x + 1), $item->getTotal())
-                 ;
-                 $x++;
-             }
-             $phpExcelObject->setActiveSheetIndex(0);
-             // Crea el writer
-             $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');
-             // Envia la respuesta del controlador
-             $response = $this->get('phpexcel')->createStreamedResponse($writer);
-             // Agrega los headers requeridos
-             $dispositionHeader = $response->headers->makeDisposition(
-                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
-                 'Green Patio - Listado Facturas La Imprenta'.'.xlsx'
-             );
-             $response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');
-             $response->headers->set('Pragma', 'public');
-             $response->headers->set('Cache-Control', 'maxage=1');
-             $response->headers->set('Content-Disposition', $dispositionHeader);
-             $phpExcelObject->getActiveSheet()->setTitle('Facturación Green Patio');
-             // Define el indice de página al número 1, para abrir esa página al abrir el archivo
-             $phpExcelObject->setActiveSheetIndex(0);
-             // Crea el writer
-             $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');
-             // Envia la respuesta del controlador
-             $response = $this->get('phpexcel')->createStreamedResponse($writer);
-             // Agrega los headers requeridos
-             $dispositionHeader = $response->headers->makeDisposition(
-                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
-                 'Green Patio - Listado Facturacion La Imprenta.xlsx'
-             );
-             $response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');
-             $response->headers->set('Pragma', 'public');
-             $response->headers->set('Cache-Control', 'maxage=1');
-             $response->headers->set('Content-Disposition', $dispositionHeader);
-             return $response;
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-invoice.html.twig',
-             array(
-                 'invocied' => $invoiced,
-                 'sumatoriaTotalNet' => $sumatoriaTotalNet,
-                 'sumatoriaTotalVat' => $sumatoriaTotalVat,
-                 'sumatoriaTotal' => $sumatoriaTotal,
-             )
-         );
-     }
-     /**
-      * @Route("/reservations/updateinvoicedate/", name="reservation_update_invoice_date")
-      * Editar la fecha de una factura
-      */
-     public function updateInvoiceDateAction( Request $request){
-         $em = $this->getDoctrine()->getManager();
-         $invoiceId = $request->request->get('invoice_id');
-         $invoiceNewDate = $request->request->get('new_invoice_date');
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $invoice = $em->getRepository(ReservationInvoice::class)->findOneById($invoiceId);
-         $newDate = new DateTime($invoiceNewDate);
-         $invoice->setDateAt($newDate);
-         // Modificamos el number para que se adapte a la nueva fecha
-         $invoice->setNumber('GPF-' . $newDate->format('dmy') . substr($invoice->getNumber(),10));
-         $invoice->setUpdatedId($user_id);
-         $invoice->setUpdatedAt(new DateTime('now'));
-         $em->persist($invoice);
-         $em->flush();
-         return $this->redirectToRoute('reservation_invoice_list');
-     }
-     /**
-      * @Route("/mkbdgt/{token}", name="reservations_greenpatio_make_budget")
-      */
-     public function makeBudgetAction($token, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $budgetControl = $em->getRepository(ReservationBudgetControl::class)->findOneByToken($token);
-         $allBudgets = $em->getRepository(ReservationBudgetControl::class)->findByReservationId($budgetControl->getReservationId());
-         $id = $budgetControl->getReservationId();
- //        $paymentsClient = new ReservationPaymentsClient();
- //        $paymentsClient->setReservationId($id);
- //        $form = $this->createReservationPaymentsClientForm($paymentsClient);
-         $reserva = $em->getRepository(Reservation::class)->findOneById($id);
- //        $payments = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
-         $services = $em->getRepository(ReservationService::class)->findByReservationId($id);
-         $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
- //        $allProformas = $em->getRepository(ReservationProforma::class)->findAll();
- //        if (!empty($allProformas)){
- //            $number = end($allProformas)->getId() + 1;
- //        } else {
-         // Primer registro de proformas
-         $number = 1;
- //        }
-         $type = 'Proforma';
-         $date = new DateTime('now');
-         $prefix = "GP-".$date->format('dmy')."-";
-         $reservaInv = new ReservationInvoice();
-         $reservaInv->setReservationId($id);
- //        $form1 = $this->createReservationInvoiceProformaForm($reservaInv);
-         $data = $this->baseInvoiceReservation($id, $type, $number, $prefix, $date);
- //        $token = $data['token'];
-         $idLounges = array();
-         if (array_key_exists('lounge',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['lounge'] as $key => $item) {
-                 $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneByLngControlId($item['id']);
-                 if (empty($existe)){
-                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = true;
-                 } else {
-                     $data['datasupplier']['lounge'][$key]['enabledToInvoice'] = false;
-                 }
-             }
-         }
-         if (array_key_exists('service',$data['datasupplier'])) {
-             foreach ($data['datasupplier']['service'] as $key => $item) {
-                 $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneBySrvControlId($item['id']);
-                 if (empty($existe)){
-                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = true;
-                 } else {
-                     $data['datasupplier']['service'][$key]['enabledToInvoice'] = false;
-                 }
-             }
-         }
- //        $idPayments = array();
- //        if (array_key_exists('payment',$data['datasupplier'])) {
- //            foreach ($data['datasupplier']['payment'] as $key => $item) {
- //                $existe = $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($item['id']);
- //
- //                if (empty($existe)){
- //                    $data['datasupplier']['payment'][$key]['enabledToInvoice'] = true;
- //                } else {
- //                    $data['datasupplier']['payment'][$key]['enabledToInvoice'] = false;
- //                }
- //            }
- //        }
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         return $this->render('MDS/GreenPatioBundle/reservations/budget-add-items.html.twig',
-             array(
-                 'id' => $id,
-                 'idLounges' => $idLounges,
-                 'reserva' => $reserva,
-                 'idPayments' => null,
-                 'type' => $data['type'],
-                 'number' => $data['number'],
-                 'prefix' => $data['prefix'],
-                 'date' => $data['date'],
-                 'token' => $token,
-                 'company' => $data['company'],
-                 'clients' => $data['clients'],
-                 'datasupplier' => $data['datasupplier'],
-                 'currency' => $data['currency'],
-                 'totales_neto' => $data['totales_neto'],
-                 'bases_imponibles' => $data['bases_imponibles'],
-                 'totales' => $data['totales'],
-                 'balance' => $data['balance'],
-                 'paymentInvoice' => $data['paymentInvoice'],
-                 'payments' => null,
-                 'user_id' => $user_id,
-                 'allBudgets' => $allBudgets,
-             )
-         );
-     }
-     /**
-      * @Route("/createbdgt/{token}", name="reservations_greenpatio_create_budget")
-      */
-     public function createBudgetAction($token, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         $budgetControl = $em->getRepository(ReservationBudgetControl::class)->findOneByToken($token);
-         $nameBud = $request->request->get('budget_name_hidden');
-         $budgetControl->setName($nameBud);
-         $em->persist($budgetControl);
-         $em->flush();
-         /* Obtengo usuario logueado */
-         $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
-         $user_id = $user_logueado->getId();
-         $arrayLounge = $request->request->get('lounge_hidden_bool');
-         $arrayService = $request->request->get('service_hidden_bool');
-         foreach ($arrayLounge as $key => $item) {
-             if ($item == 'true'){
-                 //Buscamos la sala
-                 $lounge = $em->getRepository(ReservationLoungeSimple::class)->findOneById($key);
-                 $budgetItem = new ReservationBudgetItems();
-                 $budgetItem->setReservationId($budgetControl->getReservationId());
-                 $budgetItem->setControlId($budgetControl->getId());
-                 $budgetItem->setItemType('LOUNGE');
-                 $budgetItem->setLngControlId($key);
-                 $budgetItem->setLngLoungeName($lounge->getLoungeName());
-                 $budgetItem->setLngIdLounge($lounge->getIdLounge());
-                 $budgetItem->setLngDateStart($lounge->getDateStart());
-                 $budgetItem->setLngDateEnd($lounge->getDateEnd());
-                 $budgetItem->setLngServicePrice($lounge->getServicePrice());
-                 $budgetItem->setLngPax($lounge->getPax());
-                 $budgetItem->setLngType($lounge->getType());
-                 $budgetItem->setLngHourStart($lounge->getHourStart());
-                 $budgetItem->setLngMinStart($lounge->getMinStart());
-                 $budgetItem->setLngHourEnd($lounge->getHourEnd());
-                 $budgetItem->setLngMinEnd($lounge->getMinEnd());
-                 $budgetItem->setCreatedAt(new DateTime('now'));
-                 $budgetItem->setCreatedId($user_id);
-                 $budgetItem->setUpdatedAt(new DateTime('now'));
-                 $budgetItem->setUpdatedId($user_id);
-                 $em->persist($budgetItem);
-                 $em->flush();
-             }
-         }
-         foreach ($arrayService as $key => $item) {
-             if ($item == 'true'){
-                 //Buscamos el servicio
-                 $service = $em->getRepository(ReservationService::class)->findOneById($key);
-                 $budgetItem = new ReservationBudgetItems();
-                 $budgetItem->setReservationId($budgetControl->getReservationId());
-                 $budgetItem->setControlId($budgetControl->getId());
-                 $budgetItem->setItemType('SERVICE');
-                 $budgetItem->setSrvControlId($key);
-                 $budgetItem->setSrvSupplierId($service->getSupplierId());
-                 $budgetItem->setSrvServiceId($service->getServiceId());
-                 $budgetItem->setSrvServiceCatId($service->getServiceCatId());
-                 $budgetItem->setSrvServiceCatName($service->getServiceCatName());
-                 $budgetItem->setSrvName($service->getName());
-                 $budgetItem->setSrvPrice($service->getPrice());
-                 $budgetItem->setSrvCurrency($service->getCurrency());
-                 $budgetItem->setSrvUnits($service->getUnits());
-                 $budgetItem->setSrvOpCommissions($service->getOpCommissions());
-                 $budgetItem->setSrvCommissions($service->getCommissions());
-                 $budgetItem->setSrvOpOver($service->getOpOver());
-                 $budgetItem->setSrvOver($service->getOver());
-                 $budgetItem->setSrvOpIva($service->getOpIva());
-                 $budgetItem->setSrvIva($service->getIva());
-                 $budgetItem->setSrvPax($service->getPax());
-                 $budgetItem->setSrvHour($service->getHour());
-                 $budgetItem->setSrvHour($service->getHour());
-                 $budgetItem->setSrvDateInAt($service->getDateInAt());
-                 $budgetItem->setSrvDateOutAt($service->getDateOutAt());
-                 $budgetItem->setSrvContcolor($service->getContcolor());
-                 $budgetItem->setSrvRank($service->getRank());
-                 $budgetItem->setSrvAssistantId($service->getAssistantId());
-                 $budgetItem->setSrvActivityId($service->getActivityId());
-                 $budgetItem->setSrvPay($service->getPay());
-                 $budgetItem->setCreatedAt(new DateTime('now'));
-                 $budgetItem->setCreatedId($user_id);
-                 $budgetItem->setUpdatedAt(new DateTime('now'));
-                 $budgetItem->setUpdatedId($user_id);
-                 $em->persist($budgetItem);
-                 $em->flush();
-             }
-         }
-         $data = array();
-         $data = $this->baseInvoiceDoneReservation($budgetControl->getReservationId(), 0,'P');
- //        $allInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($newInvoice->getReservationId());
-         $allInvoices = null;
-             //Es una proforma
- //        $proforma = $em->getRepository(ReservationProforma::class)->findOneByReservationId($id);
-         $invoiceIdToRec = null;
-         return $this->render('MDS/GreenPatioBundle/reservations/budget-print.html.twig', array(
-         'id' => $budgetControl->getReservationId(),
-         'type' => $data['type'],
-         'number' => $data['number'],
-         'invoiceIdToRec' => $invoiceIdToRec,
-         'prefix' => $data['prefix'],
-         'date' => $data['date'],
-         'token' => '',
-         'company' => $data['company'],
-         'clients' => $data['clients'],
-         'datasupplier' => $data['datasupplier'],
-         'totales_neto' => $data['totales_neto'],
-         'bases_imponibles' => $data['bases_imponibles'],
-         'totales' => $data['totales'],
-         'balance' => $data['balance'],
-         'currency' => $data['currency'],
-         'paymentInvoice' => $data['paymentInvoice']
-     ));
-     }
-     /**
-      * @Route("/selinvoicesp/{id}",  name="reservations_select_invoice_special")
-      * Vista previa para selecionar la entidad a la cual se le va a facturar (cliente o proveedor)
-      */
-     public function generateReservationSpecialInvoiceAction($id, Request $request)
-     {
-         $em = $this->getDoctrine()->getManager();
-         //Buscamos los clientes
-         $clients = $em->getRepository(Client::class)->findAll();
-         //Buscamos los proveedores
-         $suppliers = $em->getRepository(Supplier::class)->findAll();
-         //Unimos en un solo arreglo
-         $arrayClients = array();
-         foreach ($clients as $item){
-             $arrayClients[] = array(
-                 'nombre' => $item->getName(),
-                 'id' => $item->getId(),
-                 'tipo' => 'CLIENTE',
-                 'indice' => 'C'.$item->getId(),
-             );
-         }
-         foreach ($suppliers as $item){
-             $arrayClients[] = array(
-                 'nombre' => $item->getCompany(),
-                 'id' => $item->getId(),
-                 'tipo' => 'PROVEEDOR',
-                 'indice' => 'S'.$item->getId(),
-             );
-         }
-         return $this->render('MDS/GreenPatioBundle/reservations/services-invoice-select-client-supplier.html.twig',
-             array(
-                 'id' => $id,
-                 'clients' => $arrayClients,
-             )
-         );
-     }
-     private function clientDataToInvoice($invoice, $typeClient, $idClient, $reservationId){
-         //Recibe una ReservationInvoice y se le agregan los datos del cliente
-         $em = $this->getDoctrine()->getManager();
-         $address = null;
-         if (empty($invoice)){
-             // Venimos de un selector y vamos a cotizar
-             $reserva = $em->getRepository(Reservation::class)->findOneById($reservationId);
-             $typeClient = 'Client'; $idClient = $reserva->getClient();
-             $invoice = new ReservationInvoice();
-         }
-         if ($typeClient == 'Client'){
-             $client = $em->getRepository(Client::class)->findOneById($idClient); $typeClient = 'Client';
-             if (!empty($client)){ $name = $client->getName(); $address = $client->getAddress() . ' ' . $client->getAddressNumber(); }
-         } else {
-             // Proveedor (Para facturas de comision)
-             $client = $em->getRepository(Supplier::class)->findOneById($idClient); $typeClient = 'Supplier';
-             if (!empty($client)){ $name = $client->getCompany(); $address = $client->getAddress(); }
-         }
-         if(empty($client)){
-             // No se encontro el cliente o proveedor, se utilizará por defecto el de la reserva
-             $reserva = $em->getRepository(Reservation::class)->findOneById($invoice->getReservationId()); $typeClient = 'Client';
-             $client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
-             if (!empty($client)){ $name = $client->getName(); $address = $client->getAddress() . ' ' . $client->getAddressNumber(); }
-         }
-         $region = $em->getRepository(Regions::class)->findOneById($client->getRegion());
-         $country = $em->getRepository(Country::class)->findOneById($client->getCountry());
-         $address = (empty($client->getRegion())) ? $address : $address. ', ' . $region->getRegion();
-         $address = (empty($client->getZipCode())) ? $address : $address. ' - ' . $client->getZipCode();
-         $address = (empty($client->getCountry())) ? $address : $address. ', ' . $country->getCountry();
-         $invoice->setClientAddress($address);
-         $invoice->setClientName($name);
-         $clientDocument = null;
-         $clientDocument = (empty($client->getTypeDocument())) ? $clientDocument : $client->getTypeDocument();
-         $clientDocument = (empty($client->getIdDocument())) ? ' ' : $clientDocument. ': ' . $client->getIdDocument();
-         $invoice->setClientDocument($clientDocument);
-         $invoice->setClientType($typeClient);
-         return $invoice;
-     }
-     private function clientOrSupplierDataSearchToInvoice($index, $reservationId){
-         //Recibe un indice C22 o S41 para buscar los datos del cliente 22 o el proveedor 41 y pasar esos datos para la siguiente factura
-         $em = $this->getDoctrine()->getManager();
-         $address = null; $name = null; $clientDocument = null; $typeClient = null;
-         if (substr($index,0,1) == 'C'){
-             // Cliente
-             $client = $em->getRepository(Client::class)->findOneById(substr($index,1,strlen($index))); $typeClient = 'Client';
-             if (!empty($client)){ $name = $client->getName(); $address = $client->getAddress() . ' ' . $client->getAddressNumber(); }
-         } else {
-             // Proveedor (Para facturas de comision)
-             $client = $em->getRepository(Supplier::class)->findOneById(substr($index,1,strlen($index))); $typeClient = 'Supplier';
-             if (!empty($client)){ $name = $client->getCompany(); $address = $client->getAddress(); }
-         }
-         if(empty($client)){
-             // No se encontro el cliente o proveedor, se utilizará por defecto el de la reserva
-             $reserva = $em->getRepository(Reservation::class)->findOneById($reservationId); $typeClient = 'Client';
-             $client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
-             if (!empty($client)){ $name = $client->getName(); $address = $client->getAddress() . ' ' . $client->getAddressNumber(); }
-         }
-         $region = $em->getRepository(Regions::class)->findOneById($client->getRegion());
-         $country = $em->getRepository(Country::class)->findOneById($client->getCountry());
-         $address = (empty($client->getRegion())) ? $address : $address. ', ' . $region->getRegion();
-         $address = (empty($client->getZipCode())) ? $address : $address. ' - ' . $client->getZipCode();
-         $address = (empty($client->getCountry())) ? $address : $address. ', ' . $country->getCountry();
-         $clientDocument = (empty($client->getTypeDocument())) ? $clientDocument : $client->getTypeDocument();
-         $clientDocument = (empty($client->getIdDocument())) ? ' ' : $clientDocument. ': ' . $client->getIdDocument();
-         $dataClient = array(
-                             'clientName' => $name,
-                             'clientAddress' => $address,
-                             'clientDocument' => $clientDocument,
-                             'clientType' => $typeClient);
-         return $dataClient;
-     }
- }