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

use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class ClosingMotiveController
 * Controller for closing motives.
 */
class ClosingMotiveController extends CRUDController
{
    public function __construct(private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    /**
     * @param string $action
     */
    protected function createEntity($action, Request $request): object
    {
        $entity = parent::createEntity($action, $request);

        if ($request->query->has('parent_id')) {
            $parentId = $request->query->getInt('parent_id');

            $parent = $this->managerRegistry->getManager()
                ->getRepository($this->getEntityClass())
                ->find($parentId);

            if (null === $parent) {
                throw $this->createNotFoundException('parent id not found');
            }

            $entity->setParent($parent);
        }

        return $entity;
    }

    /**
     * @param \Doctrine\ORM\QueryBuilder|mixed $query
     *
     * @return \Doctrine\ORM\QueryBuilder|mixed
     */
    protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
    {
        /* @var \Doctrine\ORM\QueryBuilder $query */
        return $query->orderBy('e.ordering', 'ASC');
    }
}
