<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class FullNameRule implements ValidationPlugin
{
    public static function id(): string { return 'fullName'; }
    public static function label(): string { return 'Full name (min words)'; }
    public static function group(): string { return 'Format'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'minWords', 'type' => 'number', 'label' => 'Minimum words', 'default' => 2],
        ];
    }

    public static function appliesTo(): array { return ['text']; }
    public static function defaultMessage(): string { return 'Enter at least {minWords} words (e.g. first and last name).'; }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $min = max(1, (int) ($params['minWords'] ?? 2));
        $words = preg_split('/\s+/u', trim((string) $value), -1, PREG_SPLIT_NO_EMPTY) ?: [];
        if (count($words) < $min) return false;
        // Each word: letters (unicode), apostrophes and hyphens only.
        foreach ($words as $w) {
            if (!preg_match("/^[\\p{L}'\\-]+$/u", $w)) return false;
        }
        return true;
    }

    public static function clientRule(array $params): array
    {
        return ['words' => max(1, (int) ($params['minWords'] ?? 2))];
    }
}
