<?php
/** @noinspection PhpUnusedParameterInspection */
/** @noinspection PhpMissingReturnTypeInspection */

/** @noinspection PhpUnused */

namespace WPDRMS\ASP\Hooks\Filters;

use WP_Term;

if ( !defined('ABSPATH') ) {
	die('-1');
}

class ArchivePages extends AbstractFilter {
	public function handle() {}

	/**
	 * Restricts the taxonomy term filters on the archive pages to show only those that are available on the current page
	 *
	 * @hook asp_fontend_get_taxonomy_terms
	 * @param WP_Term[] $original_terms
	 * @param string    $taxonomy
	 * @param array     $original_args
	 * @param bool      $needed_all
	 * @param array     $search_options
	 * @return WP_Term[]
	 */
	public function restrictTaxonomyTermFiltersOnArchivePages( array $original_terms, string $taxonomy, array $original_args, bool $needed_all, array $search_options ) {
		if ( !$search_options['frontend_terms_relevant_only_on_archives'] ) {
			return $original_terms;
		}

		global $wpdb;

		// Get the current queried object
		$current_queried_object = get_queried_object();

		// Check if we're on a term archive
		if ( !is_a( $current_queried_object, 'WP_Term' ) ) {
			return $original_terms;
		}


		// Create cache key that includes the term ID
		$cache_key = 'terms_' . $taxonomy . '_' . $current_queried_object->term_id;

		// Check transient cache
		$cached_terms = get_transient( $cache_key );
		if ( false !== $cached_terms ) {
			return $cached_terms;
		}

		// Get post IDs in the current category using a custom SQL query
		$query = $wpdb->prepare(
			"
            SELECT DISTINCT tr.object_id
            FROM {$wpdb->term_relationships} tr
            INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
            WHERE tt.taxonomy = %s
            AND tt.term_id = %d
            ",
			$current_queried_object->taxonomy, // e.g., 'category'
			$current_queried_object->term_id
		);

		$post_ids = $wpdb->get_col( $query ); // phpcs:ignore

		if ( empty( $post_ids ) ) {
			return array(); // No posts in this category, return empty array
		}

		// Prepare get_terms() arguments
		$args = array(
			'taxonomy'   => $taxonomy,
			'hide_empty' => false, // Include terms even if empty in other contexts
			'object_ids' => $post_ids, // Filter by post IDs
			'fields'     => 'all',
		);

		if ( isset($original_args['order']) ) {
			$args['order'] = $original_args['order'];
		}
		if ( isset($original_args['orderby']) ) {
			$args['orderby'] = $original_args['orderby'];
		}

		/**
		 * @var WP_Term[] $terms
		 */
		$terms = get_terms( $args );

		if ( is_wp_error( $terms ) ) {
			$terms = $original_terms;
		} elseif ( !empty($original_terms) && !empty($terms) ) {
			$terms = array_filter(
				$terms,
				function ( $term ) use ( $original_terms ) {
					return in_array($term->term_id, array_map(fn( $t )=>$t->term_id, $original_terms), true);
				}
			);
		}

		// Cache the results for 1 minute
		set_transient( $cache_key, $terms, MINUTE_IN_SECONDS );

		return $terms;
	}
}
