<?php

namespace Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers;

use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Str;
use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Links as StandardLinks;
class Links extends StandardLinks
{
    public static function insert_link($content, $source, $phrase, $phrase_replacement)
    {
        $prelude = '';
        $position = Str::position($content, $source);
        if ($position === \false) {
            return \false;
        }
        while (!empty($content) && (Str::is_in_comment($content, $source) || in_array(Str::get_enclosing_tag($content, $source), ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'img', 'button', 'th', 'thead']))) {
            $position = Str::position($content, $source) + strlen($source);
            $prelude .= substr($content, 0, $position);
            $content = substr($content, $position);
        }
        $position = Str::position($content, $source) + strlen($prelude);
        $phrase_position = Str::position($source, $phrase);
        return Str::addSlashToUnicodeSequences(substr_replace($prelude . $content, $phrase_replacement, $position + $phrase_position, strlen($phrase)));
    }
    public static function remove_link($content, $link, $anchor)
    {
        $pattern = '/<a\b[^>]*href="' . preg_quote($link, '/') . '"[^>]*>' . preg_quote($anchor, '/') . '<\/a>/i';
        // trim out the link around the anchor
        $updated_content = preg_replace($pattern, $anchor, $content, 1);
        if ($content === $updated_content || is_null($content)) {
            return \false;
        }
        return $updated_content;
    }
}
