<?php

namespace Jaga\Tools\Validator;

use Phalcon\Validation;
use Phalcon\Validation\Message;
use Phalcon\Validation\Validator;

/**
 * Class Max
 * Checks if a value is lower than max
 *
 * <code>
 * use Phalcon\Validation;
 * use Jaga\Tools\Validator\Max;
 *
 * $validator = new Validation();
 *
 * $validator->add(
 *     "year",
 *     new Max(
 *         [
 *             "max" => 2020,
 *             "message" => "Year must be less than or equal to 2020. Are you coming from the future?",
 *         ]
 *     )
 * );
 *
 * $validator->add(
 *     [
 *         "endmonth",
 *         "endyear",
 *     ],
 *     new Max(
 *         [
 *             "max" => [
 *                 "endmonth" => 12,
 *                 "endyear"  => 2020,
 *             ],
 *             "message" => [
 *                 "terms"        => "Year must be more than or equal to 12",
 *                 "anotherTerms" => "Year must be more than or equal to 2020. Are you coming from the future?",
 *             ],
 *         ]
 *     )
 * );
 * </code>
 */
class Max extends Validator
{
    /**
     * Executes the validation
     */
    public function validate(Validation $validation, $field): bool
    {
        $max = $this->getOption('max', false);

        $value = $validation->getValue($field);

        $valid = (is_numeric($value) && $value <= $max) ||
            (is_string($value) && $max >= 0 && strlen($value) <= $max) ||
            (is_array($value) && $max >= 0 && count($value) <= $max);

        if ($value <= $max) {
            return true;
        }

        $message = $this->getOption('message');
        $validation->appendMessage(
            new Message(
                $message, 
                $field
            )
        );

        return false;
    }
}
