<?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\CmsBundle\Filter\Type\Offer;

use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
 * Multi-value age filter.
 *
 * URL forms:
 *   ?alter=7                   single numeric age (legacy, still supported)
 *   ?alter[]=7&alter[]=14      multiple numeric ages
 *   ?alter[]=3-6&alter[]=16+   age bands (lower-upper, or "<n>+")
 *
 * Each value is OR'd: an offer matches if its [minAge,maxAge] range covers
 * any one of the requested ages/bands.
 */
class AgeType extends AbstractOfferFilterType
{
    public static function getName(): string
    {
        return 'alter';
    }

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

    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'label' => 'Alter',
            'compound' => false,
            'multiple' => true,
            'empty_data' => null,
        ]);
    }

    public function apply(QueryBuilder $qb, FormInterface $form): void
    {
        $values = self::normalize($form->getData());
        if ([] === $values) {
            return;
        }

        $k = $form->getName();
        $orParts = [];
        $i = 0;
        foreach ($values as $value) {
            if (preg_match('/^(\d+)\s*-\s*(\d+)$/', $value, $m)) {
                $low = (int) $m[1];
                $high = (int) $m[2];
            } elseif (preg_match('/^(\d+)\+$/', $value, $m)) {
                $low = (int) $m[1];
                $high = 99;
            } elseif (ctype_digit($value)) {
                $low = $high = (int) $value;
            } else {
                continue;
            }

            $orParts[] = \sprintf(
                '(o.minAge IS NULL OR o.minAge = 0 OR o.minAge <= :q_%s_h_%d) AND (o.maxAge IS NULL OR o.maxAge = 0 OR o.maxAge >= :q_%s_l_%d)',
                $k,
                $i,
                $k,
                $i,
            );
            $qb->setParameter('q_'.$k.'_l_'.$i, $low);
            $qb->setParameter('q_'.$k.'_h_'.$i, $high);
            ++$i;
        }

        if ([] === $orParts) {
            return;
        }

        $qb->andWhere($qb->expr()->orX(...array_map(static fn (string $p) => '('.$p.')', $orParts)));
    }

    public function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        $values = self::normalize($form->getData());
        if ([] === $values) {
            return null;
        }

        return new TranslatableMessage('offerList.filter.age', ['value' => implode(', ', $values)]);
    }

    /**
     * @return list<string>
     */
    private static function normalize(mixed $value): array
    {
        if (null === $value || '' === $value) {
            return [];
        }

        $arr = \is_array($value) ? $value : [$value];
        $out = [];
        foreach ($arr as $v) {
            if (null === $v || '' === $v) {
                continue;
            }
            $out[] = (string) $v;
        }

        return $out;
    }
}
