<?php

namespace App\Controller;

use App\Entity\Announcement;
use App\Form\AnnouncementType;
use App\Repository\AnnouncementRepository;
use App\Repository\InternApplicationRepository;
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;

#[Route('/announcement')]
final class AnnouncementController extends AbstractController
{

    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly AnnouncementRepository $announcementRepository,
    ){}
    #[Route('/', name: 'app_announcement_index')]
    public function list(Request $request,): Response
    {
        $user = $this->getUser();
        $announcements = [];

        $companyName = $request->query->get('company_name');
        $location = $request->query->get('location');
        $category = $request->query->get('category');

        if (in_array('ROLE_ADMIN', $user->getRoles())) {
            $showNonValidated = $request->query->get('show_non_validated');

            if ($showNonValidated) {
                $announcements = $this->announcementRepository->findBy(['status' => 'notVerified']);
            } else {
                $announcements = $this->announcementRepository->findAll();
            }
        }

        if (in_array('ROLE_EMPLOYEE', $user->getRoles())) {
            $company = $user->getCompany();

            if ($company) {
                $announcements = $this->announcementRepository->findBy(['company' => $company]);
            }
        }

        if (in_array('ROLE_INTERN', $user->getRoles())) {
            $announcements = $this->announcementRepository->findBy(['status' => 'Verified']);
        }

        if ($companyName || $location || $category) {
            $announcements = $this->announcementRepository->searchAnnouncements($companyName, $location, $category);
        }

        $favorites = [];
        if (in_array('ROLE_INTERN', $user->getRoles())) {
            $favorites = array_map(
                fn($f) => $f->getAnnouncement()->getId(),
                $user->getFavorites()->toArray()
            );
        }

        return $this->render('announcement/index.html.twig', [
            'announcements' => $announcements,
            'favorites' => $favorites,
            'showNonValidated' => $request->query->get('show_non_validated', false),
        ]);
    }



    #[Route('/new', name: 'app_announcement_new', methods: ['GET', 'POST'])]
    public function new(Request $request,): Response
    {
        /*$user = $this->getUser();

        if (in_array('ROLE_EMPLOYEE', $user->getRoles())) {
            $company = $user->getCompany();

            if (!$company)
            {
                echo "Compétez votre profile avant de créer une annonce";
                $this->redirectToRoute('app_user_edit',['id' => $user->getId(),]);
            }
        }*/

        $announcement = new Announcement();
        $form = $this->createForm(AnnouncementType::class, $announcement);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $announcement->setCreationDate(new \DateTime());
            $announcement->setStatus('notVerified');
            $this->entityManager->persist($announcement);
            $this->entityManager->flush();

            return $this->redirectToRoute('app_announcement_index', [], Response::HTTP_SEE_OTHER);
        }

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

    #[Route('/{id}', name: 'app_announcement_show', methods: ['GET'])]
    public function show(Announcement $announcement): Response
    {
        return $this->render('announcement/show.html.twig', [
            'announcement' => $announcement,
        ]);
    }

    #[Route('/{id}/edit', name: 'app_announcement_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Announcement $announcement,): Response
    {
        $form = $this->createForm(AnnouncementType::class, $announcement);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->entityManager->flush();

            return $this->redirectToRoute('app_announcement_index', [], Response::HTTP_SEE_OTHER);
        }

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

    #[Route('/{id}', name: 'app_announcement_delete', methods: ['POST'])]
    public function delete(Request $request, Announcement $announcement,): Response
    {
        if ($this->isCsrfTokenValid('delete'.$announcement->getId(), $request->getPayload()->getString('_token'))) {
            $this->entityManager->remove($announcement);
            $this->entityManager->flush();
        }

        return $this->redirectToRoute('app_announcement_index', [], Response::HTTP_SEE_OTHER);
    }

    #[Route('/{id}/validate', name: 'app_announcement_validate', methods: ['POST'])]
    public function validate(Request $request, Announcement $announcement,): Response
    {
        if ($announcement->getStatus() !== 'Verified')
        {
            $announcement->setStatus('Verified');
            $this->entityManager->flush();
        }
        return $this->redirectToRoute('app_announcement_show',
            ['id' => $announcement->getId()], Response::HTTP_SEE_OTHER);
    }

}
