<?php

namespace App\Controller\FrontEnd;

use App\Entity\Tag;

use Doctrine\ORM\EntityManagerInterface;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class TagController extends AbstractController
{
    #[Route('/tags', name: 'front_end_tag_list', priority: 1)]
    public function index(EntityManagerInterface $entityManager): Response
    {
        $tags = $entityManager->getRepository(Tag::class)->findAll();

        $tagsDisplay = [];

        foreach ($tags as $index => $tag) {
            $tagsDisplay[] = [
                'title' => $tag->getTitle(),
                'urlSafeTitle' => strtolower(str_replace(' ', '-', $tag->getTitle())),
                'count' => $tag->getCount(),
            ];
        }

        return $this->render('front/tag/index.html.twig', [
            'tags' => $tagsDisplay
        ]);
    }
    
    #[Route('/tags/{tagTitle}', name: 'front_end_tag_detail')]
    public function detail(EntityManagerInterface $entityManager, string $tagTitle): Response
    {   
        $formattedTitle = ucwords(str_replace('-', ' ', $tagTitle));
        $tag = $entityManager->getRepository(tag::class)->findOneBy(['title' => $formattedTitle]);
        
        return $this->render('front/tag/detail.html.twig', [
            'title' => $tag->getTitle(),
            'posts' => $tag->getPosts(),
            'photos' => $tag->getPhotos(),
            'count' => $tag->getCount()
        ]);
    }
}
