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

use Chill\PersonBundle\CRUD\Controller\EntityPersonCRUDController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Chill\JobBundle\Entity\Immersion;
use Symfony\Component\HttpFoundation\Response;

/**
 * CRUD Controller for reports (Frein, ...).
 */
class ImmersionCrudController extends EntityPersonCRUDController
{
    protected function onBeforeRedirectAfterSubmission(string $action, $entity, FormInterface $form, Request $request): ?Response
    {
        $next = $request->request->get('submit', 'save-and-close');

        return match ($next) {
            'save-and-close', 'delete-and-close' => $this->redirectToRoute('chill_job_report_index', [
                'person' => $entity->getPerson()->getId(),
            ]),
            default => parent::onBeforeRedirectAfterSubmission($action, $entity, $form, $request),
        };
    }

    protected function createFormFor(string $action, $entity, ?string $formClass = null, array $formOptions = []): FormInterface
    {
        if ($entity instanceof Immersion) {
            if ('edit' === $action || 'new' === $action) {
                return parent::createFormFor($action, $entity, $formClass, [
                    'center' => $entity->getPerson()->getCenter(),
                ]);
            }
            if ('bilan' === $action) {
                return parent::createFormFor($action, $entity, $formClass, [
                    'center' => $entity->getPerson()->getCenter(),
                    'step' => 'bilan',
                ]);
            }
            if ('delete' === $action) {
                return parent::createFormFor($action, $entity, $formClass, $formOptions);
            }
            throw new \LogicException("this step {$action} is not supported");
        }

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

    protected function onPreFlush(string $action, $entity, FormInterface $form, Request $request)
    {
        // for immersion / edit-bilan action
        if ('bilan' === $action) {
            /* @var $entity Immersion */
            $entity->setIsBilanFullfilled(true);
        }

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

    /**
     * Edit immersion bilan.
     *
     * @param int $id
     */
    public function bilan(Request $request, $id): Response
    {
        return $this->formEditAction('bilan', $request, $id);
    }
}
