<?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\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Person\ResidentialAddress;
use Chill\PersonBundle\Form\ResidentialAddressType;
use Chill\PersonBundle\Repository\ResidentialAddressRepository;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
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\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final class ResidentialAddressController extends AbstractController
{
    public function __construct(private readonly UrlGeneratorInterface $generator, private readonly TranslatorInterface $translator, private readonly ResidentialAddressRepository $residentialAddressRepository, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    #[Route(path: '/{_locale}/person/residential-address/{id}/delete', name: 'chill_person_residential_address_delete')]
    public function deleteAction(Request $request, ResidentialAddress $residentialAddress): Response
    {
        $this->denyAccessUnlessGranted(PersonVoter::UPDATE, $residentialAddress->getPerson());

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

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

            $this->addFlash('success', $this->translator->trans('Residential address had been deleted'));

            return $this->redirectToRoute('chill_person_residential_address_list', ['id' => $residentialAddress->getPerson()->getId()]);
        }

        return $this->render('@ChillPerson/ResidentialAddress/delete.html.twig', [
            'person' => $residentialAddress->getPerson(),
            'residentialAddress' => $residentialAddress,
            'delete_form' => $form->createView(),
        ]);
    }

    #[Route(path: '/{_locale}/person/residential-address/{id}/edit', name: 'chill_person_residential_address_edit')]
    public function editAction(Request $request, ResidentialAddress $residentialAddress): Response
    {
        if ($request->query->has('kind')) {
            $kind = $request->query->getAlpha('kind', '');
        } else {
            $kind = null;
        }

        $person = $residentialAddress->getPerson();
        $this->denyAccessUnlessGranted(PersonVoter::UPDATE, $person);

        $form = $this->createForm(ResidentialAddressType::class, $residentialAddress, ['kind' => $kind]);
        $form->handleRequest($request);

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

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

            return $this->redirect(
                $request->get('returnPath', null) ??
                $this->generator->generate('chill_person_residential_address_list', ['id' => $person->getId()])
            );
        }

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

    #[Route(path: '/{_locale}/person/{id}/residential-address/list', name: 'chill_person_residential_address_list')]
    public function listAction(Request $request, Person $person): Response
    {
        $this->denyAccessUnlessGranted(PersonVoter::SEE, $person);

        $residentialAddresses = $this->residentialAddressRepository->findBy(['person' => $person], ['startDate' => 'DESC']);

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

    #[Route(path: '/{_locale}/person/{id}/residential-address/new', name: 'chill_person_residential_address_new')]
    public function newAction(Request $request, Person $person): Response
    {
        $residentialAddress = new ResidentialAddress();
        $residentialAddress->setPerson($person);

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

        if (!$request->query->has('kind')) {
            return $this->render('@ChillPerson/ResidentialAddress/new_pick_kind.html.twig', ['person' => $person]);
        }
        $kind = $request->query->getAlpha('kind', '');

        $form = $this->createForm(ResidentialAddressType::class, $residentialAddress, ['kind' => $kind]);
        $form->handleRequest($request);

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

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

            return $this->redirect(
                $request->get('returnPath', null) ??
                $this->generator->generate('chill_person_residential_address_list', ['id' => $residentialAddress->getPerson()->getId()])
            );
        }

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