<?php

namespace Jaga\Tools\Validator;

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

/**
 * Class Min
 * Checks if a value is lower than min
 *
 * <code>
 * use Phalcon\Validation;
 * use Jaga\Tools\Validator\Min;
 *
 * $validator = new Validation();
 *
 * $validator->add(
 *     "year",
 *     new Min(
 *         [
 *             "min" => 1945,
 *             "message" => "Year must be more than or equal to 1945",
 *         ]
 *     )
 * );
 *
 * $validator->add(
 *     [
 *         "startmonth",
 *         "startyear",
 *     ],
 *     new Min(
 *         [
 *             "min" => [
 *                 "startmonth" => 1,
 *                 "startyear"  => 1945,
 *             ],
 *             "message" => [
 *                 "terms"        => "Month must be more than or equal to 1",
 *                 "anotherTerms" => "Year must be more than or equal to 1945",
 *             ],
 *         ]
 *     )
 * );
 * </code>
 */
class Min extends Validator
{
    /**
     * Executes the validation
     */
    public function validate(Validation $validation, $field): bool
    {
        $min = $this->getOption('min', false);

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

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

        if ($value >= $min) {
            return true;
        }

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

        return false;
    }
}
