<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class CreditCardRule implements ValidationPlugin
{
    public static function id(): string { return 'creditCard'; }
    public static function label(): string { return 'Credit card (Luhn)'; }
    public static function group(): string { return 'Format'; }
    public static function paramsSchema(): array { return []; }
    public static function appliesTo(): array { return ['text', 'number']; }
    public static function defaultMessage(): string { return 'Enter a valid card number.'; }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $digits = preg_replace('/\D+/', '', (string) $value);
        $len = strlen((string) $digits);
        if ($len < 12 || $len > 19) return false;
        return self::luhn((string) $digits);
    }

    public static function clientRule(array $params): array
    {
        return ['luhn' => true];
    }

    private static function luhn(string $number): bool
    {
        $sum = 0; $alt = false;
        for ($i = strlen($number) - 1; $i >= 0; $i--) {
            $n = (int) $number[$i];
            if ($alt) { $n *= 2; if ($n > 9) $n -= 9; }
            $sum += $n; $alt = !$alt;
        }
        return $sum % 10 === 0;
    }
}
