<?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\TicketBundle\Controller\Admin;

use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\TicketBundle\Entity\Motive;
use Chill\TicketBundle\MotiveDTO;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

class MotiveController extends CRUDController
{
    protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
    {
        /* @var QueryBuilder $query */
        $query->addOrderBy('e.ordering', 'ASC');

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

    protected function createFormFor(string $action, mixed $entity, ?string $formClass = null, array $formOptions = []): FormInterface
    {
        if (in_array($action, ['new', 'edit'], true) && $entity instanceof Motive) {
            $dto = MotiveDTO::fromMotive($entity);

            return parent::createFormFor($action, $dto, $formClass, $formOptions);
        }

        return parent::createFormFor($action, $entity, $formClass, $formOptions);
    }

    protected function onFormValid(string $action, object $entity, FormInterface $form, Request $request): void
    {
        if (in_array($action, ['new', 'edit'], true) && $entity instanceof Motive) {
            $dto = $form->getData();
            if ($dto instanceof MotiveDTO) {
                $dto->applyToMotive($entity);
            }
        }

        parent::onFormValid($action, $entity, $form, $request);
    }
}
