<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ThirdPartyBundle\Controller;

use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\ThirdPartyBundle\Repository\ThirdPartyACLAwareRepositoryInterface;
use Chill\ThirdPartyBundle\Security\Voter\ThirdPartyVoter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;

final class ThirdPartyController extends CRUDController
{
    private readonly bool $askCenter;

    public function __construct(
        protected AuthorizationHelper $authorizationHelper,
        protected TranslatorInterface $translator,
        protected PaginatorFactory $paginatorFactory,
        protected RequestStack $requestStack,
        protected ThirdPartyACLAwareRepositoryInterface $thirdPartyACLAwareRepository,
        ParameterBagInterface $parameterBag,
    ) {
        $this->askCenter = $parameterBag->get('chill_main')['acl']['form_show_centers'];
    }

    public function generateTemplateParameter(string $action, $entity, Request $request, array $defaultTemplateParameters = [])
    {
        $defaultTemplateParameters['askCenter'] = $this->askCenter;

        return $defaultTemplateParameters;
    }

    protected function buildFilterOrderHelper(string $action, Request $request): ?FilterOrderHelper
    {
        return $this->getFilterOrderHelperFactory()
            ->create(self::class)
            ->addSearchBox(['name', 'company_name', 'acronym'])
            // ->addToggle('only-active', [])
            //    ->addOrderBy()
            ->build();
    }

    protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int
    {
        if (null === $filterOrder) {
            throw new \LogicException('filterOrder should not be null');
        }

        return $this->thirdPartyACLAwareRepository->countThirdParties(
            ThirdPartyVoter::SHOW,
            $filterOrder->getQueryString()
        );
    }

    protected function createFormFor(string $action, $entity, ?string $formClass = null, array $formOptions = []): FormInterface
    {
        if ('new' === $action) {
            return parent::createFormFor($action, $entity, $formClass, \array_merge(
                $formOptions,
                ['kind' => $this->requestStack->getCurrentRequest()->query->getAlpha('kind')]
            ));
        }

        if ('edit' === $action) {
            return parent::createFormFor($action, $entity, $formClass, \array_merge(
                $formOptions,
                ['kind' => $entity->getKind()]
            ));
        }

        return parent::createFormFor($action, $entity, $formClass, $formOptions);
    }

    protected function getQueryResult(string $action, Request $request, int $totalItems, PaginatorInterface $paginator, ?FilterOrderHelper $filterOrder = null)
    {
        return $this->thirdPartyACLAwareRepository
            ->listThirdParties(
                ThirdPartyVoter::SHOW,
                $filterOrder->getQueryString(),
                ['name' => 'ASC'],
                $paginator->getItemsPerPage(),
                $paginator->getCurrentPageFirstItemNumber()
            );
    }

    protected function onPostCheckACL($action, Request $request, $entity): ?Response
    {
        if ('edit' === $action || 'view' === $action) {
            if ($entity->isChild()) {
                throw $this->createAccessDeniedException();
            }
        }

        if ('new' === $action) {
            if (!$request->query->has('kind')) {
                return $this->render('@ChillThirdParty/ThirdParty/new_pick_kind.html.twig');
            }
            $kind = $request->query->getAlpha('kind', '');

            if (!(ThirdParty::KIND_COMPANY === $kind || ThirdParty::KIND_CONTACT === $kind)) {
                throw new BadRequestHttpException('This kind is not supported: '.$kind);
            }

            $entity->setKind($kind);
        }

        return null;
    }

    /**
     * @param ThirdParty $entity
     */
    protected function onPostFetchEntity($action, Request $request, $entity): ?Response
    {
        if ('view' === $action && $entity->getParent() instanceof ThirdParty) {
            $params = [
                'id' => $entity->getParent()->getId(),
            ];

            if ($request->query->has('returnPath')) {
                $params['returnPath'] = $request->query->get('returnPath');
            }

            if ($request->query->has('returnLabel')) {
                $params['returnLabel'] = $request->query->get('returnLabel');
            }

            return $this->redirectToRoute('chill_crud_3party_3party_view', $params);
        }

        return null;
    }
}
