<?php

namespace App\Controller\Admin;

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

    #[Route('/categories', name: 'admin_categories')]
    public function index(): Response
    {
        $categories = $this->entityManager->getRepository(Category::class)
            ->createQueryBuilder('c')
            ->leftJoin('c.parent', 'p')
            ->addSelect('p')
            ->orderBy('c.position', 'ASC')
            ->addOrderBy('c.title', 'ASC')
            ->getQuery()
            ->getResult();

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

    #[Route('/categories/create', name: 'admin_category_create', methods: ['GET', 'POST'])]
    public function create(Request $request): Response
    {
        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('category_form', $request->request->get('_token'))) {
                $this->addFlash('error', 'Gecersiz CSRF token. Lutfen tekrar deneyin.');

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

            $category = new Category();
            $this->handleFormData($category, $request);

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

            $this->addFlash('success', 'Kategori basariyla olusturuldu.');

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

        $categories = $this->entityManager->getRepository(Category::class)
            ->findBy([], ['title' => 'ASC']);

        return $this->render('admin/category/form.html.twig', [
            'category' => null,
            'categories' => $categories,
        ]);
    }

    #[Route('/categories/{id}/edit', name: 'admin_category_edit', methods: ['GET', 'POST'])]
    public function edit(int $id, Request $request): Response
    {
        $category = $this->entityManager->getRepository(Category::class)->find($id);
        if (!$category) {
            throw $this->createNotFoundException('Kategori bulunamadi.');
        }

        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('category_form', $request->request->get('_token'))) {
                $this->addFlash('error', 'Gecersiz CSRF token. Lutfen tekrar deneyin.');

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

            $this->handleFormData($category, $request);

            $this->entityManager->flush();

            $this->addFlash('success', 'Kategori basariyla guncellendi.');

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

        $categories = $this->entityManager->getRepository(Category::class)
            ->findBy([], ['title' => 'ASC']);

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

    #[Route('/categories/{id}/delete', name: 'admin_category_delete', methods: ['POST'])]
    public function delete(int $id, Request $request): Response
    {
        $category = $this->entityManager->getRepository(Category::class)->find($id);
        if (!$category) {
            throw $this->createNotFoundException('Kategori bulunamadi.');
        }

        if ($this->isCsrfTokenValid('delete_category_' . $id, $request->request->get('_token'))) {
            $this->entityManager->remove($category);
            $this->entityManager->flush();
            $this->addFlash('success', 'Kategori basariyla silindi.');
        } else {
            $this->addFlash('error', 'Gecersiz CSRF token. Silme islemi gerceklestirilemedi.');
        }

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

    private function handleFormData(Category $category, Request $request): void
    {
        $data = $request->request;

        // --- Title & Slug ---
        $title = trim((string) $data->get('title', ''));
        $category->setTitle($title);

        $slug = trim((string) $data->get('slug', ''));
        if ($slug === '') {
            $slug = (string) $this->slugger->slug($title)->lower();
        }
        $category->setSlug($slug);

        // --- Description ---
        $category->setDescription($data->get('description') ?: null);

        // --- Parent Category ---
        $parentId = $data->get('parent_id');
        if ($parentId) {
            $parent = $this->entityManager->getRepository(Category::class)->find((int) $parentId);
            $category->setParent($parent);
        } else {
            $category->setParent(null);
        }

        // --- Visual settings ---
        $category->setColor($data->get('color') ?: null);
        $category->setIcon($data->get('icon') ?: null);
        $category->setImage($data->get('image') ?: null);

        // --- Status & Position ---
        $category->setStatus($data->get('status', 'active') ?: 'active');
        $category->setPosition((int) $data->get('position', 0));
        $category->setIsDefault((bool) $data->get('is_default', false));

        // --- SEO fields ---
        $category->setSeoTitle($data->get('seo_title') ?: null);
        $category->setSeoDescription($data->get('seo_description') ?: null);

        // --- Assigned Modules (comma-separated -> JSON array) ---
        $modulesString = trim((string) $data->get('assigned_modules', ''));
        if ($modulesString !== '') {
            $modules = array_filter(array_map('trim', explode(',', $modulesString)));
            $category->setAssignedModules(array_values($modules));
        } else {
            $category->setAssignedModules(null);
        }
    }
}
