<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Replacements;

use PrettyLinks\Pro\Options\Store as OptionsStore;

/**
 * V3-parity global disclosure link appended to any post content that had
 * keyword or URL replacements run. Gated by `enable_link_to_disclosures`;
 * text/URL/position come from sibling options.
 *
 * Position: `'top' | 'bottom' | 'top_and_bottom'` (v3 shape). An existing
 * `prli-link-to-disclosures` block in the content is respected — we never
 * double-inject.
 */
final class Disclosures
{
    /**
     * The Pro options store.
     *
     * @var OptionsStore
     */
    private OptionsStore $options;

    /**
     * Constructor.
     *
     * @param OptionsStore $options The Pro options store.
     */
    public function __construct(OptionsStore $options)
    {
        $this->options = $options;
    }

    /**
     * Whether the global disclosure link is enabled.
     *
     * @return boolean
     */
    public function enabled(): bool
    {
        return (bool) $this->options->getPro('enable_link_to_disclosures', false);
    }

    /**
     * Inject the disclosure link block into the given content.
     *
     * @param string $content The post content to inject into.
     *
     * @return string
     */
    public function inject(string $content): string
    {
        if (!$this->enabled() || $content === '') {
            return $content;
        }
        if (strpos($content, 'prli-link-to-disclosures') !== false) {
            return $content;
        }

        $url  = (string) $this->options->getPro('disclosures_link_url', '');
        $text = (string) $this->options->getPro('disclosures_link_text', '');
        if ($url === '' || $text === '') {
            return $content;
        }

        $block = '<div class="prli-link-to-disclosures"><a href="'
            . esc_url($url) . '">' . esc_html($text) . '</a></div>';

        $position = (string) $this->options->getPro('disclosures_link_position', 'bottom');
        if ($position === 'top') {
            return $block . $content;
        }
        if ($position === 'top_and_bottom') {
            return $block . $content . $block;
        }
        return $content . $block;
    }
}
