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

use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Form\Type\AddressType;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Class PersonAddressController
 * Controller for addresses associated with person.
 */
class PersonAddressController extends AbstractController
{
    /**
     * PersonAddressController constructor.
     */
    public function __construct(private readonly ValidatorInterface $validator, private readonly TranslatorInterface $translator, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/address/create', name: 'chill_person_address_create', methods: ['POST'])]
    public function createAction(mixed $person_id, Request $request)
    {
        $person = $this->managerRegistry->getManager()
            ->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_UPDATE',
            $person,
            'You are not allowed to edit this person.'
        );

        $address = new Address();

        $form = $this->createCreateForm($person, $address);
        $form->handleRequest($request);

        $person->addAddress($address);

        if ($form->isSubmitted() && $form->isValid()) {
            $validatePersonErrors = $this->validatePerson($person);

            if (0 !== \count($validatePersonErrors)) {
                foreach ($validatePersonErrors as $error) {
                    $this->addFlash('error', $error->getMessage());
                }
            } elseif ($form->isValid()) {
                $em = $this->managerRegistry->getManager();
                $em->flush();

                $this->addFlash(
                    'success',
                    $this->translator->trans('The new address was created successfully')
                );

                return $this->redirectToRoute('chill_person_address_list', [
                    'person_id' => $person->getId(),
                ]);
            } else {
                $this->addFlash('error', $this->translator
                    ->trans('Error! Address not created!'));
            }
        }

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

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/address/{address_id}/edit', name: 'chill_person_address_edit')]
    public function editAction(mixed $person_id, mixed $address_id)
    {
        $person = $this->managerRegistry->getManager()
            ->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_UPDATE',
            $person,
            'You are not allowed to edit this person.'
        );

        $address = $this->findAddressById($person, $address_id);

        $form = $this->createEditForm($person, $address);

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

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/address/list', name: 'chill_person_address_list')]
    public function listAction(mixed $person_id)
    {
        $person = $this->managerRegistry->getManager()
            ->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_SEE',
            $person,
            'You are not allowed to edit this person.'
        );

        return $this->render('@ChillPerson/Address/list.html.twig', [
            'person' => $person,
        ]);
    }

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/address/new', name: 'chill_person_address_new')]
    public function newAction(mixed $person_id)
    {
        $person = $this->managerRegistry->getManager()
            ->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_UPDATE',
            $person,
            'You are not allowed to edit this person.'
        );

        $address = new Address();

        $form = $this->createCreateForm($person, $address);

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

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/address/{address_id}/update', name: 'chill_person_address_update')]
    public function updateAction(mixed $person_id, mixed $address_id, Request $request)
    {
        $person = $this->managerRegistry->getManager()
            ->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_UPDATE',
            $person,
            'You are not allowed to edit this person.'
        );

        $address = $this->findAddressById($person, $address_id);

        $form = $this->createEditForm($person, $address);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $validatePersonErrors = $this->validatePerson($person);

            if (0 !== \count($validatePersonErrors)) {
                foreach ($validatePersonErrors as $error) {
                    $this->addFlash('error', $error->getMessage());
                }
            } elseif ($form->isValid()) {
                $this->managerRegistry->getManager()
                    ->flush();

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

                return $this->redirectToRoute('chill_person_address_list', [
                    'person_id' => $person->getId(),
                ]);
            } else {
                $this->addFlash('error', $this->translator
                    ->trans('Error when updating the period'));
            }
        }

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

    /**
     * @return \Symfony\Component\Form\Form
     */
    protected function createCreateForm(Person $person, Address $address)
    {
        $form = $this->createForm(AddressType::class, $address, [
            'method' => 'POST',
            'action' => $this->generateUrl('chill_person_address_create', [
                'person_id' => $person->getId(),
            ]),
            'has_no_address' => true,
        ]);

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

        return $form;
    }

    /**
     * @return \Symfony\Component\Form\Form
     */
    protected function createEditForm(Person $person, Address $address)
    {
        $form = $this->createForm(AddressType::class, $address, [
            'method' => 'POST',
            'action' => $this->generateUrl('chill_person_address_update', [
                'person_id' => $person->getId(),
                'address_id' => $address->getId(),
            ]),
            'has_no_address' => true,
        ]);

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

        return $form;
    }

    /**
     * @param int $address_id
     *
     * @return Address
     *
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the address id does not exists or is not associated with given person
     */
    protected function findAddressById(Person $person, $address_id)
    {
        $address = $this->managerRegistry->getManager()
            ->getRepository(Address::class)
            ->find($address_id);

        if (!$person->getAddresses()->contains($address)) {
            throw $this->createAccessDeniedException('Not allowed to see this address');
        }

        return $address;
    }

    /**
     * @return \Symfony\Component\Validator\ConstraintViolationListInterface
     */
    private function validatePerson(Person $person)
    {
        $errors = $this->validator
            ->validate($person, null, ['Default']);
        $errors_addresses_consistent = $this->validator
            ->validate($person, null, ['addresses_consistent']);

        foreach ($errors_addresses_consistent as $error) {
            $errors->add($error);
        }

        return $errors;
    }
}
