<?php

namespace App\Controller\FrontEnd;

use App\Entity\Category;

use Doctrine\ORM\EntityManagerInterface;

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

final class CategoryController extends AbstractController
{
    #[Route('/categories', name: 'front_end_category_list', priority: 1)]
    public function index(EntityManagerInterface $entityManager): Response
    {
        $categories = $entityManager->getRepository(Category::class)->findAll();

        $categoriesDisplay = [];

        foreach ($categories as $index => $category) {
            $categoriesDisplay[] = [
                'title' => $category->getTitle(),
                'urlSafeTitle' => strtolower(str_replace(' ', '-', $category->getTitle())),
                'count' => $category->getCount(),
            ];
        }

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