<?php

namespace App\Controller\Admin;

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

    #[Route('/polls', name: 'admin_polls')]
    public function index(): Response
    {
        $polls = $this->entityManager->getRepository(Poll::class)
            ->createQueryBuilder('p')
            ->orderBy('p.createdAt', 'DESC')
            ->getQuery()
            ->getResult();

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

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

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

            $poll = new Poll();
            $this->handleFormData($poll, $request);

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

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

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

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

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

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

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

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

            $this->entityManager->flush();

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

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

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

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

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

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

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

        // --- Basic fields ---
        $poll->setQuestion(trim((string) $data->get('question', '')));
        $poll->setStatus($data->get('status', 'draft') ?: 'draft');
        $poll->setMultipleChoice((bool) $data->get('multiple_choice', false));
        $poll->setShowResults((bool) $data->get('show_results', true));

        // --- Dates ---
        $startsAtStr = $data->get('starts_at');
        if ($startsAtStr) {
            try {
                $poll->setStartsAt(new \DateTimeImmutable($startsAtStr));
            } catch (\Exception) {
                $poll->setStartsAt(null);
            }
        } else {
            $poll->setStartsAt(null);
        }

        $endsAtStr = $data->get('ends_at');
        if ($endsAtStr) {
            try {
                $poll->setEndsAt(new \DateTimeImmutable($endsAtStr));
            } catch (\Exception) {
                $poll->setEndsAt(null);
            }
        } else {
            $poll->setEndsAt(null);
        }

        // --- Options ---
        $optionTexts = $data->all('options');

        // Remove existing options that are no longer present
        foreach ($poll->getOptions()->toArray() as $existingOption) {
            $poll->removeOption($existingOption);
            $this->entityManager->remove($existingOption);
        }

        // Add new options
        $position = 0;
        foreach ($optionTexts as $text) {
            $text = trim((string) $text);
            if ($text === '') {
                continue;
            }

            $option = new PollOption();
            $option->setOptionText($text);
            $option->setPosition($position);
            $poll->addOption($option);
            $this->entityManager->persist($option);

            $position++;
        }
    }
}
