<?php

namespace App\Controller;

use App\Entity\Collection;
use App\Security\Voter\RecordVoter;
use App\Entity\ConservationPlace;
use App\RecordStatus;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ConservationPlaceController extends AbstractController
{
    #[Route('/conservation_place', name: 'app_conservation_place')]
    public function index(EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(ConservationPlace::class);
        $records = $repo->findBy([], ['id' => 'DESC']);
        $count = count($records);

        $records = array_slice($records, 0, 15);

        return $this->render('conservation_place/index.html.twig', [
            'controller_name' => 'ConservationPlaceController',
            'records' => $records,
            'count' => $count,
        ]);
    }

    #[Route('/conservation_place/{id<\d+>}', name: 'app_conservation_place_view')]
    public function view(ConservationPlace $conservationPlace, EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(ConservationPlace::class);

        $coords = $repo->coordinates($conservationPlace->getId());

        $conservationPlace->setLat((float) $coords['lat']);
        $conservationPlace->setLng((float) $coords['lng']);

        return $this->render('conservation_place/view.html.twig', [
            'controller_name' => 'ConservationPlaceController',
            'record' => $conservationPlace,
        ]);
    }

    #[Route('/conservation_place/delete/{id<\d+>}', name: 'app_conservation_place_del')]
    public function delete(ConservationPlace $conservationPlace, EntityManagerInterface $em): Response
    {
        try {
            $this->denyAccessUnlessGranted(RecordVoter::DELETE, $conservationPlace);
        }
        catch (AccessDeniedException) {
            $this->addFlash('warning', 'You are not authorized to delete this record');
            return $this->redirectToRoute('app_home');
        }

        if ($conservationPlace) {
            $em->remove($conservationPlace);
            $em->flush();
        }

        $this->addFlash('notice', 'Record deleted successfully');

        return $this->redirectToRoute('app_conservation_place');
    }
    /**
     * @todo Move clone logic to __clone() in Entity or Repository
     */
    #[Route('/conservation_place/copy/{id<\d+>}', name: 'app_conservation_place_copy')]
    public function copy(ConservationPlace $conservationPlace, EntityManagerInterface $em): Response
    {
        try {
            $this->denyAccessUnlessGranted(RecordVoter::EDIT, $conservationPlace);
        }
        catch (AccessDeniedException) {
            $this->addFlash('warning', 'You are not authorized to copy this record');
            return $this->redirectToRoute('app_home');
        }

        $user = $this->getUser();
        $editor = "{$user->getFirstname()} {$user->getLastName()}"; 

        $copy = clone $conservationPlace;
        $copy->setEditor($editor);
        $copy->setOwner($editor);
        $copy->setCreator($user->getUsername());
        $repo = $em->getRepository(Collection::class);
        $copy->setCollections(
            $repo->findAllByConservationPlace($conservationPlace->getId())
        );
        /*
        $repo = $em->getRepository(Collector::class);
        $copy->setCollectors(
            $repo->findAllByBibliography($bibliography->getId())
        );
        */
        $copy->setPlace("{$conservationPlace->getPlace()} - Copy");
        $copy->setModifiedAt(new \DateTimeImmutable());
        $copy->setStatus(RecordStatus::Draft->value);

        $em->persist($copy);
        $em->flush();

        $this->addFlash('notice', 'Record copied successfully');

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