<?php

namespace App\Controller;

use App\Entity\Collector;
use App\Entity\Collection;
use App\Entity\Bibliography;
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 CollectorController extends AbstractController
{
    #[Route('/collector/{id<\d+>}', name: 'app_collector')]
    public function index(Collector $collector, EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Bibliography::class);
        $bibliographies = $repo->findAllByCollector($collector->getId());
        $collector->setBibliographies($bibliographies);

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

        return $this->render('collector/index.html.twig', [
            'controller_name' => 'CollectorController',
            'record' => $collector,
        ]);
    }

    #[Route('/collector', name: 'app_collector_landing')]
    public function landing(EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Collector::class);
        $records = $repo->findBy([], ['modifiedAt' => 'DESC']);
        $count = count($records);

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

        return $this->render('collector/landing.html.twig', [
            'controller_name' => 'CollectorController',
            'records' => $records,
            'count' => $count,
        ]);
    }

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

        $em->remove($collector);
        $em->flush();

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

        return $this->redirectToRoute('app_collector_landing');
    }
    /**
     * @todo Move clone logic to __clone() in Entity or Repository
     */
    #[Route('/collector/copy/{id<\d+>}', name: 'app_collector_copy')]
    public function copy(Collector $collector, EntityManagerInterface $em): Response
    {
        try {
            $this->denyAccessUnlessGranted(RecordVoter::EDIT, $collector);
        }
        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 $collector;
        $copy->setEditor($editor);
        $copy->setOwner($editor);
        $copy->setCreator($user->getUsername());
        $repo = $em->getRepository(Bibliography::class);
        $copy->setBibliographies(
            $repo->findAllByCollector($collector->getId())
        );
        $copy->setName("{$collector->getName()} - 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_collector', ['id' => $copy->getId()]);
    }
}
