<?php

namespace App\Controller\Admin;

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

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

    #[Route('/menus', name: 'admin_menus')]
    public function index(): Response
    {
        $menus = $this->entityManager->getRepository(Menu::class)
            ->createQueryBuilder('m')
            ->leftJoin('m.items', 'i')
            ->addSelect('i')
            ->orderBy('m.createdAt', 'DESC')
            ->getQuery()
            ->getResult();

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

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

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

            $menu = new Menu();
            $this->handleMenuFormData($menu, $request);

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

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

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

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

    #[Route('/menus/{id}/edit', name: 'admin_menu_edit', methods: ['GET', 'POST'])]
    public function edit(int $id, Request $request): Response
    {
        $menu = $this->entityManager->getRepository(Menu::class)->find($id);
        if (!$menu) {
            throw $this->createNotFoundException('Menü bulunamadı.');
        }

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

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

            $this->handleMenuFormData($menu, $request);

            $this->entityManager->flush();

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

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

        // Get top-level items (no parent) ordered by position
        $items = $this->entityManager->getRepository(MenuItem::class)
            ->createQueryBuilder('mi')
            ->leftJoin('mi.children', 'c')
            ->addSelect('c')
            ->where('mi.menu = :menu')
            ->andWhere('mi.parent IS NULL')
            ->setParameter('menu', $menu)
            ->orderBy('mi.position', 'ASC')
            ->addOrderBy('c.position', 'ASC')
            ->getQuery()
            ->getResult();

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

    #[Route('/menus/{id}/delete', name: 'admin_menu_delete', methods: ['POST'])]
    public function delete(int $id, Request $request): Response
    {
        $menu = $this->entityManager->getRepository(Menu::class)->find($id);
        if (!$menu) {
            throw $this->createNotFoundException('Menü bulunamadı.');
        }

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

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

    #[Route('/menus/{id}/items', name: 'admin_menu_items', methods: ['POST'])]
    public function saveItems(int $id, Request $request): JsonResponse
    {
        $menu = $this->entityManager->getRepository(Menu::class)->find($id);
        if (!$menu) {
            return new JsonResponse(['success' => false, 'message' => 'Menü bulunamadı.'], 404);
        }

        $data = json_decode($request->getContent(), true);
        if (!isset($data['items']) || !is_array($data['items'])) {
            return new JsonResponse(['success' => false, 'message' => 'Geçersiz veri.'], 400);
        }

        $itemRepo = $this->entityManager->getRepository(MenuItem::class);

        foreach ($data['items'] as $index => $itemData) {
            $itemId = $itemData['id'] ?? null;

            if ($itemId) {
                // Update existing item
                $item = $itemRepo->find((int) $itemId);
                if ($item && $item->getMenu()->getId() === $menu->getId()) {
                    $item->setPosition($index);

                    if (isset($itemData['title'])) {
                        $item->setTitle($itemData['title']);
                    }
                    if (isset($itemData['url'])) {
                        $item->setUrl($itemData['url']);
                    }
                    if (isset($itemData['target'])) {
                        $item->setTarget($itemData['target']);
                    }
                    if (isset($itemData['icon'])) {
                        $item->setIcon($itemData['icon']);
                    }
                    if (isset($itemData['css_class'])) {
                        $item->setCssClass($itemData['css_class']);
                    }
                    if (array_key_exists('is_active', $itemData)) {
                        $item->setIsActive((bool) $itemData['is_active']);
                    }

                    // Update parent
                    $parentId = $itemData['parent_id'] ?? null;
                    if ($parentId) {
                        $parent = $itemRepo->find((int) $parentId);
                        if ($parent && $parent->getMenu()->getId() === $menu->getId()) {
                            $item->setParent($parent);
                        }
                    } else {
                        $item->setParent(null);
                    }
                }
            } else {
                // Create new item
                $item = new MenuItem();
                $item->setMenu($menu);
                $item->setTitle($itemData['title'] ?? 'Yeni Öğe');
                $item->setUrl($itemData['url'] ?? null);
                $item->setTarget($itemData['target'] ?? '_self');
                $item->setIcon($itemData['icon'] ?? null);
                $item->setCssClass($itemData['css_class'] ?? null);
                $item->setPosition($index);
                $item->setIsActive($itemData['is_active'] ?? true);

                $parentId = $itemData['parent_id'] ?? null;
                if ($parentId) {
                    $parent = $itemRepo->find((int) $parentId);
                    if ($parent && $parent->getMenu()->getId() === $menu->getId()) {
                        $item->setParent($parent);
                    }
                }

                $this->entityManager->persist($item);
            }
        }

        $this->entityManager->flush();

        return new JsonResponse(['success' => true, 'message' => 'Menü öğeleri başarıyla kaydedildi.']);
    }

    private function handleMenuFormData(Menu $menu, Request $request): void
    {
        $data = $request->request;

        $menu->setName(trim((string) $data->get('name', '')));
        $menu->setLocation((string) $data->get('location', 'header'));
        $menu->setIsActive((bool) $data->get('is_active', false));
    }
}
