<?php

namespace App\Controller;

use App\Entity\Announcement;
use App\Entity\Intern;
use App\Entity\InternFavorite;
use App\Repository\AnnouncementRepository;
use App\Repository\InternFavoriteRepository;
use App\Repository\InternRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class InternFavoriteController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly InternFavoriteRepository $internFavoriteRepository,
    ){}
    #[Route('/favorite/toggle/{id}', name: 'toggle_favorite')]
    public function toggleFavorite(Announcement $announcement): RedirectResponse {
        $intern = $this->getUser();

        $existing = $this->internFavoriteRepository->findOneBy([
            'intern' => $intern,
            'announcement' => $announcement
        ]);

        if ($existing) {
            $this->entityManager->remove($existing);
        } else {
            $favorite = new InternFavorite();
            $favorite->setIntern($intern);
            $favorite->setAnnouncement($announcement);
            $this->entityManager->persist($favorite);
        }

        $this->entityManager->flush();

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

    #[Route('/announcement/{id}/favorite/toggle', name: 'app_favorite_toggle', methods: ['POST'])]
    public function toggle(Announcement $announcement,Security $security): RedirectResponse
    {
        $user = $this->getUser();

        if (!$user instanceof Intern) {
            throw new AccessDeniedHttpException('Seuls les stagiaires peuvent ajouter aux favoris.');
        }

        $favorite = $this->entityManager->getRepository(InternFavorite::class)->findOneBy([
            'intern' => $user,
            'announcement' => $announcement
        ]);

        if ($favorite) {
            $this->entityManager->remove($favorite);
        } else {
            $favorite = new InternFavorite();
            $favorite->setIntern($user);
            $favorite->setAnnouncement($announcement);
            $this->entityManager->persist($favorite);
        }

        $this->entityManager->flush();

        return new RedirectResponse($_SERVER['HTTP_REFERER'] ?? '/');
    }

    #[Route('/announcement/{id}', name: 'app_announcement_show')]
    public function show(Announcement $announcement,): Response
    {
        $user = $this->getUser();
        $isFavorite = false;

        if (in_array('ROLE_INTERN', $user->getRoles())) {
            $favorite = $this->internFavoriteRepository->findOneBy([
                'announcement' => $announcement,
                'intern' => $user,
            ]);

            $isFavorite = $favorite ? true : false;
        }

        return $this->render('announcement/show.html.twig', [
            'announcement' => $announcement,
            'isFavorite' => $isFavorite,
        ]);
    }

    #[Route('/favorite/add/{id}', name: 'app_favorite_add')]
    public function addFavorite(Announcement $announcement,): Response
    {
        $user = $this->getUser();

        // Vérifier si l'intern a déjà ce favori
        $existingFavorite = $this->entityManager->getRepository(InternFavorite::class)->findOneBy([
            'announcement' => $announcement,
            'intern' => $user,
        ]);

        if (!$existingFavorite) {
            $favorite = new InternFavorite();
            $favorite->setAnnouncement($announcement);
            $favorite->setIntern($user);

            $this->entityManager->persist($favorite);
            $this->entityManager->flush();
        }

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

    #[Route('/favorite/remove/{id}', name: 'app_favorite_remove')]
    public function removeFavorite(Announcement $announcement,): Response
    {
        $user = $this->getUser();

        $favorite = $this->entityManager->getRepository(InternFavorite::class)->findOneBy([
            'announcement' => $announcement,
            'intern' => $user,
        ]);

        if ($favorite) {
            $this->entityManager->remove($favorite);
            $this->entityManager->flush();
        }

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