<?php

namespace App\Controller\FrontEnd;

use App\Entity\Post;

use Doctrine\ORM\EntityManagerInterface;

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

final class PostController extends AbstractController
{
    /**TODO Update so this is it's own type so i don't have to hardcode anything */
    #[Route('/words', name: 'front_end_post_list', priority: 1)]
     public function index(EntityManagerInterface $entityManager): Response 
    {
        $posts = $entityManager->getRepository(Post::class)->findAllOrderByLatest();

        $formattedPosts = [];

        foreach ($posts as $index => $post) {
            $formattedPosts [] = [
                'title' => $post->getTitle(),
                'category' => $post->getCategory()->getTitle(),
                'urlSafeCategory' => $post->getCategory()->getUrlSafeTitle(),
                'description' => $post->getDescription(),
                'date' => $post->getDate(),
                'url' => $post->getUrl()
            ];
        }
        
        return $this->render('front/post/index.html.twig', [
            'posts' => $formattedPosts
        ]);
    }

    #[Route('/words/{url:post}', name: 'front_end_post_detail')]
    public function post(Post $post): Response
    {   
        if ($post->isPublished()) {
            return $this->render('front/post/detail.html.twig', [
                'post' => $post,
                'urlSafeCategory' => $post->getCategory()->getUrlSafeTitle()
            ]);
        }

        return new Response('<h1>Page not found</h1>');
    }
}
