<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxCF\OptionsFields\SearchSidebar;

use AuxCF\Entities\Field\Enum\RepeaterFieldLayoutEnum;
use AuxCF\Entities\Field\GroupFieldEntity;
use AuxCF\Entities\Settings\Enum\OperatorEnum;

class SearchSidebarFilterTermsFieldEntity extends GroupFieldEntity
{
  public static string $name = 'aux_search_sidebar_section_filter_terms';

  protected string $label = 'Terms';
  protected string $instructions = 'If none are selected, the 5 most-used terms will be displayed as filter options.';
  protected RepeaterFieldLayoutEnum $layout = RepeaterFieldLayoutEnum::Block;

  protected array $initFields = [
    SearchSidebarFilterTaxonomyFieldEntity::class,
  ];

  protected array $initConditionalLogic = [
    [
      [ SearchSidebarFilterSourceFieldEntity::class, OperatorEnum::EQUALS, 'taxonomy' ]
    ],
  ];

  protected function afterInitFields(): void
  {
    $postTypes = get_post_types(
      [
        'exclude_from_search' => false,
        'has_archive' => true,
      ],
      'objects'
    );

    foreach ($postTypes as $postType) {
      if (!$postType instanceof \WP_Post_Type) {
        continue;
      }

      $taxonomies = get_object_taxonomies($postType->name, 'objects');

      foreach ($taxonomies as $taxonomy) {
        $name = SearchSidebarFilterTermsFieldEntity::$name . '--' . $postType->name . '--' . $taxonomy->name;

        $termsField = SearchSidebarFilterTermFieldEntity::create();
        $termsField->setOverrideName($name);
        $termsField->setTaxonomy($taxonomy->name);
        $termsField->setLabel($taxonomy->label);
        $termsField->addCondition(
          SearchSidebarFilterTaxonomyFieldEntity::class,
          OperatorEnum::EQUALS,
          $postType->name . '--' . $taxonomy->name
        );

        $this->addField($termsField);
      }
    }
  }
}
