<?php

namespace App\Handlers\Forms;

use App\Entity\Acteurs\Proprietaires;
use App\Interfaces\NotificationsInterface;
use App\Managers\ManagersInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

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

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

    private function handleValidForm(FormInterface $form): JsonResponse
    {
        /** @var Proprietaires $proprietaire */
        $proprietaire = $form->getData();
        if ($proprietaire->getId()) {
            $this->managers->setEntity($proprietaire, 'edit');
            $this->notifications->save(
                "Modification du propriétaire #{$proprietaire->getName()}",
                "Modification",
                $proprietaire,
                "pencil5",
                "orange",
                $proprietaire->getCompanyId()
            );
            $msg = 'Propriétaire modifié avec succès.';
        } else {
            $this->managers->setEntity($proprietaire, 'new');
            $this->notifications->save(
                "Nouveau propriétaire #{$proprietaire->getName()}",
                "Création",
                $proprietaire,
                "plus",
                "green",
                $proprietaire->getCompanyId()
            );
            $msg = 'Propriétaire ajouté avec succès.';
        }

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

    private function handleInvalidForm(FormInterface $form): JsonResponse
    {

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