<?php
if (!function_exists('explore_tags_get_post_types')) {
	function explore_tags_get_post_types()
	{
		$current_blog_id = get_current_blog_id();

		if ($current_blog_id === 2) {
			return ['articles'];
		}

		if ($current_blog_id === 1 && is_page()) {
			$tax = get_taxonomy('etiquettes');
			return $tax->object_type ?? [];
		}

		// Single ou archive d'un post type
		if (is_singular()) {
			return [get_post_type()];
		}
		if (is_post_type_archive()) {
			$post_type = get_query_var('post_type');
			return is_array($post_type) ? $post_type : [$post_type];
		}

		return [];
	}
}

if (!function_exists('explore_tags_get_post_ids')) {
	function explore_tags_get_post_ids($post_types, $limit = 5000)
	{
		if (empty($post_types)) {
			return [];
		}

		return get_posts([
			'post_type'      => $post_types,
			'post_status'    => 'publish',
			'fields'         => 'ids',
			'posts_per_page' => $limit,
			'no_found_rows'  => true,
		]);
	}
}

if (!function_exists('explore_tags_get_tags_url')) {
	function explore_tags_get_tags_url($tag)
	{
		$current_blog_id = get_current_blog_id();
		if ($current_blog_id === 2) {
			return add_query_arg('etiquette', $tag->slug, get_post_type_archive_link('articles'));
		}
		if (is_page()) {
			$link = get_term_link($tag);
			return !is_wp_error($link) ? $link : '#';
		}

		return add_query_arg('etiquette', $tag->slug, get_post_type_archive_link(get_post_type()));
	}
}

$post_types = explore_tags_get_post_types();
$args = [
	'taxonomy'   => 'etiquettes',
	'hide_empty' => false,
];

if (!empty($post_types)) {
	$post_ids = explore_tags_get_post_ids($post_types);
	if (!empty($post_ids)) {
		$args['object_ids'] = $post_ids;
	}
}

$tags = get_terms($args);

?>

<section class="explore-tags alignfull">
	<div class="inner">
		<div class="explore-tags__titling">
			<h2 class="explore-tags__title title-small">Tags</h2>
			<h3 class="explore-tags__subtitle subtitle-big">Explorer <br /> par Tags</h3>
		</div>
		<div class="tag-list">
			<?php foreach ($tags as $tag) : ?>
				<a href="<?php echo esc_url(explore_tags_get_tags_url($tag)); ?>" class="tag-list__tag">
					<?php echo $tag->name; ?>
					<?php
					$svg_path = get_template_directory() . '/resources/img/carhop-fleche-lien-externe-full.svg';
					if (file_exists($svg_path)) {
						echo file_get_contents($svg_path);
					}
					?>
				</a>
			<?php endforeach; ?>
		</div>
	</div>
</section>