<?php

namespace App\Controller;

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

/**
 * @Route("/tempresa")
 */
class TempresaController extends AbstractController
{
    /**
     * @Route("/", name="tempresa_index", methods={"GET"})
     */
    public function index(): Response
    {
        $tempresas = $this->getDoctrine()
            ->getRepository(Tempresa::class)
            ->findAll();

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

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

    /**
     * @Route("/new", name="tempresa_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $tempresa = new Tempresa();
        $form = $this->createForm(TempresaType::class, $tempresa);
        $form->handleRequest($request);

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

            $this->addFlash('mensaje', 'Se creó la empresa exitósamente');
            return $this->redirectToRoute('tempresa_index');
        }

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

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

    /**
     * @Route("/{idempresa}/edit", name="tempresa_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Tempresa $tempresa): Response
    {
        $form = $this->createForm(TempresaType::class, $tempresa);
        $form->handleRequest($request);

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

            $this->addFlash('mensaje', 'Se actualizó la empresa exitósamente');
            return $this->redirectToRoute('tempresa_index');
        }

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

//    /**
//     * @Route("/{idempresa}", name="tempresa_delete", methods={"DELETE"})
//     */
//    public function delete(Request $request, Tempresa $tempresa): Response
//    {
//        if ($this->isCsrfTokenValid('delete'.$tempresa->getIdempresa(), $request->request->get('_token'))) {
//            $entityManager = $this->getDoctrine()->getManager();
//            $entityManager->remove($tempresa);
//            $entityManager->flush();
//        }
//
//        return $this->redirectToRoute('tempresa_index');
//    }

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


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

        $message = 'La empresa ha sido eliminada 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="tempresa_delete")
     */
    public function deleteAction(Request $request, Tempresa $tEmpresa)
    {
        $form = $this->createCustomForm($tEmpresa->getIdempresa(), 'DELETE', 'tempresa_delete');
        $form->handleRequest($request);
        $em = $this->getDoctrine()->getManager();

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

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

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

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

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

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

}
