<?php

namespace App\Controller;

use App\Controller\Base\AbstractGuiaRemisionController;
use App\Entity\Model\Customer;
use App\Entity\Model\GuiaRemision;
use App\Entity\Model\Item;
use App\Entity\Model\Destinatario;
use App\Entity\Model\ItemPago;
use App\Entity\Model\Transportista;
use App\Form\DestinatarioType;
use App\Form\TransportistaType;
use App\Service\EmFactory;
use App\Util\Funciones;
use App\Util\RestApiFunciones;
use Knp\Component\Pager\PaginatorInterface;
use Mobile_Detect;
use Psr\Log\LoggerInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\HttpFoundation\Response;
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;

/**
 * @Route("/guiaremision")
 */
class GuiaRemisionController extends AbstractGuiaRemisionController
{

    protected $translator;

    /**
     * @Route("", name="guiaremision_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());

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

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

        /*$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('guiaremision_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());
        }

        $guiaremisions = [];
        foreach ($pagination as $item) {
            $guiaremisions[] = $item;
        }
        $listForm = $this->createForm('App\Form\ListGenericType', $guiaremisions, [
            'action' => $this->generateUrl('guiaremision_index'),
        ]);
        $listForm->handleRequest($request);
        if ($listForm->isSubmitted() && $listForm->isValid()) {
            $data = $listForm->getData();
            if (empty($data['guiaremisions'])) {
                $this->addTranslatedMessage('flash.nothing_selected', 'warning');
            } else {
                if ($request->request->has('delete')) {
                    return $this->bulkDelete($data['guiaremisions']);
                } elseif ($request->request->has('pdf')) {
                    return $this->bulkPdf($data['guiaremisions']);
                } elseif ($request->request->has('print')) {
                    return $this->bulkPrint($data['guiaremisions']);
                } elseif ($request->request->has('email')) {
                    return $this->bulkEmail($data['guiaremisions']);
                }
            }
        }
        return $this->render('GuiaRemision\index.html.twig',
            array(
                'guiaremisions' => $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}gr{id}", name="guiaremision_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();

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

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

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

        $form = $this->createFormBuilder($defaultData)
            ->add('slug', HiddenType::class)
            ->add('id', HiddenType::class)
            ->add('customerEmail')
            ->setAction($this->generateUrl('guiaremision_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('guiaremision_edit', ['id' => $entity->getId(), 'slug' => $slug]));
            } elseif ($request->request->has('Form-delete')) {
                $error = $this->delete($entity);
                if ($error)
                    return $this->redirect($this->generateUrl('guiaremision_index'));
            } elseif ($request->request->has('Form-anular')) {
                $entity->setAnulado(true);
                $em->persist($entity);
                $em->flush();
            } elseif ($request->request->has('Form-enviar')) {
                $this->enviarSriOnline($entity);
            } 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 guiaremision is open send to the edit form by default.
            return $this->redirect($this->generateUrl('guiaremision_edit', array('id' => $id)));
        }
        */

        return $this->render('GuiaRemision\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(),
            ));
    }

    /**
     * @Route("/new", name="guiaremision_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();

        $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?'SU PLAN CADUCADO EL: '.$empresa->getFechaCaduca()->format('d/m/Y'):$empresa->getMensaje(), 'danger');
            return $this->redirect($this->generateUrl('guiaremision_index'));
        }
        // Check for mobile environment.
        $movil = false;
        if ($detect->isMobile()) {
            // Your code here.
            $movil = true;
        }

        $guiaremision = new GuiaRemision();
        $guiaremision->setDireccionpPartida($empresa->getDireccionMatriz());

        /*if ($request->isMethod('GET')) {
            $customerRepo = $em->getRepository(Customer::class);
            $consfinal = $customerRepo->findConsumidorFinal($empresa->getId());
            //$consfinal = new Customer();
            if($consfinal) {
                $guiaremision->setCustomer($consfinal);
                $guiaremision->setInvoicingAddress($consfinal->getInvoicingAddress());
                $guiaremision->setCustomerEmail($consfinal->getEmail());
                $guiaremision->setCustomerName($consfinal->getName());
                $guiaremision->setCustomerIdentification($consfinal->getIdentification());
            }

        }*/

        $form = $this->createForm('App\Form\GuiaRemisionType', $guiaremision, [
            'action' => $this->generateUrl('guiaremision_add'),
        ]);

        $destinatario = new Destinatario();
        $formdestinatario = $this->createForm(DestinatarioType::class, $destinatario, [

        ]);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($request->request->has('save_draft')) {
                $guiaremision->setStatus(GuiaRemision::DRAFT);
            } else {
                // Any save action transforms this to opened.
                $guiaremision->setStatus(GuiaRemision::OPENED);
            }

            //if ($guiaremision->getCustomer() == null && $guiaremision->getCustomerIdentification() != '9999999999999') {
            //    $this->addTranslatedMessage('Cliente no se encuentra registrado', 'danger');
            //} else {
                //$guiaremision->setNumber(null);
                $serie = $guiaremision->getSeries()->getValue();
                $guiaremision->setSerie($serie);
                $guiaremision->setEmpresa($empresa);
                $guiaremision->setUsuario($user->getId());
                $guiaremision->setAmbiente($empresa->getTipoAmbiente());

                $em->persist($guiaremision);
                $em->flush();
                //$this->addTranslatedMessage('flash.added');

                $guiaremision_id = $guiaremision->getId();

                $guiaremision = $this->generarXml($guiaremision);

                if ($empresa->getEnvioAutomatico()) {

                    /*if ($guiaremision !== null) {
                        $app_url = $this->getParameter('cola_url');

                        $error = false;

                        $resp = RestApiFunciones::enviarComprobanteCola($error,
                            $guiaremision->getCustomerName(),
                            $guiaremision->getCustomerEmail(),
                            $user->getId(),
                            $guiaremision->getXml(),
                            $guiaremision->getClaveAcceso(),
                            $app_url,
                            'guiaremision'
                        );

                        if ($error) {
                            $this->addTranslatedMessage($resp, 'danger');
                            $guiaremision->setMensajeError($resp);
                        }

                        $em->persist($guiaremision);
                        $em->flush();

                    }

                    return $this->redirect($this->generateUrl('guiaremision_index'));
                    */

                }
                return $this->redirect($this->generateUrl('guiaremision_show', ['id' => $guiaremision_id, 'slug' => $guiaremision->getSlug()]));
            //}
        }

        $transportista = new Transportista();

        $formtransportista = $this->createForm(TransportistaType::class, $transportista, [
            'action' => $this->generateUrl('rest_transportista_add'),
        ]);
        $formtransportista->handleRequest($request);

        $customer = new Customer();

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

        return $this->render('GuiaRemision\edit.html.twig',
            array(
                'form' => $form->createView(),
                'formdestinatario' => $formdestinatario->createView(),
                'movil' => $movil,
                'formtransportista' => $formtransportista->createView(),
                'transportista' => $transportista,
                'formcustomer' => $formcustomer->createView(),
                'customer' => $customer,
                'entity' => $guiaremision,
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $empresa == null ? 'USD' : $empresa->getCurrency(),
                'decpunit' => $empresa->getDecPunit(),
            ));
    }


    /**
     * @Route("/edit/{slug}inv{id}", name="guiaremision_edit")
     *
     */
    public function editAction($id, EmFactory $emFactory, Request $request, $slug, 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());

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

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

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

        $destinatario = new Destinatario();
        $formdestinatario = $this->createForm(DestinatarioType::class, $destinatario, [

        ]);

        $form->handleRequest($request);

        $entity->setEmpresa($empresa);

        if ($form->isSubmitted() && $form->isValid()) {
            $redirectRoute = 'guiaremision_show';

            $serie = $entity->getSeries()->getValue();
            $entity->setSerie($serie);
            $entity->setUsuario($user->getId());

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

            /*
            // See if one of PDF/Print buttons was clicked.
            if ($request->request->has('save_pdf')) {
                $redirectRoute = 'guiaremision_show_pdf';
            } elseif ($request->request->has('save_print')) {
                $this->get('session')->set('guiaremision_auto_print', $id);
            }

            */

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

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

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

        $transportista = new Transportista();

        $formtransportista = $this->createForm(TransportistaType::class, $transportista, [
            'action' => $this->generateUrl('rest_transportista_add'),
        ]);
        $formtransportista->handleRequest($request);

        $customer = new Customer();

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

        return $this->render('GuiaRemision\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(),
                'formtransportista' => $formtransportista->createView(),
                'transportista' => $transportista,
                'formcustomer' => $formcustomer->createView(),
                'customer' => $customer,
                'formdestinatario' => $formdestinatario->createView(),
            ));
    }

    public function enviarSriOnline(GuiaRemision $guiaremision)
    {
        $guiaremision = $this->generarXml($guiaremision);
        $em = $this->getDoctrine()->getManager();

        if($guiaremision !== null) {
            $app_url = $this->getParameter('api_url');

            $error = false;
            $resp = RestApiFunciones::enviarComprobante($error, $guiaremision->getXml(), $guiaremision->getClaveAcceso(), $app_url);

            if ($error)
                $this->addTranslatedMessage($resp->message, 'danger');
            else {
                if ($resp->estado === 'recibido') {
                    $resp = $this->consultarAutorizacion($guiaremision);

                    if ($resp !== null)
                        $this->addTranslatedMessage($resp, 'danger');
                } else {
                    $guiaremision->setMensajeError($resp->message);
                    $this->addTranslatedMessage($resp->message, 'danger');
                    $em->persist($guiaremision);
                    $em->flush();
                }
            }

        }
    }

    /**
     * @Route("/payments/{slug}inv{id}", name="guiaremision_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
        $guiaremision = $em->getRepository('App\Entity\Model\GuiaRemision')->findBySlug($slug);
        if (!$guiaremision) {
            throw $this->createNotFoundException('Unable to find GuiaRemision entity.');
        }

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

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

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

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

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

        return $this->render('Payment\list.html.twig',
            [
                'guiaremisionId' => $guiaremisionId,
                '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="guiaremision_form_totals")
     */
    public function getGuiaRemisionFormTotals(EmFactory $emFactory, Request $request)
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();

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

        $response = $this->getGuiaRemisionTotalsFromPost($post, new GuiaRemision, $request->getLocale());

        return new JsonResponse($response);
    }

    /**
     * @Route("/pdfpreview/{slug}inv{id}", name="guiaremision_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());

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

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

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

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

        $error = false;
        $mensaje = "";

        $docPdf = RestApiFunciones::getPdf($error, $app_url, $guiaremision->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="guiaremision_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(GuiaRemision::class)->findBySlug($slug, $id);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Guia Remision entity.');
        }

        if ($invoice->getAutorizado()) {
            $filename = 'GR-' . $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();

    }


}
