<?php

declare(strict_types=1);

namespace App\Controller\Frontend;

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

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

    #[Route('/haber/{slug}', name: 'frontend_news_detail')]
    public function show(string $slug): Response
    {
        $newsRepo = $this->entityManager->getRepository(News::class);

        $news = $newsRepo->findOneBy([
            'slug' => $slug,
            'status' => 'published',
        ]);

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

        // Increment view count
        $news->setViewCount($news->getViewCount() + 1);
        $this->entityManager->flush();

        // Related news (same category, limit 4, exclude current)
        $relatedNews = [];
        if ($news->getCategory()) {
            $relatedNews = $newsRepo->createQueryBuilder('n')
                ->leftJoin('n.category', 'c')
                ->addSelect('c')
                ->leftJoin('n.author', 'a')
                ->addSelect('a')
                ->where('n.category = :category')
                ->andWhere('n.status = :status')
                ->andWhere('n.id != :currentId')
                ->setParameter('category', $news->getCategory())
                ->setParameter('status', 'published')
                ->setParameter('currentId', $news->getId())
                ->orderBy('n.createdAt', 'DESC')
                ->setMaxResults(4)
                ->getQuery()
                ->getResult();
        }

        // Approved comments (top-level only, children loaded via relation)
        $comments = $this->entityManager->getRepository(Comment::class)
            ->createQueryBuilder('cm')
            ->leftJoin('cm.children', 'ch')
            ->addSelect('ch')
            ->where('cm.news = :news')
            ->andWhere('cm.status = :status')
            ->andWhere('cm.parent IS NULL')
            ->setParameter('news', $news)
            ->setParameter('status', 'approved')
            ->orderBy('cm.createdAt', 'DESC')
            ->getQuery()
            ->getResult();

        return $this->render('frontend/news/detail.html.twig', [
            'news' => $news,
            'relatedNews' => $relatedNews,
            'comments' => $comments,
        ]);
    }

    #[Route('/haber/{slug}/yorum', name: 'frontend_news_comment', methods: ['POST'])]
    public function comment(string $slug, Request $request): Response
    {
        $news = $this->entityManager->getRepository(News::class)
            ->findOneBy([
                'slug' => $slug,
                'status' => 'published',
            ]);

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

        if (!$news->isAllowComments()) {
            $this->addFlash('error', 'Bu haber icin yorum yapilamaz.');
            return $this->redirectToRoute('frontend_news_detail', ['slug' => $slug]);
        }

        $authorName = trim((string) $request->request->get('author_name', ''));
        $authorEmail = trim((string) $request->request->get('author_email', ''));
        $content = trim((string) $request->request->get('content', ''));
        $parentId = $request->request->getInt('parent_id', 0);

        if ($authorName === '' || $content === '') {
            $this->addFlash('error', 'Ad ve yorum alanlari zorunludur.');
            return $this->redirectToRoute('frontend_news_detail', ['slug' => $slug]);
        }

        $comment = new Comment();
        $comment->setNews($news);
        $comment->setAuthorName($authorName);
        $comment->setAuthorEmail($authorEmail !== '' ? $authorEmail : null);
        $comment->setContent($content);
        $comment->setStatus('pending');
        $comment->setIpAddress($request->getClientIp());

        if ($parentId > 0) {
            $parentComment = $this->entityManager->getRepository(Comment::class)
                ->find($parentId);
            if ($parentComment && $parentComment->getNews()->getId() === $news->getId()) {
                $comment->setParent($parentComment);
            }
        }

        $this->entityManager->persist($comment);
        $this->entityManager->flush();

        $this->addFlash('success', 'Yorumunuz basariyla gonderildi. Onaylandiktan sonra yayinlanacaktir.');

        return $this->redirectToRoute('frontend_news_detail', ['slug' => $slug]);
    }
}
