<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Service\Form;

use Paysera\PrestashopPayments\Service\FlashMessageHandler;
use PrestaShop\PrestaShop\Core\Form\Handler;
use Symfony\Component\Form\FormInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

class FormSubmissionHandler
{
    public function __construct(
        private TranslatorInterface $translator
    ) {
    }

    public function handleSubmission(
        FormInterface $form,
        Handler $formHandler,
        FlashMessageHandler $flashHandler,
        string $successMessage
    ): void {
        if ($form->isValid()) {
            $this->handleValidForm($form, $formHandler, $flashHandler, $successMessage);

            return;
        }

        $this->handleInvalidForm($form, $flashHandler);
    }

    private function handleValidForm(
        FormInterface $form,
        Handler $formHandler,
        FlashMessageHandler $flashHandler,
        string $successMessage
    ): void {
        $errors = $formHandler->save($form->getData());

        if (count($errors) === 0) {
            $flashHandler->addSuccess(
                $this->translator->trans($successMessage, [], \PayseraPayments::TRANSLATION_DOMAIN)
            );

            return;
        }

        $translatedErrors = array_map(
            fn ($error) => $this->translator->trans($error, [], \PayseraPayments::TRANSLATION_DOMAIN),
            $errors
        );
        $flashHandler->addErrors($translatedErrors);
    }

    private function handleInvalidForm(
        FormInterface $form,
        FlashMessageHandler $flashHandler
    ): void {
        $errorMessages = [];
        foreach ($form->getErrors(true) as $error) {
            $errorMessages[] = $error->getMessage();
        }

        $flashHandler->addErrors($errorMessages);
    }
}
