<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

use App\Entity\Tenant\Category;
use App\Entity\Tenant\News;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

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

    #[Route('/kategori/{slug}', name: 'frontend_category')]
    public function show(string $slug, Request $request, PaginatorInterface $paginator): Response
    {
        $category = $this->entityManager->getRepository(Category::class)
            ->findOneBy([
                'slug' => $slug,
                'status' => 'active',
            ]);

        if (!$category) {
            throw $this->createNotFoundException('Kategori bulunamadi.');
        }

        $qb = $this->entityManager->getRepository(News::class)
            ->createQueryBuilder('n')
            ->leftJoin('n.author', 'a')
            ->addSelect('a')
            ->leftJoin('n.category', 'c')
            ->addSelect('c')
            ->where('n.category = :category')
            ->andWhere('n.status = :status')
            ->setParameter('category', $category)
            ->setParameter('status', 'published')
            ->orderBy('n.createdAt', 'DESC');

        $pagination = $paginator->paginate(
            $qb,
            $request->query->getInt('page', 1),
            20
        );

        // Subcategories
        $subcategories = $this->entityManager->getRepository(Category::class)
            ->createQueryBuilder('sc')
            ->where('sc.parent = :parent')
            ->andWhere('sc.status = :status')
            ->setParameter('parent', $category)
            ->setParameter('status', 'active')
            ->orderBy('sc.position', 'ASC')
            ->getQuery()
            ->getResult();

        // Popular in category (by viewCount)
        $popularInCategory = $this->entityManager->getRepository(News::class)
            ->createQueryBuilder('n')
            ->where('n.category = :category')
            ->andWhere('n.status = :status')
            ->setParameter('category', $category)
            ->setParameter('status', 'published')
            ->orderBy('n.viewCount', 'DESC')
            ->setMaxResults(5)
            ->getQuery()
            ->getResult();

        return $this->render('frontend/category/index.html.twig', [
            'category' => $category,
            'pagination' => $pagination,
            'subcategories' => $subcategories,
            'popularInCategory' => $popularInCategory,
        ]);
    }
}
