<?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\PersonBundle\Controller\SocialWork;

use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Chill\PersonBundle\Repository\SocialWork\ResultRepository;
use Symfony\Component\HttpFoundation\Request;

class ResultController extends CRUDController
{
    public function __construct(private readonly ResultRepository $repository) {}

    protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
    {
        $query->addOrderBy('e.id', 'ASC');

        return parent::orderQuery($action, $query, $request, $paginator);
    }

    protected function getQueryResult(
        string $action,
        Request $request,
        int $totalItems,
        PaginatorInterface $paginator,
        ?FilterOrderHelper $filterOrder = null,
    ) {
        if (0 === $totalItems) {
            return [];
        }

        if (!$filterOrder instanceof FilterOrderHelper) {
            return parent::getQueryResult($action, $request, $totalItems, $paginator, $filterOrder);
        }

        $queryString = $filterOrder->getQueryString();
        $activeFilter = $filterOrder->getCheckboxData('activeFilter');
        $nb = $this->repository->countFilteredResults($queryString, $activeFilter);

        $paginator = $this->getPaginatorFactory()->create($nb);

        return $this->repository->findFilteredResults(
            $queryString,
            $activeFilter,
            $paginator->getCurrentPageFirstItemNumber(),
            $paginator->getItemsPerPage()
        );
    }

    protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int
    {
        if (!$filterOrder instanceof FilterOrderHelper) {
            return parent::countEntities($action, $request, $filterOrder);
        }

        return $this->repository->countFilteredResults(
            $filterOrder->getQueryString(),
            $filterOrder->getCheckboxData('activeFilter')
        );
    }

    protected function buildFilterOrderHelper(string $action, Request $request): ?FilterOrderHelper
    {
        return $this->getFilterOrderHelperFactory()
            ->create(self::class)
            ->addSearchBox(['label'])
            ->addCheckbox('activeFilter', [true => 'Active', false => 'Inactive'], ['Active'])
            ->build();
    }
}
