<?php

declare(strict_types=1);

namespace App\Controller\Admin;

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

    /**
     * Astroloji ana sayfasi - bugunun burc yorumlari.
     */
    #[Route('/horoscope', name: 'admin_horoscope')]
    public function index(Request $request): Response
    {
        $dateStr = $request->query->get('date', (new \DateTime())->format('Y-m-d'));
        $date = new \DateTimeImmutable($dateStr);

        $horoscopes = $this->entityManager->getRepository(Horoscope::class)
            ->createQueryBuilder('h')
            ->where('h.horoscopeDate = :date')
            ->setParameter('date', $date->format('Y-m-d'))
            ->orderBy('h.sign', 'ASC')
            ->getQuery()
            ->getResult();

        // Burc sirasina gore sirala
        $signOrder = array_keys(Horoscope::SIGNS);
        usort($horoscopes, function ($a, $b) use ($signOrder) {
            return array_search($a->getSign(), $signOrder) - array_search($b->getSign(), $signOrder);
        });

        // Hangi burclar eksik?
        $existingSigns = array_map(fn($h) => $h->getSign(), $horoscopes);
        $missingSigns = array_diff(array_keys(Horoscope::SIGNS), $existingSigns);

        return $this->render('admin/horoscope/index.html.twig', [
            'horoscopes' => $horoscopes,
            'missingSigns' => $missingSigns,
            'signs' => Horoscope::SIGNS,
            'currentDate' => $date,
        ]);
    }

    /**
     * Yeni burc yorumu ekle.
     */
    #[Route('/horoscope/create', name: 'admin_horoscope_create', methods: ['GET', 'POST'])]
    public function create(Request $request): Response
    {
        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('horoscope_form', $request->request->get('_token'))) {
                $this->addFlash('error', 'Gecersiz CSRF token.');
                return $this->redirectToRoute('admin_horoscope_create');
            }

            $horoscope = new Horoscope();
            $this->handleFormData($horoscope, $request);

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

            $this->addFlash('success', $horoscope->getSignName() . ' burcu yorumu basariyla eklendi.');
            return $this->redirectToRoute('admin_horoscope', ['date' => $horoscope->getHoroscopeDate()->format('Y-m-d')]);
        }

        $sign = $request->query->get('sign', '');
        $date = $request->query->get('date', (new \DateTime())->format('Y-m-d'));

        return $this->render('admin/horoscope/form.html.twig', [
            'horoscope' => null,
            'signs' => Horoscope::SIGNS,
            'defaultSign' => $sign,
            'defaultDate' => $date,
        ]);
    }

    /**
     * Burc yorumunu duzenle.
     */
    #[Route('/horoscope/{id}/edit', name: 'admin_horoscope_edit', methods: ['GET', 'POST'])]
    public function edit(int $id, Request $request): Response
    {
        $horoscope = $this->entityManager->getRepository(Horoscope::class)->find($id);
        if (!$horoscope) {
            throw $this->createNotFoundException('Burc yorumu bulunamadi.');
        }

        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('horoscope_form', $request->request->get('_token'))) {
                $this->addFlash('error', 'Gecersiz CSRF token.');
                return $this->redirectToRoute('admin_horoscope_edit', ['id' => $id]);
            }

            $this->handleFormData($horoscope, $request);
            $this->entityManager->flush();

            $this->addFlash('success', $horoscope->getSignName() . ' burcu yorumu guncellendi.');
            return $this->redirectToRoute('admin_horoscope', ['date' => $horoscope->getHoroscopeDate()->format('Y-m-d')]);
        }

        return $this->render('admin/horoscope/form.html.twig', [
            'horoscope' => $horoscope,
            'signs' => Horoscope::SIGNS,
            'defaultSign' => $horoscope->getSign(),
            'defaultDate' => $horoscope->getHoroscopeDate()->format('Y-m-d'),
        ]);
    }

    /**
     * Burc yorumunu sil.
     */
    #[Route('/horoscope/{id}/delete', name: 'admin_horoscope_delete', methods: ['POST'])]
    public function delete(int $id, Request $request): Response
    {
        $horoscope = $this->entityManager->getRepository(Horoscope::class)->find($id);
        if (!$horoscope) {
            throw $this->createNotFoundException('Burc yorumu bulunamadi.');
        }

        if ($this->isCsrfTokenValid('delete_horoscope_' . $id, $request->request->get('_token'))) {
            $date = $horoscope->getHoroscopeDate()->format('Y-m-d');
            $this->entityManager->remove($horoscope);
            $this->entityManager->flush();
            $this->addFlash('success', 'Burc yorumu silindi.');
            return $this->redirectToRoute('admin_horoscope', ['date' => $date]);
        }

        $this->addFlash('error', 'Gecersiz CSRF token.');
        return $this->redirectToRoute('admin_horoscope');
    }

    /**
     * Tum burclar icin toplu yorum ekleme.
     */
    #[Route('/horoscope/bulk', name: 'admin_horoscope_bulk', methods: ['GET', 'POST'])]
    public function bulk(Request $request): Response
    {
        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('horoscope_bulk', $request->request->get('_token'))) {
                $this->addFlash('error', 'Gecersiz CSRF token.');
                return $this->redirectToRoute('admin_horoscope_bulk');
            }

            $dateStr = $request->request->get('date', (new \DateTime())->format('Y-m-d'));
            $date = new \DateTimeImmutable($dateStr);
            $count = 0;

            foreach (Horoscope::SIGNS as $slug => $signData) {
                $content = trim((string) $request->request->get('content_' . $slug, ''));
                if ($content === '') {
                    continue;
                }

                // Var mi kontrol et
                $existing = $this->entityManager->getRepository(Horoscope::class)
                    ->findOneBy(['sign' => $slug, 'horoscopeDate' => $date]);

                if ($existing) {
                    $existing->setContent($content);
                    $existing->setLoveRating($request->request->get('love_' . $slug) ?: null);
                    $existing->setCareerRating($request->request->get('career_' . $slug) ?: null);
                    $existing->setHealthRating($request->request->get('health_' . $slug) ?: null);
                } else {
                    $horoscope = new Horoscope();
                    $horoscope->setSign($slug);
                    $horoscope->setHoroscopeDate($date);
                    $horoscope->setContent($content);
                    $horoscope->setLoveRating($request->request->get('love_' . $slug) ?: null);
                    $horoscope->setCareerRating($request->request->get('career_' . $slug) ?: null);
                    $horoscope->setHealthRating($request->request->get('health_' . $slug) ?: null);
                    $this->entityManager->persist($horoscope);
                }
                $count++;
            }

            $this->entityManager->flush();
            $this->addFlash('success', $count . ' burc yorumu basariyla kaydedildi.');
            return $this->redirectToRoute('admin_horoscope', ['date' => $dateStr]);
        }

        $date = $request->query->get('date', (new \DateTime())->format('Y-m-d'));

        // Mevcut yorumlari al
        $existing = $this->entityManager->getRepository(Horoscope::class)
            ->createQueryBuilder('h')
            ->where('h.horoscopeDate = :date')
            ->setParameter('date', $date)
            ->getQuery()
            ->getResult();

        $existingMap = [];
        foreach ($existing as $h) {
            $existingMap[$h->getSign()] = $h;
        }

        return $this->render('admin/horoscope/bulk.html.twig', [
            'signs' => Horoscope::SIGNS,
            'existingMap' => $existingMap,
            'currentDate' => $date,
        ]);
    }

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

        $horoscope->setSign($data->get('sign', ''));
        $horoscope->setHoroscopeDate(new \DateTimeImmutable($data->get('horoscope_date', 'now')));
        $horoscope->setContent(trim((string) $data->get('content', '')));
        $horoscope->setLoveRating($data->get('love_rating') ?: null);
        $horoscope->setCareerRating($data->get('career_rating') ?: null);
        $horoscope->setHealthRating($data->get('health_rating') ?: null);
        $horoscope->setLuckyNumber($data->get('lucky_number') ?: null);
        $horoscope->setLuckyColor($data->get('lucky_color') ?: null);
        $horoscope->setStatus($data->get('status', 'published'));
    }
}
