<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class AlphaRule implements ValidationPlugin
{
    public static function id(): string { return 'alpha'; }
    public static function label(): string { return 'Letters only'; }
    public static function group(): string { return 'Format'; }

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

    public static function appliesTo(): array { return ['text']; }
    public static function defaultMessage(): string { return 'Use letters 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'] ?? true) ? "/^[\\p{L}\\s]+$/u" : "/^\\p{L}+$/u";
        return (bool) preg_match($re, (string) $value);
    }

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