<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class ValidIpOrCidr implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $v = is_string($value) ? trim($value) : '';

        if (filter_var($v, FILTER_VALIDATE_IP) !== false) {
            return;
        }

        if (! str_contains($v, '/')) {
            $fail(__('settings.lp_whitelist_invalid', ['value' => $v]));

            return;
        }

        [$ip, $mask] = explode('/', $v, 2);
        $max = str_contains($ip, ':') ? 128 : 32;
        if (filter_var($ip, FILTER_VALIDATE_IP) === false || ! ctype_digit($mask) || (int) $mask < 0 || (int) $mask > $max) {
            $fail(__('settings.lp_whitelist_invalid', ['value' => $v]));
        }
    }
}
