<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class PhoneRule implements ValidationPlugin
{
    public static function id(): string { return 'phone'; }
    public static function label(): string { return 'Phone / Mobile'; }
    public static function group(): string { return 'Format'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'minDigits', 'type' => 'number', 'label' => 'Min digits', 'default' => 7],
            ['key' => 'maxDigits', 'type' => 'number', 'label' => 'Max digits', 'default' => 15],
        ];
    }

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

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $raw = trim((string) $value);
        // Allowed surface characters only (digits, spaces, + ( ) - .)
        if (!preg_match('/^[+()\-.\s0-9]+$/', $raw)) return false;
        $digits = preg_replace('/\D+/', '', $raw);
        $len = strlen((string) $digits);
        $min = (int) ($params['minDigits'] ?? 7);
        $max = (int) ($params['maxDigits'] ?? 15);
        return $len >= $min && $len <= $max;
    }

    public static function clientRule(array $params): array
    {
        return ['phone' => ['min' => (int) ($params['minDigits'] ?? 7), 'max' => (int) ($params['maxDigits'] ?? 15)]];
    }
}
