<?php

namespace App\Controller\Admin;

use App\Entity\Tenant\Tag;
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;
use Symfony\Component\String\Slugger\SluggerInterface;

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

    #[Route('/tags', name: 'admin_tags')]
    public function index(Request $request): Response
    {
        $search = $request->query->get('q', '');

        $qb = $this->entityManager->getRepository(Tag::class)
            ->createQueryBuilder('t')
            ->orderBy('t.createdAt', 'DESC');

        if ($search !== '') {
            $qb->andWhere('t.name LIKE :search OR t.slug LIKE :search')
               ->setParameter('search', '%' . $search . '%');
        }

        $tags = $qb->getQuery()->getResult();

        return $this->render('admin/tag/index.html.twig', [
            'tags' => $tags,
            'search' => $search,
        ]);
    }

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

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

        $name = trim((string) $request->request->get('name', ''));
        if ($name === '') {
            $this->addFlash('error', 'Etiket adı boş bırakılamaz.');

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

        $slug = (string) $this->slugger->slug($name)->lower();

        // Check if tag with this slug already exists
        $existing = $this->entityManager->getRepository(Tag::class)
            ->findOneBy(['slug' => $slug]);

        if ($existing) {
            $this->addFlash('error', 'Bu etiket zaten mevcut.');

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

        $tag = new Tag();
        $tag->setName($name);
        $tag->setSlug($slug);

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

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

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

    #[Route('/tags/{id}/edit', name: 'admin_tag_edit', methods: ['GET', 'POST'])]
    public function edit(int $id, Request $request): Response
    {
        $tag = $this->entityManager->getRepository(Tag::class)->find($id);
        if (!$tag) {
            throw $this->createNotFoundException('Etiket bulunamadı.');
        }

        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('tag_form', $request->request->get('_token'))) {
                $this->addFlash('error', 'Geçersiz CSRF token. Lütfen tekrar deneyin.');

                return $this->redirectToRoute('admin_tag_edit', ['id' => $id]);
            }

            $name = trim((string) $request->request->get('name', ''));
            if ($name === '') {
                $this->addFlash('error', 'Etiket adı boş bırakılamaz.');

                return $this->redirectToRoute('admin_tag_edit', ['id' => $id]);
            }

            $slug = trim((string) $request->request->get('slug', ''));
            if ($slug === '') {
                $slug = (string) $this->slugger->slug($name)->lower();
            }

            $tag->setName($name);
            $tag->setSlug($slug);

            $this->entityManager->flush();

            $this->addFlash('success', 'Etiket başarıyla güncellendi.');

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

        return $this->render('admin/tag/index.html.twig', [
            'tags' => $this->entityManager->getRepository(Tag::class)
                ->findBy([], ['createdAt' => 'DESC']),
            'editTag' => $tag,
            'search' => '',
        ]);
    }

    #[Route('/tags/{id}/delete', name: 'admin_tag_delete', methods: ['POST'])]
    public function delete(int $id, Request $request): Response
    {
        $tag = $this->entityManager->getRepository(Tag::class)->find($id);
        if (!$tag) {
            throw $this->createNotFoundException('Etiket bulunamadı.');
        }

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

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