<?php

namespace App\Handlers\Forms;


use App\Entity\Properties\Charge;
use App\Managers\ManagersInterface;
use Symfony\Component\Form\FormInterface;
use App\Interfaces\NotificationsInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class ChargesHandle
{
    public function __construct(
        private NotificationsInterface $notifications,
        private ManagersInterface $managers
    ) {}

    public function handleBienForm(FormInterface $form): JsonResponse
    {
        if ($form->isValid()) {
            return $this->handleValidForm($form);
        } else {
            return $this->handleInvalidForm($form);
        }
    }

    private function handleValidForm(FormInterface $form): JsonResponse
    {
        /** @var Charge $charge */
        $charge = $form->getData();
        if ($charge->getId()) {

            $this->managers->setEntity($charge, 'edit');
            $this->notifications->save(
                "Modification de la charge #{$charge->getType()}",
                "Modification",
                $charge,
                "pencil5",
                "orange",
                $charge->getCompanyId()
            );
            $msg = 'Charge modifiée avec succès.';
        } else {
            $this->managers->setEntity($charge, 'new');
            $this->notifications->save(
                "Nouvelle charge #{$charge->getType()}",
                "Création",
                $charge,
                "plus",
                "green",
                $charge->getCompanyId()
            );
            $msg = 'Charge ajoutée avec succès.';
        }

        return new JsonResponse([
            'code' => Charge::CHARGE_ADD_SUCCESSFULLY,
            'msg' => $msg,
        ]);
    }

    private function handleInvalidForm(FormInterface $form): JsonResponse
    {

        return new JsonResponse([
            'code' => Charge::CHARGE_INVALID_FORM,
            'errors' => $this->getErrorsMessages($form)
        ]);
    }

    private function getErrorsMessages(FormInterface $form): array
    {
        $errors = [];

        foreach ($form->getErrors() as $error) {
            $errors[] = $error->getMessage();
        }

        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorsMessages($child);
            }
        }
        return $errors;
    }
}
