<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

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 SearchController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {}

    #[Route('/arama', name: 'frontend_search')]
    public function search(Request $request, PaginatorInterface $paginator): Response
    {
        $query = trim((string) $request->query->get('q', ''));
        $pagination = null;

        if ($query !== '') {
            $qb = $this->entityManager->getRepository(News::class)
                ->createQueryBuilder('n')
                ->leftJoin('n.category', 'c')
                ->addSelect('c')
                ->leftJoin('n.author', 'a')
                ->addSelect('a')
                ->where('n.status = :status')
                ->andWhere('n.title LIKE :query OR n.content LIKE :query')
                ->setParameter('status', 'published')
                ->setParameter('query', '%' . $query . '%')
                ->orderBy('n.createdAt', 'DESC');

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

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