<?php

namespace App\Handlers\Forms;

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

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

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

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

            $this->managers->setEntity($demarcheur, 'edit');
            $this->notifications->save(
                "Modification du démarcheur #{$demarcheur->getNom()}",
                "Modification",
                $demarcheur,
                "pencil5",
                "orange",
                $this->getUser()->getCompanyId()
            );
            $msg = 'Propriété modifiée avec succès.';
        } else {
            $this->managers->setEntity($demarcheur, 'new');
            $this->notifications->save(
                "Nouveau demarcheur #{$demarcheur->getNom()}",
                "Création",
                $demarcheur,
                "plus",
                "green",
                $this->getUser()->getCompanyId()
            );
            $msg = 'Demarcheur ajoutée avec succès.';
        }

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

    private function handleInvalidForm(FormInterface $form): JsonResponse
    {

        return new JsonResponse([
            'code' => Demarcheur::DEMARCHEUR_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;
    }
}
