<?php

namespace App\Controller;

use App\Entity\Testado;
use App\Entity\Tnacional;
use App\Form\Tnacional_adjuntaType;
use App\Form\TnacionaleditType;
use App\Form\TnacionalType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


/**
 * @Route("/tnacional")
 */
class TnacionalController extends AbstractController
{
    /**
     * @Route("/", name="tnacional_index", methods={"GET"})
     */
    public function index(): Response
    {
        $em = $this->getDoctrine()->getManager();
        $tnacionals = $em->getRepository('App:Tusuario')->getRegNal();
//        var_dump($tnacionals); exit();
        date_default_timezone_set('America/La_Paz');
        $indice = 0;
        $habilitaEdicion = array();

        foreach ($tnacionals as $tNal) {
            $fechaComprobar = strtotime($tNal['Hoy']);
            $fecha1 = strtotime($tNal['fechainicio']->format('Y-m-d H:i:s'));
            $fecha2  = strtotime ( '+20 minute' , strtotime($tNal['fechainicio']->format('Y-m-d H:i:s')) ) ;
//                    var_dump($fecha1. ' - ' . $fecha2); exit();
//                    var_dump(date("d/m/Y h:i:s",$fecha1). ' - ' . date("d/m/Y h:i:s",$fecha2)); exit();

            if ($fechaComprobar >= $fecha1 and $fechaComprobar <= $fecha2)
                $habilitaEdicion[$indice] = true;
            else
                $habilitaEdicion[$indice] = false;

            $indice = $indice + 1;
        }

        $deleteFormAjax = $this->createCustomForm(':USER_ID', 'DELETE', 'tnacional_delete');
        
        return $this->render('tnacional/index.html.twig', [
            'tnacionals' => $tnacionals,
            'habilitaEdicion' => $habilitaEdicion,
            'delete_form_ajax' => $deleteFormAjax->createView()
        ]);
    }

    /**
     * @Route("/new", name="tnacional_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $usuario = $this->getUser();
//        var_dump($usuario->getUsername());

        $tnacional = new Tnacional();
        $form = $this->createForm(TnacionalType::class, $tnacional);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
//            var_dump($em->getRepository( Testado::class )->findBy( [ 'idestado' => 1] )[0]); exit();
            $tnacional->setIdestado($em->getRepository( Testado::class )->findBy( [ 'idestado' => 1] )[0] );

            date_default_timezone_set('America/La_Paz');
            $fecha = new \DateTime("now");

            $tnacional->setAuditoria($fecha->format('d-m-Y H:i') . '; '. $usuario->getUsername(). '; Nuevo Trans. Nal. ');
//            $tnacional->setFechainicio($fecha);

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

            $this->addFlash('mensaje', 'Se creó la instancia del transporte nacional exitósamente');
            return $this->redirectToRoute('tnacional_index');
        }

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

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

    /**
     * @Route("/{idnacional}/edit", name="tnacional_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Tnacional $tnacional): Response
    {
        $usuario = $this->getUser();
        $form = $this->createForm(TnacionaleditType::class, $tnacional);
        $form->handleRequest($request);

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

            $tnacional->setAuditoria($fecha->format('d-m-Y H:i') . '; '. $usuario->getUsername(). '; Edita Trans. Nal. ');

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

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

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


//    /**
//     * @Route("/{idnacional}", name="tnacional_delete", methods={"DELETE"})
//     */
//    public function delete(Request $request, Tnacional $tnacional): Response
//    {
//        if ($this->isCsrfTokenValid('delete'.$tnacional->getIdnacional(), $request->request->get('_token'))) {
//            $entityManager = $this->getDoctrine()->getManager();
//            $entityManager->remove($tnacional);
//            $entityManager->flush();
//        }
//
//        return $this->redirectToRoute('tnacional_index');
//    }



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


    private function deleteRegistro($em, $tNacional)
    {
        $em->remove($tNacional);
        $em->flush();

        $message = 'El registro de transporte nacional ha sido eliminado exitósamente';
        //$this->get('session')->getFlashBag()->add('message', 'Se eliminó el registro exitosamente');
        $removed = 1;
        $alert = 'mensaje';

        return array('removed'=>$removed, 'message'=>$message, 'alert'=>$alert);
    }


    /**
     * @Route("/delete/{id}", name="tnacional_delete")
     */
    public function deleteAction(Request $request, Tnacional $tNacional)
    {
        $form = $this->createCustomForm($tNacional->getIdnacional(), 'DELETE', 'tnacional_delete');
        $form->handleRequest($request);
        $em = $this->getDoctrine()->getManager();

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

            if($request->isXMLHttpRequest())
            {
                $res = $this->deleteRegistro($em, $tNacional);

                return new Response(
                    json_encode(array('removed'=>$res['removed'], 'message'=>$res['message'], )),
                    200,
                    array('Content-Type'=>'application/json')
                );
            }

            $res = $this->deleteRegistro($em, $tNacional);

            $this->addFlash($res['alert'], $res['message']);

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

}
