<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Form\Action\Validate;

use ZOOlanders\YOOessentials\Condition\ConditionResolver;
use ZOOlanders\YOOessentials\Condition\ConditionManager;
use ZOOlanders\YOOessentials\Form\Action\StandardAction;
use ZOOlanders\YOOessentials\Form\Http\FormSubmissionResponse;
use ZOOlanders\YOOessentials\Logger;
use ZOOlanders\YOOessentials\Util;

class ValidateAction extends StandardAction
{
    public const NAME = 'validate';

    public function __invoke(FormSubmissionResponse $response, callable $next): FormSubmissionResponse
    {
        $config = $this->getConfig();
        $validation = Util\Prop::filterByPrefix($config, 'validation_');

        if (empty($validation['conditions'])) {
            return $next($response);
        }

        $conditions = array_map(function ($condition) {
            return (object) $condition;
        }, $validation['conditions']);

        $query = $validation['mode'] ?? null;

        if ($query === ConditionManager::MODE_CUSTOM) {
            $query = $validation['mode_query'] ?? null;
        }

        if (!$query) {
            $query = ConditionManager::MODE_AND;
        }

        /** @var Logger $logger */
        $logger = new Logger('access');

        /** @var ConditionResolver $resolver */
        $resolver = (new ConditionResolver($conditions))->withQuery($query)->withLogger($logger);

        $valid = $resolver->resolve(new \stdClass(), []);

        if (!$valid) {
            return $response->withErrors([$config['message'] ?? 'Validation Error']);
        }

        return $next($response);
    }
}
