<?php

namespace App\Controller;

use App\Entity\Torigen;
use App\Form\TorigenType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/torigen")
 */
class TorigenController extends AbstractController
{
    /**
     * @Route("/", name="torigen_index", methods={"GET"})
     */
    public function index(): Response
    {
        $torigens = $this->getDoctrine()
            ->getRepository(Torigen::class)
            ->findAll();

        $deleteFormAjax = $this->createCustomForm(':USER_ID', 'DELETE', 'torigen_delete');

        return $this->render('torigen/index.html.twig', [
            'torigens' => $torigens,
            'delete_form_ajax' => $deleteFormAjax->createView()
        ]);
    }

    /**
     * @Route("/new", name="torigen_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $torigen = new Torigen();
        $form = $this->createForm(TorigenType::class, $torigen);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($torigen);
            $entityManager->flush();

            $this->addFlash('mensaje', 'Se creó el origen exitósamente');
            return $this->redirectToRoute('torigen_index');
        }

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

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

    /**
     * @Route("/{idorigen}/edit", name="torigen_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Torigen $torigen): Response
    {
        $form = $this->createForm(TorigenType::class, $torigen);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            $this->addFlash('mensaje', 'Se actualizó el origen exitósamente');
            return $this->redirectToRoute('torigen_index');
        }

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

//    /**
//     * @Route("/{idorigen}", name="torigen_delete", methods={"DELETE"})
//     */
//    public function delete(Request $request, Torigen $torigen): Response
//    {
//        if ($this->isCsrfTokenValid('delete'.$torigen->getIdorigen(), $request->request->get('_token'))) {
//            $entityManager = $this->getDoctrine()->getManager();
//            $entityManager->remove($torigen);
//            $entityManager->flush();
//        }
//
//        return $this->redirectToRoute('torigen_index');
//    }


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


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

            $message = 'El origen de salida 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="torigen_delete")
     */
    public function deleteAction(Request $request, Torigen $tOrigen)
    {
        $form = $this->createCustomForm($tOrigen->getIdorigen(), 'DELETE', 'torigen_delete');
        $form->handleRequest($request);
        $em = $this->getDoctrine()->getManager();

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

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

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

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

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

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

}
