<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Form\Filter\Offer;

use Doctrine\ORM\QueryBuilder;
use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Ferienpass\AdminBundle\Form\Filter\AsSubFilter;
use Ferienpass\CoreBundle\Enum\OfferStatus;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

#[AsSubFilter(key: 'offerStatus', section: 'status', priority: 60, views: ['admin_offers_index'])]
class StatusFilter extends AbstractFilterType
{
    public function __construct(private readonly TranslatorInterface $translator)
    {
    }

    public function getParent(): string
    {
        return ChoiceType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'choices' => [OfferStatus::DRAFT, OfferStatus::FINALIZED, OfferStatus::REVIEWED, OfferStatus::PUBLISHED, OfferStatus::CANCELLED, OfferStatus::COMPLETED],
            'choice_label' => static fn (string $choice): TranslatableMessage => new TranslatableMessage('offers.status.'.$choice, [], 'admin'),
            'placeholder' => '-',
            'expanded' => true,
            'multiple' => true,
        ]);
    }

    public function apply(QueryBuilder $qb, FormInterface $form): void
    {
        if ($form->isEmpty()) {
            return;
        }

        $k = $form->getName();
        $v = (array) $form->getData();

        if (empty($v)) {
            return;
        }

        $or = $qb->expr()->orX();
        foreach ($v as $i => $status) {
            $or->add("JSON_CONTAINS_PATH(i.status, 'one', CONCAT('$.', :q_{$k}{$i})) = 1");
            $qb->setParameter("q_{$k}{$i}", $status);
        }

        $qb->andWhere($or);
    }

    protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        $data = (array) $form->getData();
        if (empty($data)) {
            return null;
        }

        return implode(', ', array_map(fn ($status) => $this->translator->trans('offers.status.'.$status, [], 'admin'), $data));
    }
}
