<?php

namespace App\Controller;

use App\Entity\Document;
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 DocumentController extends AbstractController
{
    #[Route('/document', name: 'app_document')]
    public function index(EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Document::class);
        $records = $repo->findBy([], ['modifiedAt' => 'DESC']);
        $count = count($records);

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

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

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

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

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

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

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

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

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