<?php

namespace App\Controller;

use App\Controller\Base\AbstractCreditoController;
use App\Electronico\Comprobante;
use App\Entity\Model\Customer;
use App\Entity\Model\Ncredito;
use App\Entity\Model\Item;
use App\Service\EmFactory;
use App\Util\ExportCreditosPartnerExcel;
use App\Util\ExportInvoicePartnerExcel;
use App\Util\Funciones;
use App\Util\RestApiFunciones;
use Knp\Component\Pager\PaginatorInterface;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Log\LoggerInterface;
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;

/**
 * @Route("/credito")
 */
class CreditoController extends AbstractCreditoController
{

    protected $translator;

    /**
     * @Route("", name="credito_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\Ncredito');
        $repo->setPaginator($paginator);
        // @todo Unhardcode this.
        $limit = 20;

        $form = $this->createForm('App\Form\SearchGenericType', null, [
            'action' => $this->generateUrl('credito_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());
        }

        $creditos = [];
        $reporte = [];
        foreach ($pagination->getItems() as $item) {
            $creditos[] = $item;
            if ($request->query->has('pdf') || $request->query->has('excel')){
                //$item = new Invoice();
                $aux['emision'] = $item->getIssueDate();
                $aux['serie'] = $item->getSerie();
                $aux['numero'] = $item->getNumber();
                $aux['total'] = $item->getGrossAmount();
                $aux['ruc'] = $item->getCustomerIdentification();
                $aux['cliente'] = $item->getCustomerName();
                $aux['estado'] = $item->getEstado();
                $aux['clave'] = $item->getClaveAcceso();
                $aux['fecAutorizacion'] = $item->getFechaAutorizacion();
                $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', $creditos, [
            'action' => $this->generateUrl('credito_index'),
        ]);
        $listForm->handleRequest($request);
        if ($listForm->isSubmitted() && $listForm->isValid()) {
            $data = $listForm->getData();
            if (empty($data['creditos'])) {
                $this->addTranslatedMessage('flash.nothing_selected', 'warning');
            } else {
                if ($request->request->has('delete')) {
                    return $this->bulkDelete($data['creditos']);
                } elseif ($request->request->has('pdf')) {
                    return $this->bulkPdf($data['creditos']);
                } elseif ($request->request->has('print')) {
                    return $this->bulkPrint($data['creditos']);
                } elseif ($request->request->has('email')) {
                    return $this->bulkEmail($data['creditos']);
                }
            }
        }
        return $this->render('Credito\index.html.twig',
            array(
                'creditos' => $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}ncr{id}", name="credito_show")
     *
     */
    public function showAction($id, EmFactory $emFactory, $slug, TranslatorInterface $translator, Request $request)
    {
        $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\Ncredito')->findBySlug($slug, $id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Ncredito 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('credito_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('credito_edit', ['id' => $entity->getId(), 'slug' => $slug]));
            } elseif ($request->request->has('Form-delete')) {
                $error = $this->delete($entity);
                if ($error)
                    return $this->redirect($this->generateUrl('credito_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 credito is open send to the edit form by default.
            return $this->redirect($this->generateUrl('credito_edit', array('id' => $id)));
        }
        */

        return $this->render('Credito\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="credito_add")
     *
     */
    public function newAction(EmFactory $emFactory, Request $request, 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());

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

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

        $credito = new Ncredito();
        $newItem = new Item();

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

        $form = $this->createForm('App\Form\CreditoType', $credito, [
            'action' => $this->generateUrl('credito_add'),
        ]);

        $form->handleRequest($request);

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

            /*if ($credito->getCustomer() == null) {
                $this->addTranslatedMessage('Cliente no se encuentra registrado', 'danger');
            } else {*/
                $serie = $credito->getSeries()->getValue();
                $credito->setSerie($serie);
                $this->cargarImpuestos($credito);
                $credito->setEmpresa($empresa);
                $credito->setUsuario($user->getId());
                $credito->setAmbiente($empresa->getTipoAmbiente());

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

                $credito_id = $credito->getId();

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

                if ($empresa->getEnvioAutomatico()) {

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

                        $error = false;

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

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

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

                    }

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

                }
                return $this->redirect($this->generateUrl('credito_show', ['id' => $credito_id, 'slug' => $credito->getSlug()]));
            //}
        }

        $customer = new Customer();

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

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


    /**
     * @Route("/edit/{slug}ncr{id}", name="credito_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\Ncredito')->findBySlug($slug, $id);
        if (!$entity && $entity->getEmpresa() != $empresa) {
            throw $this->createNotFoundException('Unable to find Ncredito entity.');
        }

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

        $form = $this->createForm('App\Form\CreditoType', $entity, [
            'action' => $this->generateUrl('credito_edit', ['id' => $id, 'slug' => $slug]),
        ]);
        $form->handleRequest($request);

        $entity->setEmpresa($empresa);

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

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

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

            /*
            // See if one of PDF/Print buttons was clicked.
            if ($request->request->has('save_pdf')) {
                $redirectRoute = 'credito_show_pdf';
            } elseif ($request->request->has('save_print')) {
                $this->get('session')->set('credito_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]));
        }

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

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

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

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

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

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

        }
    }

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

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

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

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

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

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

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

        $em = $emFactory->getEm();

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

        $response = $this->getNcreditoTotalsFromPost($post, new Ncredito, $request->getLocale());

        return new JsonResponse($response);
    }

    /**
     * @Route("/pdfpreview/{slug}inv{id}", name="credito_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\Ncredito')->findBySlug($slug, $id);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $filename = 'NC_' . $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').'ncreditoride.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="credito_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(Ncredito::class)->findBySlug($slug, $id);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Credito entity.');
        }

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

        $exportExcel = new ExportCreditosPartnerExcel();

        $titulo = "REPORTE NOTAS CREDITO";

        $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;

    }
}
