<?php

namespace App\Controller;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    /**
     * @Route("/admin/login", name="admin_login")
     * @param AuthenticationUtils $authenticationUtils
     * @param Request $request
     * @return Response
     */
    public function login (AuthenticationUtils $authenticationUtils, Request $request): Response
    {
        if ($this->getUser())
        {
            if (
                    $this->isGranted(User::ROLE_ADMIN) or
                    $this->isGranted(User::ROLE_SUPER_ADMIN) or
                    $this->isGranted(User::ROLE_STORE) or
                    $this->isGranted(User::ROLE_STORE_ADMIN)
                )
            {
                return $this->redirectToRoute('admin', [], 301);
            }
            return $this->redirect($request->getBaseUrl() . '/', 301);
        }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
    }


    /**
     * @Route("/logout", name="app_logout", methods={"GET"})
     */
    public function logout ()
    {
        // controller can be blank: it will never be executed!
        throw new \Exception('Don\'t forget to activate logout in security.yaml');
    }
}