<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin;

use CpCreation\VitiCore\Product\Model\ProductGift;
use CpCreation\VitiCore\Product\Repository\ProductGiftRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted(new Expression("is_granted('ROLE_ADMIN') or is_granted('ROLE_GIFT')"))]
#[Route('/gifts')]
class GiftController extends AbstractController
{
    public function __construct(private ProductGiftRepository $giftRepository)
    {
    }

    #[Route('', name: 'admin_gift')]
    public function index(): Response
    {
        $gifts = $this->giftRepository->findAll();

        return $this->render('@CpCreationVitiCore/admin/gift/index.html.twig', [
            'gifts' => $gifts,
        ]);
    }

    #[Route('/{id}/disable', name: 'admin_gift_disable')]
    public function disableAction(ProductGift $gift): RedirectResponse
    {
        $gift->setUsedAt(new \DateTime('now'));
        $this->giftRepository->save($gift);
        $this->giftRepository->flush();

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