<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Controller;

use Chill\MainBundle\Form\AbsenceType;
use Chill\MainBundle\Security\ChillSecurity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class AbsenceController extends AbstractController
{
    public function __construct(private readonly ChillSecurity $security, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    #[Route(path: '/{_locale}/absence', name: 'chill_main_user_absence_index', methods: ['GET', 'POST'])]
    public function setAbsence(Request $request)
    {
        $user = $this->security->getUser();
        $form = $this->createForm(AbsenceType::class, $user);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->managerRegistry->getManager();
            $em->flush();

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

        return $this->render('@ChillMain/Menu/absence.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }

    #[Route(path: '/{_locale}/absence/unset', name: 'chill_main_user_absence_unset', methods: ['GET', 'POST'])]
    public function unsetAbsence(Request $request)
    {
        $user = $this->security->getUser();

        $user->setAbsenceStart(null);
        $user->setAbsenceEnd(null);
        $em = $this->managerRegistry->getManager();
        $em->flush();

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