<?php

namespace App\Controller;

use App\Entity\WidgetForm;
use App\Entity\WidgetFormInput;
use App\Form\WidgetFormInputType;
use App\Repository\WidgetFormInputRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

/**
 * @IsGranted("ROLE_ADMIN")
 * @Route("/widget/form/input")
 */
class WidgetFormInputController extends AbstractController
{
    /**
     * @param {id} = widgetForm.id
     * @Route("/{id}/new", name="widget_form_input_new", methods={"POST"})
     */
    public function new(WidgetForm $widgetForm, Request $request, $id): Response
    {
        $widgetFormInput = new WidgetFormInput();
        $widgetFormInput->setWidgetForm($widgetForm);
        $form = $this->createForm(WidgetFormInputType::class, $widgetFormInput);
        $form->handleRequest($request);

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

            return $this->redirectToRoute('widget_form_editor', ['id' => $id]);
        }
    }


    /**
     * @Route("/{id}/edit/{formId}", name="widget_form_input_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, WidgetFormInput $widgetFormInput, $formId): Response
    {
        $form = $this->createForm(WidgetFormInputType::class, $widgetFormInput);
        $form->handleRequest($request);

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

            return $this->redirectToRoute('widget_form_editor', ['id' => $formId]);
        }

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

    /**
     * @Route("/{id}/{formId}", name="widget_form_input_delete", methods={"POST"})
     */
    public function delete(Request $request, WidgetFormInput $widgetFormInput, $formId): Response
    {
        if ($this->isCsrfTokenValid('delete'.$widgetFormInput->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($widgetFormInput);
            $entityManager->flush();
        }

        return $this->redirectToRoute('widget_form_editor', ['id' => $formId]);
    }
}
