<?php

namespace WPUltimateSecurity\UltimateSecurity\Support\Validation\Rules;

/**
 * URL Rule
 *
 * Validates that a value is a valid URL.
 *
 * @package WPUltimateSecurity\UltimateSecurity\Support\Validation\Rules
 * @since 2.0.0
 */
class UrlRule extends AbstractRule
{
    /**
     * Allowed protocols.
     *
     * @var array|null
     */
    private ?array $protocols = null;

    /**
     * Set allowed protocols.
     *
     * @param array $protocols Allowed protocols (e.g., ['http', 'https']).
     *
     * @return static
     */
    public function protocols(array $protocols): static
    {
        $clone = clone $this;
        $clone->protocols = $protocols;

        return $clone;
    }

    /**
     * Only allow HTTPS URLs.
     *
     * @return static
     */
    public function secure(): static
    {
        return $this->protocols(['https']);
    }

    /**
     * {@inheritDoc}
     */
    public function validate(mixed $value, string $field, array $data = []): bool
    {
        if ($value === null || $value === '') {
            return true;
        }

        if (!is_string($value)) {
            return false;
        }

        // Use WordPress URL validation
        $url = esc_url_raw($value, $this->protocols);

        return !empty($url);
    }

    /**
     * {@inheritDoc}
     */
    public function getName(): string
    {
        return 'url';
    }

    /**
     * {@inheritDoc}
     */
    protected function getDefaultMessage(string $field): string
    {
        return sprintf(
            /* translators: %s: field name */
            __('The %s must be a valid URL.', 'ultimate-security'),
            $field
        );
    }
}
