<?php

namespace App\Controller\Admin;

use App\Entity\Tenant\News;
use App\Entity\Tenant\Redirect;
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 SeoController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {}

    #[Route('/seo', name: 'admin_seo')]
    public function index(): Response
    {
        // Gather SEO overview stats
        $newsRepo = $this->entityManager->getRepository(News::class);
        $redirectRepo = $this->entityManager->getRepository(Redirect::class);

        $totalNews = $newsRepo->createQueryBuilder('n')
            ->select('COUNT(n.id)')
            ->getQuery()
            ->getSingleScalarResult();

        $redirectCount = $redirectRepo->createQueryBuilder('r')
            ->select('COUNT(r.id)')
            ->getQuery()
            ->getSingleScalarResult();

        $activeRedirectCount = $redirectRepo->createQueryBuilder('r')
            ->select('COUNT(r.id)')
            ->where('r.isActive = true')
            ->getQuery()
            ->getSingleScalarResult();

        return $this->render('admin/seo/index.html.twig', [
            'totalNews' => (int) $totalNews,
            'redirectCount' => (int) $redirectCount,
            'activeRedirectCount' => (int) $activeRedirectCount,
        ]);
    }

    #[Route('/seo/redirects', name: 'admin_seo_redirects')]
    public function redirects(Request $request): Response
    {
        $redirects = $this->entityManager->getRepository(Redirect::class)
            ->createQueryBuilder('r')
            ->orderBy('r.createdAt', 'DESC')
            ->getQuery()
            ->getResult();

        return $this->render('admin/seo/redirects.html.twig', [
            'redirects' => $redirects,
        ]);
    }

    #[Route('/seo/redirects/create', name: 'admin_seo_redirect_create', methods: ['POST'])]
    public function createRedirect(Request $request): Response
    {
        if (!$this->isCsrfTokenValid('redirect_form', $request->request->get('_token'))) {
            $this->addFlash('error', 'Geçersiz CSRF token. Lütfen tekrar deneyin.');

            return $this->redirectToRoute('admin_seo_redirects');
        }

        $data = $request->request;

        $sourcePath = trim((string) $data->get('source_path', ''));
        $targetPath = trim((string) $data->get('target_path', ''));

        if ($sourcePath === '' || $targetPath === '') {
            $this->addFlash('error', 'Kaynak ve hedef URL alanları zorunludur.');

            return $this->redirectToRoute('admin_seo_redirects');
        }

        $redirect = new Redirect();
        $redirect->setSourcePath($sourcePath);
        $redirect->setTargetPath($targetPath);
        $redirect->setStatusCode((int) $data->get('status_code', 301));
        $redirect->setIsActive((bool) $data->get('is_active', true));

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

        $this->addFlash('success', 'Yönlendirme başarıyla oluşturuldu.');

        return $this->redirectToRoute('admin_seo_redirects');
    }

    #[Route('/seo/redirects/{id}/delete', name: 'admin_seo_redirect_delete', methods: ['POST'])]
    public function deleteRedirect(int $id, Request $request): Response
    {
        $redirect = $this->entityManager->getRepository(Redirect::class)->find($id);
        if (!$redirect) {
            throw $this->createNotFoundException('Yönlendirme bulunamadı.');
        }

        if ($this->isCsrfTokenValid('delete_redirect_' . $id, $request->request->get('_token'))) {
            $this->entityManager->remove($redirect);
            $this->entityManager->flush();
            $this->addFlash('success', 'Yönlendirme başarıyla silindi.');
        } else {
            $this->addFlash('error', 'Geçersiz CSRF token. Silme işlemi gerçekleştirilemedi.');
        }

        return $this->redirectToRoute('admin_seo_redirects');
    }
}
