<?php

namespace Linksy\SearchAndReplace\Plugli\Standard\Helpers;

/**
 * Handle urls.
 *
 * @since      1.0.1
 * @package    Plugli
 * @subpackage Plugli\Standard\Helpers
 * @author     Plugli Team <https://plugli.com>
 */
/**
 * Links class.
 */
class Links
{
    const MEDIA_EXTS = ["jpg", "jpeg", "png", "gif", "mp4", "avi", "mp3", "wav", "pdf", "tiff", "webp", "mov", "ico", "tif", "epub", "docx", "zip"];
    public static function is_media($link)
    {
        $path = parse_url($link, \PHP_URL_PATH);
        if (!is_null($path)) {
            // get the file extension from the URL
            $ext = pathinfo($path, \PATHINFO_EXTENSION);
            return in_array(strtolower($ext), self::MEDIA_EXTS);
        }
        return \false;
    }
    public static function extract_from_html_dom($content)
    {
        $report_links = [];
        // Regular expression pattern to match and extract anchor tag attributes
        $patterns = ['href' => '/href="([^"]*?)"/i', 'target' => '/target="([^"]*?)"/i', 'aria-label' => '/aria-label="([^"]*?)"/i', 'rel' => '/rel="([^"]*?)"/i', 'text' => '/<a[^>]*>(.*?)<\/a>/i', 'img' => '/<img[^>]+src="([^"]+)"[^>]*alt="([^"]*?)"/i'];
        // Perform the regular expression match
        if (preg_match_all('/<a\s+[^>]*>(.*?)<\/a>/is', $content, $matches, \PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $tagContent = $match[0];
                $text = preg_replace('/[\r\n\t]/', '', $match[1]);
                $link = ['text' => $text, 'meta' => [], 'rel' => null, 'aria_label' => null, 'target_attribute' => null];
                if (preg_match($patterns['href'], $tagContent, $hrefMatch)) {
                    $href = $hrefMatch[1];
                    $link['link'] = $href;
                    // Todo - Reuben: add $is_image_url = self::is_media($href) 
                    if (preg_match($patterns['img'], $match[1], $imgMatch)) {
                        $imgSrc = $imgMatch[1];
                        $imgAlt = $imgMatch[2];
                        $link['meta'] = ['src' => $imgSrc, 'alt' => $imgAlt];
                        $link['meta']['is_image_url'] = 1;
                        $link['text'] = 'image';
                    }
                } else {
                    $link['link'] = null;
                }
                if (preg_match($patterns['target'], $tagContent, $targetMatch)) {
                    $link['target_attribute'] = strtolower($targetMatch[1]);
                }
                if (preg_match($patterns['aria-label'], $tagContent, $ariaLabelMatch)) {
                    $link['aria_label'] = $ariaLabelMatch[1];
                }
                if (preg_match($patterns['rel'], $tagContent, $relMatch)) {
                    $link['rel'] = strtolower($relMatch[1]);
                }
                $report_links[] = $link;
            }
        }
        return $report_links;
    }
}
