<?php

namespace App\Controller;

use App\Entity\Bibliography;
use App\Entity\Collection;
use App\Entity\Collector;
use App\Form\BibliographyType;
use App\Security\Voter\RecordVoter;
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;
use DateTimeImmutable;

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

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

        return $this->render('bibliography/index.html.twig', [
            'controller_name' => 'BibliographyController',
            'records' => $records,
            'count' => $count,
        ]);
    }
    
    #[Route('/bibliography/{id<\d+>}', name: 'app_bibliography_view')]
    public function view(Bibliography $bibliography, EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Collection::class);
        $collections = $repo->findAllByBibliography($bibliography->getId());
        $repo = $em->getRepository(Collector::class);
        $collectors = $repo->findAllByBibliography($bibliography->getId());

        $bibliography->setCollections($collections);
        $bibliography->setCollectors($collectors);

        $repo = $em->getRepository(Bibliography::class);
        $isEditable = $repo->hasCreatorEditor($bibliography->getCreator());

        $bibliography->setEditableStatus($isEditable);

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

    #[Route('/bibliography/search', name: 'app_bibliography_search')]
    public function search(): Response
    {
        return $this->render('bibliography/search.html.twig', [
            'controller_name' => 'BibliographyController',
        ]);
    }
    
    /**
     * @todo Permissions with voter
     */
    #[Route('/bibliography/add', name: 'app_bibliography_create')]
    public function add(): Response
    {
        $form = $this->createForm(BibliographyType::class);

        return $this->render('bibliography/create.html.twig', [
            'controller_name' => 'BibliographyController',
            'form' => $form,
        ]);
    }
    /**
     * @todo Permissions! Return JSON with 403 when AJAX
     */
    #[Route('/bibliography/delete/{id<\d+>}', name: 'app_bibliography_del')]
    public function delete(Bibliography $bibliography, EntityManagerInterface $em): Response
    {
        try {
            $this->denyAccessUnlessGranted(RecordVoter::DELETE, $bibliography);
        }
        catch (AccessDeniedException) {
            $this->addFlash('warning', 'You are not authorized to delete this record');
            return $this->redirectToRoute('app_home');
        }

        if ($bibliography) {
            $em->remove($bibliography);
            $em->flush();
            $this->addFlash('notice', 'Record deleted successfully');
        }

        return $this->redirectToRoute('app_bibliography');
    }

    /**
     * @todo Move clone logic to __clone() in Entity or Repository
     */
    #[Route('/bibliography/copy/{id<\d+>}', name: 'app_bibliography_copy')]
    public function copy(Bibliography $bibliography, EntityManagerInterface $em): Response
    {
        try {
            $this->denyAccessUnlessGranted(RecordVoter::COPY, $bibliography);
        }
        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 $bibliography;
        $copy->setEditor($editor);
        $copy->setOwner($editor);
        $copy->setCreator($user->getUsername());
        $repo = $em->getRepository(Collection::class);
        $copy->setCollections(
            $repo->findAllByBibliography($bibliography->getId())
        );
        $repo = $em->getRepository(Collector::class);
        $copy->setCollectors(
            $repo->findAllByBibliography($bibliography->getId())
        );
        $copy->setCitation("{$bibliography->getCitation()} - 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_bibliography_view', ['id' => $copy->getId()]);
    }
}
