<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CustomFieldsBundle\Controller;

use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Chill\CustomFieldsBundle\Form\CustomFieldType;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Class CustomFieldController.
 */
class CustomFieldController extends AbstractController
{
    public function __construct(
        private readonly TranslatorInterface $translator,
        private readonly ManagerRegistry $managerRegistry,
    ) {}

    /**
     * Creates a new CustomField entity.
     */
    #[Route(path: '/{_locale}/admin/customfield/new', name: 'customfield_create')]
    public function createAction(Request $request)
    {
        $entity = new CustomField();
        $form = $this->createCreateForm($entity, $request->query->get('type', null));
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->managerRegistry->getManager();
            $em->persist($entity);
            $em->flush();

            $this->addFlash('success', $this->translator
                ->trans('The custom field has been created'));

            return $this->redirectToRoute('customfieldsgroup_show', ['id' => $entity->getCustomFieldsGroup()->getId()]);
        }

        $this->addFlash('error', $this->translator
            ->trans('The custom field form contains errors'));

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

    /**
     * Displays a form to edit an existing CustomField entity.
     */
    #[Route(path: '/{_locale}/admin/customfield/edit', name: 'customfield_edit')]
    public function editAction(mixed $id)
    {
        $em = $this->managerRegistry->getManager();

        $entity = $em->getRepository(CustomField::class)->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomField entity.');
        }

        $editForm = $this->createEditForm($entity, $entity->getType());

        return $this->render('@ChillCustomFields/CustomField/edit.html.twig', [
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
        ]);
    }

    /**
     * Displays a form to create a new CustomField entity.
     */
    #[Route(path: '/{_locale}/admin/customfield/new', name: 'customfield_new')]
    public function newAction(Request $request)
    {
        $entity = new CustomField();

        // add the custom field group if defined in URL
        $cfGroupId = $request->query->get('customFieldsGroup', null);

        if (null !== $cfGroupId) {
            $cfGroup = $this->managerRegistry->getManager()
                ->getRepository(CustomFieldsGroup::class)
                ->find($cfGroupId);

            if (!$cfGroup) {
                throw $this->createNotFoundException('CustomFieldsGroup with id '.$cfGroupId.' is not found !');
            }
            $entity->setCustomFieldsGroup($cfGroup);
        }

        $form = $this->createCreateForm($entity, $request->query->get('type'));

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

    /**
     * Edits an existing CustomField entity.
     */
    #[Route(path: '/{_locale}/admin/customfield/update', name: 'customfield_update')]
    public function updateAction(Request $request, mixed $id)
    {
        $em = $this->managerRegistry->getManager();

        $entity = $em->getRepository(CustomField::class)->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CustomField entity.');
        }

        $editForm = $this->createEditForm($entity, $entity->getType());
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em->flush();

            $this->addFlash('success', $this->translator
                ->trans('The custom field has been updated'));

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

        $this->addFlash('error', $this->translator
            ->trans('The custom field form contains errors'));

        return $this->render('@ChillCustomFields/CustomField/edit.html.twig', [
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
        ]);
    }

    /**
     * Creates a form to create a CustomField entity.
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(CustomField $entity, mixed $type)
    {
        $form = $this->createForm(CustomFieldType::class, $entity, [
            'action' => $this->generateUrl(
                'customfield_create',
                ['type' => $type]
            ),
            'method' => 'POST',
            'type' => $type,
            'group_widget' => ($entity->getCustomFieldsGroup()) ? 'hidden' : 'entity',
        ]);

        $form->add('submit', SubmitType::class, ['label' => 'Create']);

        return $form;
    }

    /**
     * Creates a form to edit a CustomField entity.
     *
     * @param CustomField $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(CustomField $entity, mixed $type)
    {
        $form = $this->createForm(CustomFieldType::class, $entity, [
            'action' => $this->generateUrl('customfield_update', ['id' => $entity->getId()]),
            'method' => 'PUT',
            'type' => $type,
            'group_widget' => 'hidden',
        ]);

        $form->add('submit', SubmitType::class, ['label' => 'Update']);

        return $form;
    }
}
