<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

use App\Entity\Tenant\Author;
use App\Entity\Tenant\Category;
use App\Entity\Tenant\Horoscope;
use App\Entity\Tenant\News;
use App\Entity\Tenant\Poll;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class HomeController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {}

    #[Route('/', name: 'frontend_home')]
    public function index(): Response
    {
        $newsRepo = $this->entityManager->getRepository(News::class);
        $categoryRepo = $this->entityManager->getRepository(Category::class);

        // Latest 20 published news
        $latestNews = $newsRepo->createQueryBuilder('n')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->leftJoin('n.author', 'a')
            ->addSelect('a')
            ->where('n.status = :status')
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC')
            ->setMaxResults(20)
            ->getQuery()
            ->getResult();

        // Breaking news (isBreaking=true, published, limit 5)
        $breakingNews = $newsRepo->createQueryBuilder('n')
            ->where('n.isBreaking = :breaking')
            ->andWhere('n.status = :status')
            ->setParameter('breaking', true)
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC')
            ->setMaxResults(5)
            ->getQuery()
            ->getResult();

        // Headline news (isHeadline=true, published, limit 10)
        $headlineNews = $newsRepo->createQueryBuilder('n')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->leftJoin('n.author', 'a')
            ->addSelect('a')
            ->where('n.isHeadline = :headline')
            ->andWhere('n.status = :status')
            ->setParameter('headline', true)
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult();

        // Featured news (isFeatured=true, published, limit 8)
        $featuredNews = $newsRepo->createQueryBuilder('n')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->leftJoin('n.author', 'a')
            ->addSelect('a')
            ->where('n.isFeatured = :featured')
            ->andWhere('n.status = :status')
            ->setParameter('featured', true)
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC')
            ->setMaxResults(8)
            ->getQuery()
            ->getResult();

        // Video news (has videoUrl, published, limit 4)
        $videoNews = $newsRepo->createQueryBuilder('n')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->where('n.videoUrl IS NOT NULL')
            ->andWhere('n.videoUrl != :empty')
            ->andWhere('n.status = :status')
            ->setParameter('empty', '')
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC')
            ->setMaxResults(4)
            ->getQuery()
            ->getResult();

        // Active categories
        $categories = $categoryRepo->createQueryBuilder('c')
            ->where('c.status = :status')
            ->setParameter('status', 'active')
            ->orderBy('c.position', 'ASC')
            ->getQuery()
            ->getResult();

        // Active poll
        $activePoll = $this->entityManager->getRepository(Poll::class)
            ->createQueryBuilder('p')
            ->leftJoin('p.options', 'o')
            ->addSelect('o')
            ->where('p.status = :status')
            ->setParameter('status', 'active')
            ->orderBy('p.createdAt', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();

        // Active authors with their latest article title
        $authors = $this->entityManager->getRepository(Author::class)
            ->createQueryBuilder('a')
            ->where('a.isActive = :active')
            ->setParameter('active', true)
            ->orderBy('a.name', 'ASC')
            ->getQuery()
            ->getResult();

        // Get latest article for each author
        $authorLatestArticles = [];
        foreach ($authors as $author) {
            $latestArticle = $newsRepo->createQueryBuilder('n')
                ->where('n.author = :author')
                ->andWhere('n.status = :status')
                ->setParameter('author', $author)
                ->setParameter('status', 'published')
                ->orderBy('n.createdAt', 'DESC')
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult();
            if ($latestArticle) {
                $authorLatestArticles[$author->getId()] = $latestArticle;
            }
        }

        // Today's horoscopes
        $todayHoroscopes = $this->entityManager->getRepository(Horoscope::class)
            ->createQueryBuilder('h')
            ->where('h.horoscopeDate = :today')
            ->andWhere('h.status = :status')
            ->setParameter('today', (new \DateTime())->format('Y-m-d'))
            ->setParameter('status', 'published')
            ->getQuery()
            ->getResult();

        // Sort by sign order
        $signOrder = array_keys(Horoscope::SIGNS);
        usort($todayHoroscopes, function ($a, $b) use ($signOrder) {
            return array_search($a->getSign(), $signOrder) - array_search($b->getSign(), $signOrder);
        });

        return $this->render('frontend/home.html.twig', [
            'latestNews' => $latestNews,
            'breakingNews' => $breakingNews,
            'headlineNews' => $headlineNews,
            'featuredNews' => $featuredNews,
            'videoNews' => $videoNews,
            'categories' => $categories,
            'activePoll' => $activePoll,
            'authors' => $authors,
            'authorLatestArticles' => $authorLatestArticles,
            'horoscopes' => $todayHoroscopes,
            'horoscopeSigns' => Horoscope::SIGNS,
        ]);
    }
}
