<?php
/**
 * FluentC WordPress  File.
 *
 * This file contains the WordPress functions for updating WordPress
 *
 * @package  FluentCPlugin
 * @author   FluentC <wp@fluentc.io>
 * @category Translation
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     https://www.fluentc.ai
 */

namespace FluentC\Models;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Htmltags interface
 *
 * @since 1.2
 */
class Htmltags {


	/**
	 * HTML elements that are not translated
	 *
	 * @var array
	 * @since  1.2
	 */
	public $forbidden_selectors = array(
		'W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> ',
		'._fluentc_widget-language-manager',
		'._fluentc_widget-language-list',
		'._fluentc_widget_float_dropdown_wrapper',
		'wpadminbar'
	);

	/**
	 * HTML elements that are translated
	 *
	 * @var array
	 * @since  1.2
	 */
	public $text_containing_elements = array(
		'body',
		'h1',
		'h2',
		'h3',
		'h4',
		'h5',
		'h6',
		'p',
		'span',
		'div',
		'a',
		'button',
		'label',
		'textarea',
		'option',
		'legend',
		'caption',
		'th',
		'td',
		'li',
		'dt',
		'dd',
		'blockquote',
		'q',
		'figcaption',
		'cite',
		'code',
		'pre',
		'em',
		'strong',
		'i',
		'b',
		'u',
		's',
		'small',
		'sub',
		'sup',
		'ins',
		'del',
		'mark',
		'ruby',
		'rt',
		'rp',
		'abbr',
		'address',
		'bdi',
		'bdo',
		'data',
		'dfn',
		'samp',
		'var',
		'article',
		'aside',
		'details',
		'footer',
		'header',
		'hgroup',
		'nav',
		'section',
	);

	/**
	 * Whitespace regex
	 *
	 * @var string
	 * @since  1.2
	 */
	public $regex_only_whitespace = '/^[\s]*$/';

	/**
	 * Whitespace and punctuation regex
	 *
	 * @var string
	 * @since  1.2
	 */
	public $regex_only_digits_whitespace_punctuation = '/^[\d\s!"#$%&\'()*+,\-\.\/:;<=>?@\[\]^_`{|}~]*$/';

	/**
	 * Checks to see if link is a file
	 *
	 * @param string $current_url URL.
	 * @var   boolean
	 * @since 1.2
	 */
	public function check_for_file( $current_url ) {
		$files = array(
			'pdf',
			'rar',
			'doc',
			'docx',
			'jpg',
			'jpeg',
			'png',
			'svg',
			'ppt',
			'pptx',
			'xls',
			'zip',
			'mp4',
			'xlsx',
			'txt',
			'eps',
		);

		foreach ( $files as $file ) {
			if ( self::ends_with( strtolower( $current_url ), '.' . $file ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Changes the string to update the link if possible
	 *
	 * @param mixed $haystack haystack.
	 * @param mixed $needle needle.
	 * @return mixed
	 * @since 1.2
	 */
	public function ends_with( $haystack, $needle ) {
		$temp = strlen( $haystack );
		$len_needle = strlen( $needle );

		return '' === $needle ||
			(
				( $temp - $len_needle ) >= 0 && strpos( $haystack, $needle, $temp - $len_needle ) !== false
			);
	}

	/**
	 * Summary of processLink
	 * @param string $url
	 * @param string $language_code
	 * @return string
	 */
	public function processLink(string $url, string $language_code): string {
        $parsed_url = parse_url($url);
		$is_relative_path = empty($parsed_url['host']);
        
        // Check if the URL should be processed
        if ($this->shouldSkipProcessing($url, $parsed_url, $is_relative_path)) {
			return $url;
        }

        // Check if the language code is already present
        if ($this->hasLanguageCode($parsed_url['path'], $language_code)) {
			return $url;
        }
		
		return $this->addLanguageCodeToLink($language_code, $url);
    }

	/**
	 * Summary of shouldSkipProcessing
	 * @param mixed $url
	 * @param mixed $parsed_url
	 * @param mixed $is_relative_path
	 * @return bool
	 */
    private function shouldSkipProcessing($url, $parsed_url, $is_relative_path): bool {
		
        return $is_relative_path ||
               (isset($parsed_url['host']) && parse_url(home_url(), PHP_URL_HOST) !== $parsed_url['host']) ||
               strpos($url, '/wp-admin/') !== false ||
               $this->check_for_file($url);
    }

	/**
	 * Summary of hasLanguageCode
	 * @param mixed $path
	 * @param mixed $language_code
	 * @return bool
	 */
    public function hasLanguageCode($path, $language_code): bool {
        $path_segments = explode('/', trim($path, '/'));
	
        return !empty($path_segments) && $path_segments[0] === $language_code;
    }

	/**
	 * Summary of addLanguageCodeToLink
	 * @param mixed $language_code
	 * @param mixed $url
	 * @return string
	 */
    public function addLanguageCodeToLink($language_code, $url) {
        $url_parts = wp_parse_url($url);
		
        $original_path = isset($url_parts['path']) ? $url_parts['path'] : '';
        $path = '/' . $language_code . $original_path;
    
        $new_permalink = '';
    
        if (isset($url_parts['scheme']) && isset($url_parts['host'])) {
            $new_permalink = $url_parts['scheme'] . '://' . $url_parts['host'];
        }
    
        $new_permalink .= $path;
    
        if (!empty($url_parts['query'])) {
            $new_permalink .= '?' . $url_parts['query'];
        }
    
        if (!empty($url_parts['fragment'])) {
            $new_permalink .= '#' . $url_parts['fragment'];
        }
    
        return $new_permalink;
    }
	/**
	 * Updates Links
	 *
	 * @param  string $language permalink.
	 * @param  string $url post.
	 * @return string
	 * @since 1.2
	 */
	public function add_language_code_to_link($language_code, $url) {
		// Modify the permalink to add the language code.
		$url_parts = wp_parse_url($url);
	
		// Check if 'path' exists, if not, use an empty string
		$original_path = isset($url_parts['path']) ? $url_parts['path'] : '';
		$path = '/' . $language_code . $original_path;
	
		// Start rebuilding the URL
		$new_permalink = '';
	
		// Add scheme and host if they exist
		if (isset($url_parts['scheme']) && isset($url_parts['host'])) {
			$new_permalink = $url_parts['scheme'] . '://' . $url_parts['host'];
		}
	
		// Add the path
		$new_permalink .= $path;
	
		// Add query string if it exists
		if (!empty($url_parts['query'])) {
			$new_permalink .= '?' . $url_parts['query'];
		}
	
		// Add fragment if it exists
		if (!empty($url_parts['fragment'])) {
			$new_permalink .= '#' . $url_parts['fragment'];
		}
	
		return $new_permalink;
	}
	
    private function getLanguageFromUrl($url, $regex_lang) {
        $pattern = '/\/(' . $regex_lang . ')(\/|$|\?|#)/';
        $language_code = null;
        
        if (preg_match($pattern, wp_unslash($url), $matches)) {
            $language_code = $matches[1] ?? null;
        }
        
        return $language_code;
    }
}
