<?php

namespace App\Controller;

use App\Entity\Tfactnal;
use App\Entity\Tnacional;
use App\Entity\Tusuario;
use App\Form\TfactnalcobraType;
use App\Form\TfactnalType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/tfactnal")
 */
class TfactnalController extends AbstractController
{
    /**
     * @Route("/tncobrar", name="tfactnal_cobrar", methods={"GET"})
     */
    public function cobrar(): Response
    {
        $em = $this->getDoctrine()->getManager();
        $tfactnals = $em->getRepository('App:Tusuario')->getFactCobrarNal();

        return $this->render('tfactnal/indexCobrar.html.twig', [
            'tfactnals' => $tfactnals,
        ]);
    }

    /**
     * @Route("/tnpagados", name="tfactnal_pagados", methods={"GET"})
     */
    public function pagados(): Response
    {
        $em = $this->getDoctrine()->getManager();
        $tfactnals = $em->getRepository('App:Tusuario')->getFactPagadoNal();

        return $this->render('tfactnal/indexPagado.html.twig', [
            'tfactnals' => $tfactnals,
        ]);
    }


    /**
     * @Route("/tnpagar", name="tnal_pagar", methods={"GET"})
     */
    public function xpagar(): Response
    {
        $em = $this->getDoctrine()->getManager();
        $tfactnals = $em->getRepository('App:Tusuario')->getTransxPagarNal();

        return $this->render('tnacional/indexPagar.html.twig', [
            'tfactnals' => $tfactnals,
        ]);
    }

    /**
     * @Route("/tncumplido", name="tnal_pagado", methods={"GET"})
     */
    public function tnal_pagado(): Response
    {
        $em = $this->getDoctrine()->getManager();
        $tfactnals = $em->getRepository('App:Tusuario')->getTransportistasPagadosNal();

        return $this->render('tnacional/indexPagados.html.twig', [
            'tfactnals' => $tfactnals,
        ]);
    }

    /**
     * @Route("/new/{idnacional}", name="tfactnal_new", methods={"GET","POST"})
     */
    public function new(Request $request, $idnacional): Response
    {
        $tfactnal = new Tfactnal();
        $form = $this->createForm(TfactnalType::class, $tfactnal);
        $form->handleRequest($request);

        $em = $this->getDoctrine()->getManager();
        $tFacturas = $em->getRepository( Tfactnal::class )->findBy( ['idnacional' => $idnacional] );

        $tNacional = $this->getDoctrine()->getRepository(Tnacional::class)->findOneBy(array('idnacional'=>$idnacional));

        if ($form->isSubmitted() && $form->isValid()) {
            date_default_timezone_set('America/La_Paz');
            $fecha = new \DateTime("now");

            $usuario = $this->getUser();
//            var_dump($usuario); exit();

            $tfactnal->setIdnacional($em->getRepository( Tnacional::class )->findBy( ['idnacional' => $idnacional] )[0] );
            $tfactnal->setIdusuario($em->getRepository( Tusuario::class )->findBy( ['idusuario' => $usuario->getIdusuario()] )[0] );
            $tfactnal->setAuditoria($tfactnal->getAuditoria() . '|' . $fecha->format('d-m-Y H:i') . '; '. $usuario->getUsername(). '; Nueva Fact. Nal. ');


            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($tfactnal);
            $entityManager->flush();

            $this->addFlash('mensaje', 'Se generó la factura exitósamente');
            return $this->redirectToRoute('tnacional_index');
        }

        return $this->render('tfactnal/new.html.twig', [
            'tfactnal' => $tfactnal,
            'tFacturas' => $tFacturas,
            'tNacional'=>$tNacional,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{idfactnal}/show", name="tfactnal_show", methods={"GET"})
     */
    public function show(Tfactnal $tfactnal): Response
    {
        return $this->render('tfactnal/show.html.twig', [
            'tfactnal' => $tfactnal,
        ]);
    }

    /**
     * @Route("/{idfactnal}/edit", name="tfactnal_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Tfactnal $tfactnal): Response
    {
        $form = $this->createForm(TfactnalcobraType::class, $tfactnal);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            date_default_timezone_set('America/La_Paz');
            $fecha = new \DateTime("now");

            $em = $this->getDoctrine()->getManager();
            $usuario = $this->getUser();
            $tfactnal->setIdusuario($em->getRepository( Tusuario::class )->findBy( ['idusuario' => $usuario->getIdusuario()] )[0] );
            $tfactnal->setAuditoria($tfactnal->getAuditoria() . '|' . $fecha->format('d-m-Y H:i') . '; '. $usuario->getUsername(). '; Edita Fact. Nal. ');
            $this->getDoctrine()->getManager()->flush();

            $this->addFlash('mensaje', 'Se editó la factura exitósamente');
            return $this->redirectToRoute('tnacional_index');
        }

        return $this->render('tfactnal/edit.html.twig', [
            'tfactnal' => $tfactnal,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{idfactnal}/cobra", name="tfactnal_cobra", methods={"GET","POST"})
     */
    public function cobra(Request $request, Tfactnal $tfactnal): Response
    {
        $miObservacion = $tfactnal->getObservacion() . ' | ';
        $tfactnal->setObservacion('');

        $form = $this->createForm(TfactnalcobraType::class, $tfactnal);
        $form->handleRequest($request);
        $em = $this->getDoctrine()->getManager();

        if ($form->isSubmitted() && $form->isValid()) {
            $miMensaje1='';
            $miMensaje2='';

            if($form['fpagofact']->getData() <> '' and $form['idpago']->getData() <> '') {
                date_default_timezone_set('America/La_Paz');
                $fecha = new \DateTime("now");

                $usuario = $this->getUser();
                $tfactnal->setIdusuario($em->getRepository(Tusuario::class)->findBy(['idusuario' => $usuario->getIdusuario()])[0]);
                $tfactnal->setAuditoria($tfactnal->getAuditoria() . '|' . $fecha->format('d-m-Y H:i') . '; ' . $usuario->getUsername() . '; Cobra Fact. Nal. ');
                $tfactnal->setObservacion($miObservacion . $tfactnal->getObservacion());

                $this->getDoctrine()->getManager()->flush();

                $this->addFlash('mensaje', 'Se realizó el cobro de la factura exitósamente');
                return $this->redirectToRoute('tnacional_index');
            }
            else
            {
                if ( $form['fpagofact']->getData() == '' ) {
                    $miMensaje1 = 'Debe Colocar la fecha de cobro de la factura';
                    return $this->render('tfactnal/cobrar.html.twig', [
                        'tfactnal' => $tfactnal,
                        'mimensaje1' => $miMensaje1,
                        'form' => $form->createView(),
                    ]);
                }

                if ( $form['idpago']->getData() == '' ) {
                    $miMensaje2 = 'Debe Colocar la forma de pago de la factura';
                    return $this->render('tfactnal/cobrar.html.twig', [
                        'tfactnal' => $tfactnal,
                        'mimensaje2' => $miMensaje2,
                        'form' => $form->createView(),
                    ]);
                }
            }
        }

        return $this->render('tfactnal/cobrar.html.twig', [
            'tfactnal' => $tfactnal,
            'form' => $form->createView(),
        ]);
    }


    /**
     * @Route("/{idfactnal}", name="tfactnal_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Tfactnal $tfactnal): Response
    {
        if ($this->isCsrfTokenValid('delete'.$tfactnal->getIdfactnal(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($tfactnal);
            $entityManager->flush();
        }

        return $this->redirectToRoute('tfactnal_index');
    }

//    private function createCustomForm($id, $method, $route)
//    {
//        return $this->createFormBuilder()
//            ->setAction($this->generateUrl($route, array('id'=>$id)))
//            ->setMethod($method)
//            ->getForm();
//    }


    /**
     * @Route("/{idfactnal}/borraf", name="tfactnal_borrar", methods={"GET","POST"})
     */
    public function borrarFactura($idfactnal)
    {
        try {
            $em = $this->getDoctrine()->getManager();
            $em->getRepository('App:Tusuario')->borraFacturaNal($idfactnal);

            $this->addFlash('mensaje', 'La factura emitida del transporte nacional ha sido eliminado exitósamente');
            return $this->redirectToRoute('tnacional_index');
        }catch(\Doctrine\DBAL\DBALException $e) {
            $this->get('session')->getFlashBag()->add('mensaje-danger', 'LA FACTURA EMITIDA NO SE PUEDE BORRAR');
            return $this->redirectToRoute('tnacional_index');
        }
    }

}
