<?php

namespace App\Controller;

use App\Controller\Base\AbstractInvoiceController;
use App\Electronico\Comprobante;
use App\Entity\Model\Customer;
use App\Entity\Model\Invoice;
use App\Entity\Model\Item;
use App\Entity\Model\ItemPago;
use App\Entity\Model\PlacasSocios;
use App\Entity\Model\TransporteSocio;
use App\Service\EmFactory;
use App\Util\ExportInvoicePartnerExcel;
use App\Util\Funciones;
use App\Util\RestApiFunciones;
use Doctrine\ORM\EntityManager;
use Knp\Component\Pager\PaginatorInterface;
use Mobile_Detect;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\NodeVisitor\MacroAutoImportNodeVisitor;

/**
 * @Route("/invoice")
 */
class InvoiceController extends AbstractInvoiceController
{

    protected $translator;

    /**
     * @Route("", name="invoice_index")
     *
     */
    public function indexAction(EmFactory $emFactory, Request $request, PaginatorInterface $paginator, TranslatorInterface $translator)
    {
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $emisor = $empresaRepo->findOneByUser($user->getRuc());

        $puedeFacturar = Funciones::getValidaPuedeFacturar($emisor, $em);
        $emisor = Funciones::getValidaEmitidos($emisor, $em);

        $repo = $em->getRepository('App\Entity\Model\Invoice');
        $repo->setPaginator($paginator);
        // @todo Unhardcode this.

        $limit = 20;
        if ($request->query->has('pdf') || $request->query->has('excel'))
            $limit = 10000;

        /*$fecha = new \DateTime();
        $fecha->modify('first day of this month');
        $desde = \DateTime::createFromFormat('d/m/Y', $fecha->format('d/m/Y'));
        $fecha->modify('last day of this month');
        $hasta = \DateTime::createFromFormat('d/m/Y', $fecha->format('d/m/Y'));

        $data = [
            'terms' => null,
            'status' => null,
            'date_from' => $desde,
            'date_to' => $hasta
        ];

        */

        $form = $this->createForm('App\Form\SearchGenericType', null, [
            'action' => $this->generateUrl('invoice_index'),
            'method' => 'GET',
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $pagination = $repo->paginatedSearch($form->getData(), $limit, $request->query->getInt('page', 1), $emisor->getId());
        } else {
            $pagination = $repo->paginatedSearch([], $limit, $request->query->getInt('page', 1), $emisor->getId());
        }

        $invoices = [];
        $reporte = [];
        foreach ($pagination->getItems() as $item) {
            $invoices[] = $item[0];

            if ($request->query->has('pdf') || $request->query->has('excel')) {
                //$item[0] = new Invoice();
                $aux['emision'] = $item[0]->getIssueDate();
                $aux['serie'] = $item[0]->getSerie();
                $aux['numero'] = $item[0]->getNumber();
                $aux['total'] = $item[0]->getGrossAmount();
                $aux['tipo_iva'] = $item[0]->getPorIva();
                $aux['ruc'] = $item[0]->getCustomerIdentification();
                $aux['cliente'] = $item[0]->getCustomerName();
                $aux['estado'] = $item[0]->getEstado();
                $aux['clave'] = $item[0]->getClaveAcceso();
                $aux['fecAutorizacion'] = $item[0]->getFechaAutorizacion();
                $aux['anulado'] = $item[0]->getAnulado() == true ? "1" : "0";
                $aux['nota1'] = $item[0]->getNotes();
                $aux['nota2'] = $item[0]->getNote1();
                $reporte[] = $aux;
            }
        }

        if ($form->isSubmitted()) {
            if ($request->query->has('pdf')) {
                return $this->reportePdf($reporte);
            } elseif ($request->query->has('excel')) {
                return $this->reporteExcel($reporte);
            }
        }

        $listForm = $this->createForm('App\Form\ListGenericType', $invoices, [
            'action' => $this->generateUrl('invoice_index'),
        ]);
        $listForm->handleRequest($request);
        if ($listForm->isSubmitted() && $listForm->isValid()) {
            $data = $listForm->getData();
            //if (empty($data['invoices'])) {
            //    $this->addTranslatedMessage('flash.nothing_selected', 'warning');
            //} else {
            if ($request->request->has('delete')) {
                return $this->bulkDelete($data['invoices']);
            } elseif ($request->request->has('pdf')) {
                return $this->bulkPdf($data['invoices']);
            } elseif ($request->request->has('print')) {
                return $this->bulkPrint($data['invoices']);
            } elseif ($request->request->has('email')) {
                return $this->bulkEmail($data['invoices']);
            }
            //}
        }
        return $this->render('Invoice\index.html.twig',
            array(
                'invoices' => $pagination,
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $emisor == null ? 'USD' : $emisor->getCurrency(),
                'search_form' => $form->createView(),
                'list_form' => $listForm->createView(),
            ));
    }


    /**
     * @Route("/show/{slug}inv{id}", name="invoice_show")
     *
     */
    public function showAction($id, EmFactory $emFactory, $slug, TranslatorInterface $translator, Request $request, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $emdefault = $this->getDoctrine()->getManager('default');
        $codigosaux = Funciones::getCodAuxiliares($emdefault);

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $emisor = $empresaRepo->findOneByUser($user->getRuc());

        $entity = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $defaultData = ['slug' => $slug, 'id' => $id, 'customerEmail' => $entity->getCustomerEmail()];

        $form = $this->createFormBuilder($defaultData)
            ->add('slug', HiddenType::class)
            ->add('id', HiddenType::class)
            ->add('customerEmail')
            ->setAction($this->generateUrl('invoice_show', ['id' => $id, 'slug' => $slug]))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // data is an array with "name", "email", and "message" keys
            $data = $form->getData();

            if ($request->request->has('Form-pdf')) {
                $this->generarPdf($entity);
            } elseif ($request->request->has('Form-email')) {
                if (isset($data['customerEmail'])) {
                    $email = $data['customerEmail'];
                    $this->enviarMail($email, $entity);
                } else
                    $this->addTranslatedMessage('Email del cliente nulo o en blanco', 'warning');
            } elseif ($request->request->has('Form-edit')) {
                if ($entity->getAutorizado() === false)
                    return $this->redirect($this->generateUrl('invoice_edit', ['id' => $entity->getId(), 'slug' => $slug]));
            } elseif ($request->request->has('Form-delete')) {
                $error = $this->delete($entity);
                if ($error)
                    return $this->redirect($this->generateUrl('invoice_index'));
            } elseif ($request->request->has('Form-anular')) {
                $entity->setAnulado(true);
                $em->persist($entity);
                $em->flush();
            } elseif ($request->request->has('Form-enviar')) {
                $this->enviarSriOnline($entity, $codigosaux);
            } elseif ($request->request->has('Form-auto')) {
                if ($entity->getAutorizado() === false) {
                    $resp = $this->consultarAutorizacion($entity);
                    if ($resp != null)
                        $this->addTranslatedMessage($resp, 'danger');
                }

            }
        }

        if ($entity->getMensajeError()) {
            $this->addTranslatedMessage($entity->getMensajeError(), 'danger');
        }

        /*if (!$entity->isClosed()) {
            // When the invoice is open send to the edit form by default.
            return $this->redirect($this->generateUrl('invoice_edit', array('id' => $id)));
        }
        */

        return $this->render('Invoice\show.html.twig',
            array(
                'entity' => $entity,
                'form' => $form->createView(),
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $emisor == null ? 'USD' : $emisor->getCurrency(),
                'decpunit' => $emisor->getDecPunit(),
                'transportesocio' => $entity->getTransportesocio() ? $entity->getTransportesocio() : null
            ));
    }

    /**
     * @Route("/new", name="invoice_add")
     *
     */
    public function newAction(EmFactory $emFactory, Request $request, TranslatorInterface $translator)
    {
        //require_once "Mobile_Detect.php";
        $detect = new Mobile_Detect;


        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $emdefault = $this->getDoctrine()->getManager('default');
        $codigosaux = Funciones::getCodAuxiliares($emdefault);
        $em = $emFactory->getEm();

        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        $puedefacturar = Funciones::getValidaPuedeFacturar($empresa, $em);
        $empresa = Funciones::getValidaEmitidos($empresa, $em);

        if ($empresa->getPuedefacturar() === false && $empresa->getTipoAmbiente() === "2") {
            $this->addTranslatedMessage(
                ($empresa->getMensaje() === null
                    ? 'PLAN CADUCADO EL: ' . $empresa->getFechaCaduca()->format('d/m/Y')
                    : $empresa->getMensaje()
                ) . ' | Soporte: 0987635146',
                'danger'
            );

            return $this->redirect($this->generateUrl('invoice_index'));
        }
        // Check for mobile environment.
        $movil = false;
        if ($detect->isMobile()) {
            // Your code here.
            $movil = true;
        }

        $cambioplan = false;
        $total = $em->getRepository(Invoice::class)->getFacturasxMes($empresa->getId());
        $plan = $empresa->getPlan();
        $planes = null;
        $msgcambioplan = "";
        if ($plan->getIlimitado() === false) {
            if ($total > floatval($plan->getNumFacMes())) {
                $planesRepo = $em->getRepository('App\Entity\Model\Planes');
                $planes = $planesRepo->findTodos();
                foreach ($planes as $key => $aux) {
                    if ($aux === $plan) {
                        unset($planes[$key]);
                        break;
                    }
                }
                //$this->addTranslatedMessage('Número de facturas emitidas excede del plan contratado', 'danger');
                $msgcambioplan = 'N&uacute;mero de facturas emitidas excede del plan contratado | soporte: 0987635146.';
                $cambioplan = true;
            }
        }

        $invoice = new Invoice();
        $invoice->setEmpresa($empresa);
        $newItem = new Item();

        $tax = $em->getRepository('App\Entity\Model\Tax')->findTaxDefault($empresa->getId());
        $newItem->setTaxes($tax);
        $invoice->addItem($newItem);

        $itemPago = new ItemPago();
        $invoice->addPago($itemPago);

        $itemPago1 = new ItemPago();
        $invoice->addPago($itemPago1);

        $placas = [];

        if ($empresa->getEstransportista()) {
            $socio = $empresa->getTransportesocio();
            if ($socio) {
                //$socio = new TransporteSocio();
                $placas = $em->getRepository('App\Entity\Model\TransporteSocio')->findPlacasSocioEmpresa($socio->getId());
            }
        }

        $form = $this->createForm('App\Form\InvoiceType', $invoice, [
            'action' => $this->generateUrl('invoice_add'),
        ]);

        if ($empresa->getEstransportista()) {
            $socio = $empresa->getTransportesocio();
            if ($socio) {
                $form->add('placa', EntityType::class, array(
                    'class' => 'App\Entity\Model\PlacasSocios',
                    'choice_label' => 'value',
                    'required' => true,
                    //'placeholder' => 'Seleccione una serie ...',
                    'label' => 'PLACA',
                    'choices' => $placas
                ));
            }
        }

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            if ($request->request->has('save_draft')) {
                $invoice->setStatus(Invoice::DRAFT);
            } else {
                // Any save action transforms this to opened.
                $invoice->setStatus(Invoice::OPENED);
            }

            //if ($invoice->getCustomer() == null && $invoice->getCustomerIdentification() != '9999999999999') {
            //    $this->addTranslatedMessage('Cliente no se encuentra registrado', 'danger');
            //} else {
            //$invoice->setNumber(null);
            $serie = $invoice->getSeries()->getValue();
            $invoice->setSerie($serie);
            $this->cargarImpuestos($invoice);
            $totpago = 0;
            foreach ($invoice->getPagos() as $pago) {
                //$pago = new ItemPago();
                if ($pago) {
                    if ($pago->getValor() > 0) {
                        $totpago += $pago->getValor();
                    }
                }
            }

            $invoice->checkAmounts();

            if ($totpago != $invoice->getGrossAmount()) {
                $this->addTranslatedMessage('ERROR: Total formas de pago ' . sprintf("%0.2f", $totpago) . ' NO coincide con el total de la factura ' . sprintf("%0.2f", $invoice->getGrossAmount()), 'danger');
            } else {
                $invoice->setEmpresa($empresa);
                $invoice->setUsuario($user->getId());
                $invoice->setAmbiente($empresa->getTipoAmbiente());

                if ($invoice->getCustomerIdentification() === '9999999999999' && floatval($invoice->getTotalFactura()) > 50) {
                    $this->addTranslatedMessage('Consumidor final no puede facturar mas de 50 dolares', 'danger');

                } else {
                    if ($empresa->getEstransportista()) {
                        $socio = $empresa->getTransportesocio();
                        if ($socio) {
                            $invoice->setTransportesocio($socio);
                            $auxplaca = $invoice->getPlaca()->getName();
                            $invoice->setPlaca($auxplaca);
                        }
                    }

                    if ($plan->getIlimitado() === false) {
                        $monto = $invoice->getTotalFactura();
                        $maximo = floatval($plan->getValMaxFac());
                        if ($monto > $maximo) {
                            $planesRepo = $em->getRepository('App\Entity\Model\Planes');
                            $planes = $planesRepo->findTodos();
                            foreach ($planes as $key => $aux) {
                                if ($aux === $plan) {
                                    unset($planes[$key]);
                                    break;
                                }
                            }
                            $msgcambioplan = 'Monto facturado excede el valor permitido del plan contratado.';
                            $cambioplan = true;
                        }
                    }

                    if ($cambioplan === false) {
                        $em->persist($invoice);
                        $em->flush();
                        //$this->addTranslatedMessage('flash.added');

                        $invoice_id = $invoice->getId();

                        $invoice = $this->generarXml($invoice, $codigosaux);

                        if ($request->request->has('savesend')) {
                            $this->enviarSriOnline($invoice, $codigosaux);
                        }
                        return $this->redirect($this->generateUrl('invoice_show', ['id' => $invoice_id, 'slug' => $invoice->getSlug()]));
                    }
                }
            }
        }

        $customer = new Customer();

        $formcustomer = $this->createForm('App\Form\CustomerType', $customer, [
            'action' => $this->generateUrl('rest_customer_add'),
        ]);
        $formcustomer->handleRequest($request);

        if ($cambioplan) {
            $formcambioplan = $this->createForm('App\Form\CambioPlanType', $customer, [
                'action' => $this->generateUrl('invoice_add'),
            ]);
            $formcambioplan->handleRequest($request);
        }

        /*$emdefault = $emFactory->getEmDataBase($request->getSession()->get('dbapi'));
        $alertas = null;
        $resp = Funciones::getSri($emdefault);
        $em = $emFactory->getEmDataBase($user->getDataBase());

        if (sizeof($resp) > 0) {
            if($resp["mantenimientosri"] && isset($resp['logosri'])) {
                $alerta['logosri'] = $resp['logosri'];

                $alertas[] = $alerta;
            }
        }*/

        return $this->render('Invoice\edit.html.twig',
            array(
                'form' => $form->createView(),
                'movil' => $movil,
                'formcustomer' => $formcustomer->createView(),
                'customer' => $customer,
                'entity' => $invoice,
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $empresa == null ? 'USD' : $empresa->getCurrency(),
                'decpunit' => $empresa->getDecPunit(),
                'cambioplan' => $cambioplan,
                'planes' => $planes,
                'msgcambioplan' => $msgcambioplan,
                'formcambioplan' => $cambioplan ? $formcambioplan->createView() : null,
                'estransportista' => $empresa->getEstransportista(),
                /*'srialerts' => $alertas,*/

            ));
    }


    /**
     * @Route("/edit/{slug}inv{id}", name="invoice_edit")
     *
     */
    public function editAction($id, EmFactory $emFactory, Request $request, $slug, TranslatorInterface $translator)
    {
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();
        $emdefault = $this->getDoctrine()->getManager('default');
        $codigosaux = Funciones::getCodAuxiliares($emdefault);

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        $entity = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$entity && $entity->getEmpresa() != $empresa) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        if ($entity->getAutorizado()) {
            return $this->redirect($this->generateUrl('invoice_show', ['id' => $id, 'slug' => $slug]));
        }

        $placas = [];

        if ($empresa->getEstransportista()) {
            $socio = $empresa->getTransportesocio();
            if ($socio) {
                //$socio = new TransporteSocio();
                $placas = $placas = $em->getRepository('App\Entity\Model\TransporteSocio')->findPlacasSocioEmpresa($socio->getId());
            }
        }

        $form = $this->createForm('App\Form\InvoiceType', $entity, [
            'action' => $this->generateUrl('invoice_edit', ['id' => $id, 'slug' => $slug]),
        ]);

        if ($empresa->getEstransportista()) {
            $socio = $empresa->getTransportesocio();
            if ($socio) {
                $form->add('placa', EntityType::class, array(
                    'class' => 'App\Entity\Model\PlacasSocios',
                    'choice_label' => 'value',
                    'required' => true,
                    //'placeholder' => 'Seleccione una serie ...',
                    'label' => 'PLACA',
                    'choices' => $placas,
                    'choice_value' => function ($value) {
                        //return $value->getName();

                        if (gettype($value) === PlacasSocios::class)
                            return $value->getName();
                        else
                            return $value;
                    },
                ));
            }
        }

        $form->handleRequest($request);

        $entity->setEmpresa($empresa);

        if ($form->isSubmitted() && $form->isValid()) {
            $redirectRoute = 'invoice_show';
            $serie = $entity->getSeries()->getValue();
            $entity->setSerie($serie);
            $entity->setUsuario($user->getId());
            $this->cargarImpuestos($entity);

            $totpago = 0;
            foreach ($entity->getPagos() as $pago) {
                //$pago = new ItemPago();
                if ($pago) {
                    if ($pago->getValor() > 0) {
                        $totpago += $pago->getValor();
                    }
                }
            }

            $entity->checkAmounts();

            if ($totpago != $entity->getGrossAmount()) {
                $this->addTranslatedMessage('ERROR: Total formas de pago ' . sprintf("%0.2f", $totpago) . ' NO coincide con el total de la factura ' . sprintf("%0.2f", $entity->getGrossAmount()), 'danger');
            } else {
                if ($empresa->getEstransportista()) {
                    $socio = $empresa->getTransportesocio();
                    if ($socio) {
                        $entity->setTransportesocio($socio);
                        $auxplaca = $entity->getPlaca()->getName();
                        $entity->setPlaca($auxplaca);
                    }
                }

                if ($request->request->has('save_draft')) {
                    $entity->setStatus(Invoice::DRAFT);
                } elseif ($request->request->has('save_close')) {
                    $entity->setForcefullyClosed(true);
                } elseif ($entity->isDraft()) {
                    // Any save action transforms this to opened.
                    $entity->setStatus(Invoice::OPENED);
                }

                //$customer = new Customer();
                if ($entity->getCustomerIdentification() === '9999999999999' && floatval($entity->getTotalFactura()) > 50) {
                    $this->addTranslatedMessage('Consumidor final no puede facturar mas de 50 dolares', 'danger');

                } else {
                    // Save.
                    $em->persist($entity);
                    $em->flush();
                    //$this->addTranslatedMessage('flash.updated');

                    $entity = $this->generarXml($entity, $codigosaux);

                    if ($request->request->has('savesend')) {
                        $this->enviarSriOnline($entity, $codigosaux);
                    }

                    return $this->redirect($this->generateUrl($redirectRoute, ['id' => $id, 'slug' => $slug]));
                }
            }
        }

        return $this->render('Invoice\edit.html.twig',
            array(
                'entity' => $entity,
                'form' => $form->createView(),
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $empresa == null ? 'USD' : $empresa->getCurrency(),
                'decpunit' => $empresa->getDecPunit(),
                'estransportista' => $empresa->getEstransportista(),

            ));
    }

 
 
 
 
public function enviarSriOnline(Invoice $invoice, $codigosaux = null)
{
    $invoice = $this->generarXml($invoice, $codigosaux);
    $em = $this->getDoctrine()->getManager();

    if ($invoice !== null) {

        $app_url = $this->getParameter('api_url');

        $error = false;

        $resp = RestApiFunciones::enviarComprobante(
            $error,
            $invoice->getXml(),
            $invoice->getClaveAcceso(),
            $app_url
        );
        //$this->logger->info('RESPUESTA API:', (array)$resp);
$this->get('logger')->info('RESPUESTA API:', (array)$resp);
        if ($error) {

            $errorDetalle = '';

            if(isset($resp->message)){
                $errorDetalle = $resp->message;
            }elseif(isset($resp->mensaje)){
                $errorDetalle = $resp->mensaje;
            }else{
                $errorDetalle = 'No se pudo enviar la factura al SRI.';
            }

            $linkWhatsapp = 'https://wa.me/593987635146?text=' .
                urlencode("Hola, mi factura no se pudo enviar al SRI.\n\nError:\n".$errorDetalle."\n\n¿Me pueden ayudar por favor?");

            $mensaje = '
            ❌ No se pudo enviar la factura al SRI.<br><br>

            ⚠️ Presione el botón <b>ENVIAR SRI</b> para volver a intentarlo.<br><br>

            <button type="button" class="btn btn-warning" onclick="var e=document.getElementById(\'errorSRI\');if(e.style.display===\'none\'||e.style.display===\'\'){e.style.display=\'block\';}else{e.style.display=\'none\';}">
🔎 Ver error
</button>

<div id="errorSRI" style="
display:none;
margin-top:10px;
padding:15px;
background:#fff3cd;
color:#000;
border-left:5px solid #f39c12;
border-radius:6px;
font-size:14px;
line-height:1.5;">

            <strong>Error técnico:</strong><br>

            <pre style="white-space:pre-wrap;color:#000;background:#fff;padding:10px;border-radius:5px;">
'.$errorDetalle.'
            </pre>

            <br>

            <a href="'.$linkWhatsapp.'" target="_blank" class="btn btn-success">
            📲 Pedir ayuda por WhatsApp
            </a>
            </div>

            <script>
            setTimeout(function(){

                var errorTexto = `'.$errorDetalle.'`;

                if(errorTexto.includes("CLAVE DE ACCESO REGISTRADA")){

                    var btn = document.getElementById("btn-autorizar-sri");

                    if(btn){
                        btn.classList.add("sri-alerta");
                        btn.scrollIntoView({behavior:"smooth", block:"center"});
                    }

                }else{

                    var btn = document.getElementById("btn-enviar-sri");

                    if(btn){
                        btn.classList.add("sri-alerta");
                        btn.scrollIntoView({behavior:"smooth", block:"center"});
                    }

                }

            },500);
            </script>
            ';

            $this->addTranslatedMessage($mensaje, 'danger');

        } else {

            if ($resp->estado === 'recibido') {

                $resp = $this->consultarAutorizacion($invoice);

                if ($resp !== null) {

                    $errorSri = $resp;

                    $linkWhatsapp = 'https://wa.me/593987635146?text=' .
                        urlencode("Hola, mi factura no se pudo autorizar en el SRI.\n\nError:\n".$errorSri."\n\n¿Me pueden ayudar por favor?");

                    $mensaje = '
                    ⚠️ La factura fue creada pero no se autorizó en el SRI.<br><br>

                    ⚠️ Presione el botón <b>ENVIAR SRI</b> para volver a intentarlo.<br><br>

                    <button type="button" class="btn btn-warning" onclick="document.getElementById(\'errorSRI\').style.display=\'block\'">
                    🔎 Ver error
                    </button>

                    <div id="errorSRI" style="
                    display:none;
                    margin-top:10px;
                    padding:15px;
                    background:#fff3cd;
                    color:#000;
                    border-left:5px solid #f39c12;
                    border-radius:6px;">
                    <strong>Error técnico:</strong><br>

                    <pre style="white-space:pre-wrap;color:#000;background:#fff;padding:10px;border-radius:5px;">
'.$errorSri.'
                    </pre>

                    <br>

                    <a href="'.$linkWhatsapp.'" target="_blank" class="btn btn-success">
                    📲 Pedir ayuda por WhatsApp
                    </a>
                    </div>

                    <script>
                    setTimeout(function(){

                        var errorTexto = `'.$errorSri.'`;

                        if(errorTexto.includes("CLAVE DE ACCESO REGISTRADA")){

                            var btn = document.getElementById("btn-autorizar-sri");

                            if(btn){
                                btn.classList.add("sri-alerta");
                                btn.scrollIntoView({behavior:"smooth", block:"center"});
                            }

                        }else{

                            var btn = document.getElementById("btn-enviar-sri");

                            if(btn){
                                btn.classList.add("sri-alerta");
                                btn.scrollIntoView({behavior:"smooth", block:"center"});
                            }

                        }

                    },500);
                    </script>
                    ';

                    $this->addTranslatedMessage($mensaje, 'warning');

                }

            } else {

                $errorDetalle = $resp->message ?? 'Error desconocido';

                $invoice->setMensajeError($errorDetalle);

                $linkWhatsapp = 'https://wa.me/593987635146?text=' .
                    urlencode("Hola, mi factura no se pudo enviar al SRI.\n\nError:\n".$errorDetalle."\n\n¿Me pueden ayudar por favor?");

                $mensaje = '
                ❌ Error al enviar la factura al SRI.<br><br>

                ⚠️ Presione el botón <b>ENVIAR SRI</b> para volver a intentarlo.<br><br>

                <button type="button" class="btn btn-warning" onclick="document.getElementById(\'errorSRI\').style.display=\'block\'">
                🔎 Ver error
                </button>

                <div id="errorSRI" style="
                display:none;
                margin-top:10px;
                padding:15px;
                background:#fff3cd;
                color:#000;
                border-left:5px solid #f39c12;
                border-radius:6px;">
                <strong>Error técnico:</strong><br>

                <pre style="white-space:pre-wrap;color:#000;background:#fff;padding:10px;border-radius:5px;">
'.$errorDetalle.'
                </pre>

                <br>

                <a href="'.$linkWhatsapp.'" target="_blank" class="btn btn-success">
                📲 Pedir ayuda por WhatsApp
                </a>
                </div>

                <script>
                setTimeout(function(){

                    var errorTexto = `'.$errorDetalle.'`;

                    if(errorTexto.includes("CLAVE DE ACCESO REGISTRADA")){

                        var btn = document.getElementById("btn-autorizar-sri");

                        if(btn){
                            btn.classList.add("sri-alerta");
                            btn.scrollIntoView({behavior:"smooth", block:"center"});
                        }

                    }else{

                        var btn = document.getElementById("btn-enviar-sri");

                        if(btn){
                            btn.classList.add("sri-alerta");
                            btn.scrollIntoView({behavior:"smooth", block:"center"});
                        }

                    }

                },500);
                </script>
                ';

                $this->addTranslatedMessage($mensaje, 'danger');

                $em->persist($invoice);
                $em->flush();
            }
        }
    }
}




    /**
     * @Route("/payments/{slug}inv{id}", name="invoice_payments")
     *
     */
    public function paymentsAction(Request $request, $slug, EmFactory $emFactory, TranslatorInterface $translator)
    {
        $this->translator = $translator;

        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        // Return all payments
        $invoice = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $payment = new Payment;
        $addForm = $this->createForm('App\Form\PaymentType', $payment, [
            'action' => $this->generateUrl('invoice_payments', ['id' => $invoice->getId(), 'slug' => $slug]),
        ]);
        $addForm->handleRequest($request);
        if ($addForm->isSubmitted() && $addForm->isValid()) {
            $invoice->addPayment($payment);
            $em->persist($invoice);
            $em->flush();
            $this->addTranslatedMessage('payment.flash.added');

            // Rebuild the query, since we have new objects now.
            return $this->redirect($this->generateUrl('invoice_index'));
        }

        $listForm = $this->createForm('App\Form\ListInvoicePaymentType', $invoice->getPayments()->getValues(), [
            'action' => $this->generateUrl('invoice_payments', ['id' => $invoice->getId(), 'slug' => $slug]),
        ]);
        $listForm->handleRequest($request);

        if ($listForm->isSubmitted() && $listForm->isValid()) {
            $data = $listForm->getData();
            foreach ($data['payments'] as $payment) {
                $invoice->removePayment($payment);
                $em->persist($invoice);
                $em->flush();
            }
            $this->addTranslatedMessage('payment.flash.bulk_deleted');

            // Rebuild the query, since some objects are now missing.
            return $this->redirect($this->generateUrl('invoice_index'));
        }

        return $this->render('Payment\list.html.twig',
            [
                'invoiceId' => $invoiceId,
                'add_form' => $addForm->createView(),
                'list_form' => $listForm->createView(),
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $emisor == null ? 'USD' : $emisor->getCurrency(),
            ]);
    }

    /**
     * @Route("/form-totals", name="invoice_form_totals")
     */
    public function getInvoiceFormTotals(EmFactory $emFactory, Request $request)
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();

        $post = $request->request->get('invoice');
        if (!$post) {
            throw new NotFoundHttpException;
        }

        $response = $this->getInvoiceTotalsFromPost($post, new Invoice, $request->getLocale());

        return new JsonResponse($response);
    }

    /**
     * @Route("/pdfpreview/{slug}inv{id}", name="invoice_show_pdf_preview")
     *
     */
    public function showOnlinePdfAction($id, $slug, EmFactory $emFactory, TranslatorInterface $translator, Request $request, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        $invoice = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $filename = 'FAC_' . $invoice->getSerie() . "-" . str_pad($invoice->getNumber(), 9, '0', STR_PAD_LEFT) . '.pdf';

        if ($invoice->getAutorizado())
            $xml = $invoice->getXmlAutorizado();
        else
            $xml = $invoice->getXml();

        $app_url = $this->getParameter('api_url') . 'facturaride.php';

        $error = false;
        $mensaje = "";

        $docPdf = RestApiFunciones::getPdf($error, $app_url, $invoice->getClaveAcceso(), $xml, $mensaje, $empresa->getRuc());

        if ($error) {
            $this->addTranslatedMessage('ERRROR AL GENERAR EL PDF, ' . $mensaje, 'danger');
        } else {
            file_put_contents($filename, $docPdf);

            $pdf = base64_encode(file_get_contents($filename));

            $response = new Response($pdf);
            $response->headers->set('Content-Type', 'application/octet-stream');
            $response->headers->set('Content-Description', 'File Transfer');
            $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
            // $response->headers->set('Expires', '0');
            // $response->headers->set('Content-Transfer-Encoding', 'binary');
            $response->headers->set('Content-length', strlen($pdf));
            $response->headers->set('Cache-Control', 'no-cache private');
            // $response->headers->set('Pragma', 'public');
            // Send headers before outputting anything
            $response->sendHeaders();

            try {
                unlink($filename);
            } catch (\Exception $ex) {

            }
            return $response;
        }
    }

    /**
     * @Route("download/xml/{slug}inv{id}", name="invoice_download_xml")
     *
     */
    public function xmldownloadAction($id, $slug, EmFactory $emFactory, Request $request, TranslatorInterface $translator, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        $invoice = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        if ($invoice->getAutorizado()) {
            $filename = 'FA-' . $invoice->getSerie() . "-" . str_pad($invoice->getNumber(), 9, '0', STR_PAD_LEFT) . '.xml';
            try {
                $xml = $invoice->getXmlAutorizado();

                file_put_contents($filename, $xml);

                $contentType = 'application/xml';

                $content = file_get_contents($filename);
                $response = new Response();
                $response->headers->set('Content-Type', $contentType);
                $response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '"');

                $response->headers->addCacheControlDirective('no-cache', true);
                $response->headers->addCacheControlDirective('must-revalidate', true);

                $response->setContent($content);
                return $response;
            } catch (\Exception $ex) {

            } finally {
                try {
                    unlink($filename);
                } catch (\Exception $ex) {

                }
            }

        } else
            $xml = $invoice->getXml();

    }

    private function reporteExcel($invoices)
    {

        $format = 'xlsx';
        $filename = 'facturas' . '.' . $format;

        $exportExcel = new ExportInvoicePartnerExcel();

        $titulo = "REPORTE FACTURAS";

        $spreadsheet = $exportExcel->createSpreadsheet($invoices, $titulo);

        switch ($format) {
            /*case 'ods':
                $contentType = 'application/vnd.oasis.opendocument.spreadsheet';
                $writer = new Ods($spreadsheet);
                break;
            case 'csv':
                $contentType = 'text/csv';
                $writer = new Csv($spreadsheet);
                break;*/
            case 'xlsx':
                $contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                $writer = new Xlsx($spreadsheet);
                break;

        }

        //$writer->save($filename);

        $response = new StreamedResponse();
        $response->headers->set('Content-Type', $contentType);
        $response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '"');
        $response->setPrivate();
        $response->headers->addCacheControlDirective('no-cache', true);
        $response->headers->addCacheControlDirective('must-revalidate', true);
        $response->setCallback(function () use ($writer) {
            $writer->save('php://output');
        });

        return $response;

    }


}
