<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\MotdType;
use App\Form\EmployeeType;
use Psr\Log\LoggerInterface;
use App\Repository\TemplateRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

#[Route('/group', name: 'group_')]
class GroupController extends AbstractController
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    #[Route('/', name: 'index')]
    public function index(Request $request, TemplateRepository $TemplateRepository): Response
    {

        /**
         *  @var User $currentUser
         */
        $currentUser = $this->getUser();
        $group = $currentUser->getMainGroup();
        if (!$this->IsGranted('administrate', $group)) {
            throw new AccessDeniedHttpException('granted_not_allowed_administrate_group');
        }


        $form = $this->createForm(MotdType::class, $group);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (!$this->IsGranted('motd', $group)) {
                throw new AccessDeniedHttpException('granted_not_allowed_editing_motd_group');
            }

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($group);
            try {
                $entityManager->flush();
                $this->addFlash('success', 'alert_success_editing_motd');
            } catch (\Throwable $th) {
                if ($_ENV['APP_ENV'] === 'dev') {
                    throw $th; //DEBUG
                } else {
                    $this->logger->error($th);
                }
                $this->addFlash('danger', 'alert_error_editing_motd');
            }
        } elseif ($form->isSubmitted() && !$form->isValid()) {
            $this->addFlash('warning', 'alert_error_form_post');
        }

        return $this->render('group/index.html.twig', [
            'controller_name' => 'GroupController',
            'formMOTD' => $form->createView(),
            'group' => $group,
            'templates' => $TemplateRepository->listForUser($currentUser)->getResult()
        ]);
    }

    #[Route('/fire/{id}', name: 'fire')]
    public function fire(User $User, Request $Request): Response
    {

        /**
         * @var User $currentUser
         */
        $currentUser = $this->getUser();

        $group = $currentUser->getMainGroup();
        if (!$this->IsGranted('fire', $group)) {
            throw new AccessDeniedHttpException('granted_not_allowed_fire_employee');
        }

        if (
            null != $User->getMainRank()
            && $User->getMainRank()->getPower() >= $currentUser->getMainRank()->getPower()
            && !$currentUser->getAdminMode()
        ) {
            $this->addFlash('danger', 'alert_error_cant_fire_superior_or_same_rank');
            return $this->redirectToRoute('group_index');
        }

        $entityManager = $this->getDoctrine()->getManager();
        $User->setMainGroup(null);
        $User->setMainRank(null);
        $entityManager->persist($User);
        try {
            $entityManager->flush();
        } catch (\Throwable $th) {
            if ($_ENV['APP_ENV'] === 'dev') {
                throw $th; //DEBUG
            }
            $this->addFlash('danger', 'alert_error_fire_employee');
            if (null != $Request->headers->get('referer')) {
                return $this->redirect($Request->headers->get('referer'));
            }
            return $this->redirectToRoute('group_index');
        }
        $this->addFlash('success', 'alert_success_fire_employee');
        if (null != $Request->headers->get('referer')) {
            return $this->redirect($Request->headers->get('referer'));
        }
        return $this->redirectToRoute('group_index');
    }

    #[Route('/employee/{id}', name: 'employee')]
    public function employee(User $Employee, Request $Request): Response
    {
        /**
         * @var User $currentUser
         */
        $currentUser = $this->getUser();

        $group = $currentUser->getMainGroup();
        if (!$this->IsGranted('administrate', $group)) {
            throw new AccessDeniedHttpException('granted_not_allowed_administrate_group');
        }

        //check if employee belong to user group

        if ($Employee->getMainGroup() != $currentUser->getMainGroup()) {
            throw new AccessDeniedHttpException('granted_not_allowed_administrate_other_group_employee');
        }


        $UserActualRank = $Employee->getMainRank();

        /**
         * @var User $currentUser
         */
        $currentUser = $this->getUser();

        $form = $this->createForm(EmployeeType::class, $Employee);
        $form->handleRequest($Request);

        if ($form->isSubmitted() && $form->isValid()) {
            //check if rank is modified
            if ($UserActualRank != $Employee->getMainRank()) {
                if (!$this->IsGranted('rank', $group)) {
                    $this->addFlash('warning', 'alert_error_editing_employee_rank');
                    if (null != $Request->headers->get('referer')) {
                        return $this->redirect($Request->headers->get('referer'));
                    }
                    return $this->redirectToRoute('group_employee', ['id' => $Employee->getId()]);
                }

                if (
                    $Employee == $currentUser
                ) {
                    $this->addFlash('warning', 'alert_error_editing_employee_own_rank');
                    if (null != $Request->headers->get('referer')) {
                        return $this->redirect($Request->headers->get('referer'));
                    }
                    return $this->redirectToRoute('group_employee', ['id' => $Employee->getId()]);
                }


                if (
                    $UserActualRank != null
                    && $UserActualRank->getPower() >= $currentUser->getMainRank()->getPower()
                    && !$currentUser->getAdminMode()
                ) {
                    $this->addFlash('warning', 'alert_error_editing_employee_superior_or_same_rank');
                    if (null != $Request->headers->get('referer')) {
                        return $this->redirect($Request->headers->get('referer'));
                    }
                    return $this->redirectToRoute('group_employee', ['id' => $Employee->getId()]);
                }

                if (
                    $Employee->getMainRank()->getPower() >= $currentUser->getMainRank()->getPower()
                    && !$currentUser->getAdminMode()
                ) {
                    $this->addFlash('warning', 'alert_error_setting_employee_superior_or_same_rank');
                    if (null != $Request->headers->get('referer')) {
                        return $this->redirect($Request->headers->get('referer'));
                    }
                    return $this->redirectToRoute('group_employee', ['id' => $Employee->getId()]);
                }
            }
            //end check rank modified

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($Employee);
            try {
                $entityManager->flush();
                $this->addFlash('success', 'alert_success_editing_employee');
            } catch (\Throwable $th) {
                if ($_ENV['APP_ENV'] === 'dev') {
                    throw $th; //DEBUG
                } else {
                    $this->logger->error($th);
                }
                $this->addFlash('danger', 'alert_error_editing_employee');
            }
        } elseif ($form->isSubmitted() && !$form->isValid()) {
            $this->addFlash('warning', 'alert_error_form_post');
        }

        return $this->render('group/employee.html.twig', [
            'controller_name' => 'GroupController',
            'form' => $form->createView(),
            'employee' => $Employee
        ]);
    }
}
