<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class RegexRule implements ValidationPlugin
{
    public static function id(): string { return 'regex'; }
    public static function label(): string { return 'Regular expression'; }
    public static function group(): string { return 'Advanced'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'pattern', 'type' => 'text', 'label' => 'Pattern (no slashes)', 'default' => '', 'placeholder' => 'e.g. ^[A-Z]{2}\\d{4}$'],
            ['key' => 'flags', 'type' => 'text', 'label' => 'Flags', 'default' => '', 'placeholder' => 'e.g. i'],
        ];
    }

    public static function appliesTo(): array { return []; }
    public static function defaultMessage(): string { return 'Value does not match the required format.'; }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $pattern = (string) ($params['pattern'] ?? '');
        if ($pattern === '') return true; // nothing configured → nothing to fail
        // Only PCRE flags that are safe here; strip delimiters the user may add.
        $flags = preg_replace('/[^imsuxADSUXJ]/', '', (string) ($params['flags'] ?? ''));
        $delimited = '/' . str_replace('/', '\\/', $pattern) . '/' . $flags;
        $r = @preg_match($delimited, (string) $value);
        if ($r === false) return true; // invalid pattern → don't block the save
        return $r === 1;
    }

    public static function clientRule(array $params): array
    {
        $pattern = (string) ($params['pattern'] ?? '');
        if ($pattern === '') return [];
        return ['pattern' => $pattern, 'flags' => preg_replace('/[^imsuy]/', '', (string) ($params['flags'] ?? ''))];
    }
}
