<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class NumberRule implements ValidationPlugin
{
    public static function id(): string { return 'number'; }
    public static function label(): string { return 'Number / range'; }
    public static function group(): string { return 'Numeric'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'integer', 'type' => 'bool', 'label' => 'Whole number only', 'default' => false],
            ['key' => 'min', 'type' => 'number', 'label' => 'Minimum', 'default' => ''],
            ['key' => 'max', 'type' => 'number', 'label' => 'Maximum', 'default' => ''],
        ];
    }

    public static function appliesTo(): array { return ['number', 'currency', 'text']; }
    public static function defaultMessage(): string { return 'Enter a valid number.'; }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $s = trim((string) $value);
        if (!is_numeric($s)) return false;
        $n = $s + 0;
        if (self::flag($params['integer'] ?? false) && floor($n) != $n) return false;
        if (($params['min'] ?? '') !== '' && is_numeric($params['min']) && $n < ($params['min'] + 0)) return false;
        if (($params['max'] ?? '') !== '' && is_numeric($params['max']) && $n > ($params['max'] + 0)) return false;
        return true;
    }

    public static function clientRule(array $params): array
    {
        $rule = ['number' => true];
        if (self::flag($params['integer'] ?? false)) $rule['integer'] = true;
        if (($params['min'] ?? '') !== '' && is_numeric($params['min'])) $rule['min'] = $params['min'] + 0;
        if (($params['max'] ?? '') !== '' && is_numeric($params['max'])) $rule['max'] = $params['max'] + 0;
        return $rule;
    }

    private static function flag(mixed $v): bool
    {
        return in_array(strtolower((string) $v), ['1', 'yes', 'true', 'on'], true);
    }
}
