<?php

namespace App\Handlers\Forms;

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

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

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

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

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

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

    private function handleInvalidForm(FormInterface $form): JsonResponse {

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