<?php

namespace App\Controller;

use App\Entity\Announcement;
use App\Entity\Degree;
use App\Entity\Intern;
use App\Entity\InternApplication;
use App\Entity\InternDegree;
use App\Entity\InternSkill;
use App\Entity\Skill;
use App\Form\InternType;
use App\Repository\AnnouncementRepository;
use App\Repository\DegreeRepository;
use App\Repository\InternApplicationRepository;
use App\Repository\InternDegreeRepository;
use App\Repository\InternRepository;
use App\Repository\InternSkillRepository;
use App\Repository\SkillRepository;
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('/intern')]
final class InternController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    private readonly AnnouncementRepository $announcementRepository,
    private readonly InternRepository $internRepository,
    private readonly InternApplicationRepository $internApplicationRepository,
    private readonly InternDegreeRepository $internDegreeRepository,
    private readonly InternSkillRepository $internSkillRepository,
    private readonly DegreeRepository $degreeRepository,
    private readonly SkillRepository $skillRepository,
    ){}
    #[Route(name: 'app_intern_index', methods: ['GET'])]
    public function index(): Response
    {
        return $this->render('intern/index.html.twig', [
            'interns' => $this->internRepository->findAll(),
        ]);
    }

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

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

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

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

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

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

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

    #[Route('/degrees/add', name:'app_intern_add_degrees', methods:['POST'])]
    public function addDegrees(Request $request): Response
    {
        $intern = $this->getUser();

        if (!$intern instanceof Intern) {
            throw $this->createAccessDeniedException("Seuls les stagiaires peuvent sélectionner des diplômes.");
        }

        $selectedDegreeIds = $request->request->all('selected_degrees');

        if ($selectedDegreeIds == []) {
            $this->addFlash('error', "Aucune sélection valide n'a été effectuée.");
            return $this->redirectToRoute('app_degree_index');
        }

        foreach ($selectedDegreeIds as $degreeId) {
            $degree = $this->degreeRepository->find($degreeId);

            if (!$degree) {
                continue;
            }

            $existingInternDegree = $this->internDegreeRepository->findOneBy([
                'intern' => $intern,
                'degree' => $degree
            ]);

            if (!$existingInternDegree) {
                $internDegree = new InternDegree();
                $internDegree->setIntern($intern);
                $internDegree->setDegree($degree);
                $internDegree->setGraduationDate(new \DateTime());

                $this->entityManager->persist($internDegree);
            }
        }

        $this->entityManager->flush();

        $this->addFlash('success', 'Les diplômes ont été ajoutés avec succès.');

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

    #[Route('/application/send', name:'app_intern_send_application', methods:['POST'])]
    public function sendApplication(Request $request,): Response
    {
        $intern = $this->getUser();
        if (!$intern instanceof Intern) {
            throw $this->createAccessDeniedException("Seuls les stagiaires peuvent envoyer des candidatures.");
        }

        $announcementId = $request->request->get('announcement_id');
        $announcement = $this->announcementRepository->find($announcementId);

        $existingInternApplication = $this->internApplicationRepository->findOneBy([
            'intern' => $intern,
            'application' => $announcement
        ]);

        if (!$existingInternApplication) {
            $internApplication = new InternApplication();
            $internApplication->setIntern($intern);
            $internApplication->setApplication($announcement);
            $internApplication->setApplicationDate(new \DateTime());
            $internApplication->setStatus("En Attente");

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

        $this->addFlash('success', 'La candidature à bien été envoyée.');

        return $this->redirectToRoute('app_profile');

    }

    #[Route('/skills/add', name:'app_intern_add_skills', methods:['POST'])]
    public function addSkills(Request $request,): Response
    {
        $intern = $this->getUser();

        if (!$intern instanceof Intern) {
            throw $this->createAccessDeniedException("Seuls les stagiaires peuvent sélectionner des compétences.");
        }

        $selectedSkillIds = $request->request->all('selected_skills');

        if ($selectedSkillIds == []) {
            $this->addFlash('error', "Aucune sélection valide n'a été effectuée.");
            return $this->redirectToRoute('app_skill_index');
        }

        foreach ($selectedSkillIds as $skillId) {
            $skill = $this->skillRepository->find($skillId);

            if (!$skill) continue;

            $existingInternSkill = $this->internSkillRepository->findOneBy([
                'intern' => $intern,
                'skill' => $skill
            ]);

            if (!$existingInternSkill) {
                $internSkill = new InternSkill();
                $internSkill->setIntern($intern);
                $internSkill->setSkill($skill);

                $this->entityManager->persist($internSkill);
            }
        }

        $this->entityManager->flush();

        $this->addFlash('success', 'Les compétences ont été ajoutées avec succès.');

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

}
