<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Controller;

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


class DefaultController extends AbstractController
{
    /**
     * @Route("/getgre", name="homepage")
     */
    public function indexAction(Request $request, Security $security, AuthenticationUtils $helper): Response
    {

        // if user is already logged in, don't display the login page again
        if ($security->isGranted('ROLE_USER')) {
            return $this->redirectToRoute('list_agents');
        }

        // this statement solves an edge-case: if you change the locale in the login
        // page, after a successful login you are redirected to a page in the previous
        // locale. This code regenerates the referrer URL whenever the login page is
        // browsed, to ensure that its locale is always the current one.
        $this->saveTargetPath($request->getSession(), 'main', $this->generateUrl('list_agents'));

        return $this->render('security/login.html.twig', [
            // last username entered by the user (if any)
            'last_username' => $helper->getLastUsername(),
            // last authentication error (if any)
            'error' => $helper->getLastAuthenticationError(),
        ]);
    }

    /**
     * @Route("/check_expiration_lock/{id}", methods={"GET"}, name="check_expiration_lock")
     */
    public function checkExpirationLock(LockEntites $lock =null) {
        if (is_null($lock)) {
            $isExpired = true;
        } else {
            $lockDuration = 3600; // Durée du lock en secondes (exemple : 5 minutes)
            $lockStart = $lock->getDateDebut()->getTimestamp();
            $now = time();

            $isExpired = ($now - $lockStart) > $lockDuration;
        }

        return new JsonResponse(['expired' => $isExpired]);
    }
}
