<?php

namespace App\Controller\Admin;

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

    #[Route('/pages', name: 'admin_pages')]
    public function index(): Response
    {
        $pages = $this->entityManager->getRepository(Page::class)
            ->createQueryBuilder('p')
            ->orderBy('p.position', 'ASC')
            ->addOrderBy('p.createdAt', 'DESC')
            ->getQuery()
            ->getResult();

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

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

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

            $page = new Page();
            $this->handleFormData($page, $request);

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

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

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

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

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

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

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

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

            $this->entityManager->flush();

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

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

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

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

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

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

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

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

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

        // --- Content ---
        $page->setContent($data->get('content') ?: null);

        // --- Featured Image ---
        $page->setFeaturedImage($data->get('featured_image') ?: null);

        // --- Template ---
        $page->setTemplate($data->get('template', 'default') ?: 'default');

        // --- Status ---
        $page->setStatus($data->get('status', 'draft') ?: 'draft');

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

        // --- Position ---
        $page->setPosition((int) $data->get('position', 0));
    }
}
