<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\Routing\Attribute\Route;

use Doctrine\ORM\EntityManagerInterface;

use App\Entity\State;
use App\Entity\Investigation;

use App\Repository\StateRepository;
use App\Repository\BroadcastRepository;
use App\Repository\InvestigationRepository;

use App\Form\BroadcastType;

#[Route('/broadcast')]
final class BroadcastController extends AbstractController
{
    /**
     * @param EntityManagerInterface $em
     * @param StateRepository $stateRepository
     * @param BroadcastRepository $broadcastRepository
     * @param InvestigationRepository $investigationRepository
     * @return $this
     */
    public function __construct(
        private EntityManagerInterface $em,
        private StateRepository $stateRepository,
        private BroadcastRepository $broadcastRepository,
        private InvestigationRepository $investigationRepository,
    ) {
        $this->em = $em;
        $this->stateRepository = $stateRepository;
        $this->broadcastRepository = $broadcastRepository;
        $this->investigationRepository = $investigationRepository;
    }

    #[Route('/index', name: 'app_broadcast_index')]
    public function index(): Response
    {
        $investigations = $this->investigationRepository->findInvestigationAdminValidated($this->getUser());

        $broadcasts = $this->broadcastRepository->findByUser($this->getUser());

        return $this->render('broadcast/index.html.twig', [
            'investigations' => $investigations,
            'broadcasts' => $broadcasts,
        ]);
    }

    #[Route('/add/{id}', name: 'app_broadcast_add')]
    public function add(Request $request, Investigation $investigation): Response
    {
        $form = $this->createForm(BroadcastType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $broadcast = $form->getData();
            $broadcast->setInvestigation($investigation);
            $broadcast->setCreateBy($this->getUser());
            $broadcast->setCost(150);
            $this->em->persist($broadcast);
            $this->em->flush();

            $investigation->setLastState(31);
            $this->em->persist($investigation);
            $this->em->flush();

            $this->stateRepository->addState($investigation, 3, 1, $broadcast);

            $this->addFlash('danger', " <strong>Well done!</strong> You successfully read this important alert message.");
            
            return $this->redirectToRoute('app_broadcast_index');
        }

        return $this->render('broadcast/add.html.twig', [
            'form' => $form->createView(),
            'investigation' => $investigation,
        ]);
    }
}
