<?php
declare(strict_types=1);

/**
 * This source file is available under the terms of the
 * Pimcore Open Core License (POCL)
 * Full copyright and license information is available in
 * LICENSE.md which is distributed with this source code.
 *
 *  @copyright  Copyright (c) Pimcore GmbH (https://www.pimcore.com)
 *  @license    Pimcore Open Core License (POCL)
 */

namespace Pimcore\Bundle\AdminBundle\Controller\Admin\DataObject;

use Pimcore\Bundle\AdminBundle\Controller\AdminAbstractController;
use Pimcore\Bundle\AdminBundle\Helper\GridHelperService;
use Pimcore\Bundle\AdminBundle\Security\CsrfProtectionHandler;
use Pimcore\Helper\ParameterBagHelper;
use Pimcore\Localization\LocaleServiceInterface;
use Pimcore\Model\DataObject;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
 * @internal
 */
#[Route('/variants', name: 'pimcore_admin_dataobject_variants_')]
class VariantsController extends AdminAbstractController
{
    use DataObjectActionsTrait;

    #[Route('/update-key', name: 'updatekey', methods: ['PUT'])]
    public function updateKeyAction(Request $request): JsonResponse
    {
        $id = ParameterBagHelper::getInt($request->request, 'id');
        $key = $request->request->get('key');
        $object = DataObject\Concrete::getById($id);

        return $this->adminJson($this->renameObject($object, $key));
    }

    /**
     * @throws \Exception
     */
    #[Route('/get-variants', name: 'getvariants', methods: ['GET', 'POST'])]
    public function getVariantsAction(
        Request $request,
        EventDispatcherInterface $eventDispatcher,
        GridHelperService $gridHelperService,
        LocaleServiceInterface $localeService,
        CsrfProtectionHandler $csrfProtection
    ): JsonResponse {
        $parentObject = DataObject\Concrete::getById((int) $request->get('objectId'));
        if (empty($parentObject)) {
            throw new \Exception('No Object found with id ' . $request->get('objectId'));
        }

        if (!$parentObject->isAllowed('view')) {
            throw new \Exception('Permission denied');
        }

        $allParams = array_merge($request->request->all(), $request->query->all());
        $allParams['folderId'] = $parentObject->getId();
        $allParams['classId'] = $parentObject->getClassId();

        $csrfProtection->checkCsrfToken($request);

        $result = $this->gridProxy(
            $allParams,
            DataObject::OBJECT_TYPE_VARIANT,
            $request,
            $eventDispatcher,
            $gridHelperService,
            $localeService
        );

        return $this->adminJson($result);
    }
}
