<?php

namespace GriffinForms\Frontend\Security\FormValidations;

class Manager
{
    /**
     * @var array<int,ValidationInterface>
     */
    protected $validators = [];

    /**
     * @param array<int,ValidationInterface|string> $validators
     */
    public function __construct(array $validators = [])
    {
        if (empty($validators)) {
            $this->registerValidator(new AccountRegistration());
            return;
        }

        foreach ($validators as $validator) {
            $this->registerValidator($validator);
        }
    }

    /**
     * @param ValidationInterface|string $validator
     */
    public function registerValidator($validator): void
    {
        if (is_string($validator)) {
            if (!class_exists($validator)) {
                return;
            }
            $validator = new $validator();
        }

        if (!$validator instanceof ValidationInterface) {
            return;
        }

        $this->validators[] = $validator;
    }

    public function validate(int $form_id, array $context = []): array
    {
        if ($form_id <= 0 || empty($this->validators)) {
            return [];
        }

        usort($this->validators, function (ValidationInterface $a, ValidationInterface $b) {
            return $a->getPriority() <=> $b->getPriority();
        });

        $errors = [];

        foreach ($this->validators as $validator) {
            $validator_errors = $validator->validate($form_id, $context);
            if (empty($validator_errors) || !is_array($validator_errors)) {
                continue;
            }

            foreach ($validator_errors as $field_id => $field_errors) {
                if (!isset($errors[$field_id]) || !is_array($errors[$field_id])) {
                    $errors[$field_id] = [];
                }

                if (!is_array($field_errors)) {
                    $errors[$field_id][] = $field_errors;
                    continue;
                }

                foreach ($field_errors as $iteration_index => $iteration_errors) {
                    if (!isset($errors[$field_id][$iteration_index]) || !is_array($errors[$field_id][$iteration_index])) {
                        $errors[$field_id][$iteration_index] = [];
                    }

                    if (!is_array($iteration_errors)) {
                        $errors[$field_id][$iteration_index][] = $iteration_errors;
                        continue;
                    }

                    $errors[$field_id][$iteration_index] = array_values(array_unique(array_merge(
                        $errors[$field_id][$iteration_index],
                        $iteration_errors
                    )));
                }
            }
        }

        return $errors;
    }
}
