<?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;

use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
use Symfony\Component\OptionsResolver\OptionsResolver;

class OffersFilter extends AbstractFilter
{
    public function __construct(#[AutowireIterator('ferienpass_admin.sub_filter', indexAttribute: 'key', defaultPriorityMethod: 'getPriority')] iterable $filterTypes, private readonly Security $security)
    {
        $this->filterTypes = [];
        foreach ($filterTypes as $key => $filter) {
            if ($filter instanceof AbstractFilterType) {
                $this->filterTypes[$key] = $filter;
            }
        }
    }

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

        $resolver->setDefaults([
            'label_format' => 'offers.filter.%name%',
        ]);
    }

    protected function getSorting(): array
    {
        $return = [];
        $return[] = [
            'date' => static fn (QueryBuilder $qb) => $qb->addOrderBy('d.begin', 'ASC'),
            'date_desc' => static fn (QueryBuilder $qb) => $qb->addOrderBy('d.begin', 'DESC'),
            'name' => static fn (QueryBuilder $qb) => $qb->addOrderBy('i.name', 'ASC'),
            'edition' => static fn (QueryBuilder $qb) => $qb->addOrderBy('e.name', 'ASC'),
        ];

        if ($this->security->isGranted('ROLE_ADMIN')) {
            $return[] = [
                'host' => static fn (QueryBuilder $qb) => $qb->addOrderBy('h.name', 'ASC'),
                // 'status' => fn (QueryBuilder $qb) => $qb->addOrderBy('i.state', 'ASC')->addOrderBy('i.name', 'ASC'),
            ];
        }

        return array_merge(...$return);
    }
}
