<?php

namespace App;

//Get hidden decors categories
function get_hidden_decors_categories() {
  $cached_terms = wp_cache_get('hidden_decors_categories', 'decors');
  if ($cached_terms) {
      return $cached_terms;
  }

  remove_filter('get_terms_args', 'App\\hide_hidden_categories_from_queries', 10, 2);

  $terms = get_terms([
      'taxonomy' => 'decors-category',
      'hide_empty' => false,
      'fields' => 'ids',
      'meta_query' => [
          [
              'key' => 'hide_from_archives',
              'value' => '1',
              'compare' => '='
          ]
      ]
  ]);

  add_filter('get_terms_args', 'App\\hide_hidden_categories_from_queries', 10, 2);

  wp_cache_set('hidden_decors_categories', $terms, 'decors', 60);

  return $terms;
}

//remove hidden categories from the select_category field
add_filter('acf/fields/taxonomy/wp_list_categories/name=select_category', function ( $args, $field ) {
  $args['exclude'] = get_hidden_decors_categories();

  return $args;
}, 10, 2);

//remove hidden categories from frontend queries
add_filter( 'get_terms_args', 'App\\hide_hidden_categories_from_queries', 10, 2 );

function hide_hidden_categories_from_queries($args, $taxonomies) {
  if (is_admin()) return $args;
  if ($taxonomies[0] !== 'decors-category') return $args;

  $args['exclude'] = get_hidden_decors_categories();

  return $args;

}

//remove decors in hidden categories from frontend queries
add_action('pre_get_posts', function ($query) {
  if (is_admin()) return;
  if (!$query->is_main_query() && !$query->is_search()) return;

  $query->set('tax_query', [
      [
          'taxonomy' => 'decors-category',
          'field' => 'id',
          'terms' => get_hidden_decors_categories(),
          'operator' => 'NOT IN'
      ]
  ]);
});

//Hide hidden decors from SEO with yoast
add_filter('wpseo_exclude_from_sitemap_by_post_ids', function () {
  $posts = new \WP_Query([
      'post_type' => 'decor',
      'posts_per_page' => -1,
      'fields' => 'ids',
      'tax_query' => [
          [
              'taxonomy' => 'decors-category',
              'field' => 'id',
              'terms' => get_hidden_decors_categories(),
          ]
      ]
  ]);

  return $posts->posts;
}, 10, 2);

//Hide hidden decors from SEO with yoast
add_filter('wpseo_robots', function($robots) {
  if (is_singular('decors')) return $robots;
  
  global $post;

  remove_filter('get_terms_args', 'App\\hide_hidden_categories_from_queries', 10, 2);
  $decors_terms = wp_get_post_terms($post->ID, 'decors-category', ['fields' => 'ids']);
  add_filter('get_terms_args', 'App\\hide_hidden_categories_from_queries', 10, 2);

  $results = array_intersect($decors_terms, get_hidden_decors_categories());

  if (count($results) >= 1) return 'noindex, follow';

  return $robots;
});