<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class OfferUrlTemplate implements Rule
{
    public function passes($attribute, $value): bool
    {
        if ($value === null || $value === '') {
            return true;
        }

        $allowed = [
            '{user_id}', '{USER_ID}', '{uid}', '{UID}', '{subid}', '{SUBID}',
            '{username}', '{USERNAME}', '{email}', '{EMAIL}',
        ];
        $normalized = str_replace($allowed, 'example', (string) $value);

        // Unknown template tokens are likely a configuration typo.
        if (preg_match('/[{}]/', $normalized)) {
            return false;
        }

        if (!filter_var($normalized, FILTER_VALIDATE_URL)) {
            return false;
        }

        return in_array(strtolower((string) parse_url($normalized, PHP_URL_SCHEME)), ['http', 'https'], true);
    }

    public function message(): string
    {
        return 'The :attribute must be an HTTP(S) URL using only supported user placeholders.';
    }
}
