<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class IpAddressRule implements ValidationPlugin
{
    public static function id(): string { return 'ip'; }
    public static function label(): string { return 'IP address'; }
    public static function group(): string { return 'Format'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'version', 'type' => 'select', 'label' => 'Version', 'options' => ['any', 'ipv4', 'ipv6'], 'default' => 'any'],
        ];
    }

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

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $v = (string) ($params['version'] ?? 'any');
        $flags = $v === 'ipv4' ? FILTER_FLAG_IPV4 : ($v === 'ipv6' ? FILTER_FLAG_IPV6 : 0);
        return filter_var(trim((string) $value), FILTER_VALIDATE_IP, $flags) !== false;
    }

    public static function clientRule(array $params): array
    {
        // IPv4 gets a client pattern; IPv6 / any is enforced server-side only.
        if (($params['version'] ?? 'any') === 'ipv4') {
            return ['pattern' => "^(25[0-5]|2[0-4]\\d|1?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}$"];
        }
        return [];
    }
}
