<?php

namespace App\Controller;

use App\Entity\Collection;
use App\Entity\Bibliography;
use App\Entity\Collector;
use App\RecordStatus;
use App\Security\Voter\RecordVoter;
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 CollectionController extends AbstractController
{
    #[Route('/collection', name: 'app_collection')]
    public function index(EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Collection::class);
        $records = $repo->findBy([], ['modifiedAt' => 'DESC']);
        $count = count($records);

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

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

    #[Route('/collection/{id<\d+>}', name: 'app_collection_view')]
    public function view(Collection $collection, EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Bibliography::class);
        $bibliographies = $repo->findAllByCollection($collection->getId());
        $collection->setBibliographies($bibliographies);

        $repo = $em->getRepository(Collection::class);
        $isEditable = $repo->hasCreatorEditor($collection->getCreator());
        $collection->setEditableStatus($isEditable);

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

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

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

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

        return $this->redirectToRoute('app_collection');
    }
    /**
     * @todo Move clone logic to __clone() in Entity or Repository
     */
    #[Route('/collection/copy/{id<\d+>}', name: 'app_collection_copy')]
    public function copy(Collection $collection, EntityManagerInterface $em): Response
    {
        try {
            $this->denyAccessUnlessGranted(RecordVoter::EDIT, $collection);
        }
        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 $collection;
        $copy->setEditor($editor);
        $copy->setOwner($editor);
        $copy->setCreator($user->getUsername());
        $repo = $em->getRepository(Bibliography::class);
        $copy->setBibliographies(
            $repo->findAllByCollection($collection->getId())
        );
        /*
        $repo = $em->getRepository(Collector::class);
        $copy->setCollectors(
            $repo->findAllByBibliography($bibliography->getId())
        );
        */
        $copy->setTitle("{$collection->getTitle()} - 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_collection_view', ['id' => $copy->getId()]);
    }
}
