<?php
/**
 * @author Daniel Knudsen <d.knudsen@spawntree.de>
 * @date 10.06.24
 */


namespace App\Filter;

use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ApiPlatform\Metadata\ApiFilter;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;

#[ApiFilter(UserNameSearchFilter::class)]
class UserNameSearchFilter extends AbstractFilter
{
    public const FILTER_NAME = "userNameSearch";

    public function __construct(ManagerRegistry $managerRegistry, ?LoggerInterface $logger = null, ?array $properties = null)
    {
        parent::__construct($managerRegistry, $logger, $properties);
    }

    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?\ApiPlatform\Metadata\Operation $operation = null, array $context = []): void
    {
        if ($property !== self::FILTER_NAME) {
            return;
        }

        if ($value) {
            // Alias für User-Tabelle
            $rootAlias = $queryBuilder->getRootAliases()[0];

            // Case-insensitive Suche nach Vorname oder Nachname, der den Wert enthält
            $queryBuilder->andWhere(
                $queryBuilder->expr()->orX(
                    $queryBuilder->expr()->like('LOWER(' . $rootAlias . '.firstName)', ':searchTerm'),
                    $queryBuilder->expr()->like('LOWER(' . $rootAlias . '.lastName)', ':searchTerm')
                )
            )
            ->setParameter('searchTerm', '%' . strtolower($value) . '%');
        }
    }

    public function getDescription(string $resourceClass): array
    {
        return [
            self::FILTER_NAME => [
                'property' => 'firstLastName',
                'type' => 'string',
                'required' => false,
                'openapi' => [
                    'description' => 'Filter user names that have the search term in their first name or last name',
                    'type' => 'string',
                ],
            ],
        ];
    }

}