<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class AlphanumericRule implements ValidationPlugin
{
    public static function id(): string { return 'alphanumeric'; }
    public static function label(): string { return 'Letters & numbers'; }
    public static function group(): string { return 'Format'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'allowSpaces', 'type' => 'bool', 'label' => 'Allow spaces', 'default' => false],
        ];
    }

    public static function appliesTo(): array { return ['text']; }
    public static function defaultMessage(): string { return 'Use letters and numbers only.'; }

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

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $re = self::flag($params['allowSpaces'] ?? false) ? "/^[\\p{L}\\p{N}\\s]+$/u" : "/^[\\p{L}\\p{N}]+$/u";
        return (bool) preg_match($re, (string) $value);
    }

    public static function clientRule(array $params): array
    {
        $pat = self::flag($params['allowSpaces'] ?? false) ? "^[\\p{L}\\p{N}\\s]+$" : "^[\\p{L}\\p{N}]+$";
        return ['pattern' => $pat, 'flags' => 'u'];
    }
}
