<?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\DocStoreBundle\Controller;

use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\DocStoreBundle\Form\PersonDocumentType;
use Chill\DocStoreBundle\Security\Authorization\PersonDocumentVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use Chill\DocStoreBundle\Service\Signature\PDFSignatureZoneParser;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;

/**
 * Class DocumentPersonController.
 */
#[Route(path: '/{_locale}/person/{person}/document')] // TODO faire un controller abstrait ?
class DocumentPersonController extends AbstractController
{
    /**
     * DocumentPersonController constructor.
     */
    public function __construct(
        protected TranslatorInterface $translator,
        protected EventDispatcherInterface $eventDispatcher,
        protected AuthorizationHelper $authorizationHelper,
        protected PDFSignatureZoneParser $PDFSignatureZoneParser,
        protected StoredObjectManagerInterface $storedObjectManagerInterface,
        private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry,
    ) {}

    #[Route(path: '/{id}/delete', name: 'chill_docstore_person_document_delete')]
    public function delete(Request $request, Person $person, PersonDocument $document): Response
    {
        $this->denyAccessUnlessGranted(PersonDocumentVoter::DELETE, $document);

        $form = $this->createForm(FormType::class);
        $form->add('submit', SubmitType::class, ['label' => 'Delete']);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->managerRegistry->getManager()->remove($document);
            $this->managerRegistry->getManager()->flush();

            $this->addFlash('success', $this->translator->trans('The document is successfully removed'));

            if ($request->query->has('returnPath')) {
                return $this->redirect($request->query->get('returnPath'));
            }

            return $this->redirectToRoute('chill_docstore_generic-doc_by-person_index', ['id' => $person->getId()]);
        }

        return $this->render(
            '@ChillDocStore/PersonDocument/delete.html.twig',
            [
                'document' => $document,
                'delete_form' => $form->createView(),
                'person' => $person,
            ]
        );
    }

    #[Route(path: '/{id}/edit', name: 'person_document_edit', methods: 'GET|POST')]
    public function edit(Request $request, Person $person, PersonDocument $document): Response
    {
        $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person);
        $this->denyAccessUnlessGranted('CHILL_PERSON_DOCUMENT_UPDATE', $document);

        $document->setUser($this->getUser());
        $document->setDate(new \DateTime('Now'));

        $form = $this->createForm(
            PersonDocumentType::class,
            $document,
            [
                'role' => 'CHILL_PERSON_DOCUMENT_UPDATE',
            ]
        );
        $form->handleRequest($request);

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

            $this->addFlash('success', $this->translator->trans('The document is successfully updated'));

            $event = new PrivacyEvent($person, [
                'element_class' => PersonDocument::class,
                'element_id' => $document->getId(),
                'action' => 'update',
            ]);
            $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

            return $this->redirectToRoute(
                'person_document_edit',
                ['id' => $document->getId(), 'person' => $person->getId()]
            );
        }

        if ($form->isSubmitted() && !$form->isValid()) {
            $this->addFlash('error', $this->translator->trans('This form contains errors'));
        }

        $event = new PrivacyEvent($person, [
            'element_class' => PersonDocument::class,
            'element_id' => $document->getId(),
            'action' => 'edit',
        ]);
        $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

        return $this->render(
            '@ChillDocStore/PersonDocument/edit.html.twig',
            [
                'document' => $document,
                'form' => $form->createView(),
                'person' => $person,
            ]
        );
    }

    #[Route(path: '/new', name: 'person_document_new', methods: 'GET|POST')]
    public function new(Request $request, Person $person): Response
    {
        if (null === $person) {
            throw $this->createNotFoundException('person not found');
        }

        $this->denyAccessUnlessGranted(PersonVoter::SEE, $person);

        $document = new PersonDocument();
        $document->setUser($this->getUser());
        $document->setPerson($person);
        $document->setDate(new \DateTime('Now'));

        $form = $this->createForm(PersonDocumentType::class, $document, [
            'role' => 'CHILL_PERSON_DOCUMENT_CREATE',
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->denyAccessUnlessGranted(
                'CHILL_PERSON_DOCUMENT_CREATE',
                $document,
                'creation of this activity not allowed'
            );

            $em = $this->managerRegistry->getManager();
            $em->persist($document);
            $em->flush();

            $this->addFlash('success', $this->translator->trans('The document is successfully registered'));

            return $this->redirectToRoute('chill_docstore_generic-doc_by-person_index', ['id' => $person->getId()]);
        }

        if ($form->isSubmitted() && !$form->isValid()) {
            $this->addFlash('error', $this->translator->trans('This form contains errors'));
        }

        return $this->render('@ChillDocStore/PersonDocument/new.html.twig', [
            'document' => $document,
            'form' => $form->createView(),
            'person' => $person,
        ]);
    }

    #[Route(path: '/{id}', name: 'person_document_show', methods: 'GET')]
    public function show(Person $person, PersonDocument $document): Response
    {
        $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person);
        $this->denyAccessUnlessGranted('CHILL_PERSON_DOCUMENT_SEE', $document);

        $event = new PrivacyEvent($person, [
            'element_class' => PersonDocument::class,
            'element_id' => $document->getId(),
            'action' => 'show',
        ]);
        $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

        return $this->render(
            '@ChillDocStore/PersonDocument/show.html.twig',
            ['document' => $document, 'person' => $person]
        );
    }
}
