<?php
declare(strict_types=1);

namespace WP_AUX\Entities\AuxCF\OptionsFields\PostType;

use AuxCF\Entities\Field\Enum\RepeaterFieldLayoutEnum;
use AuxCF\Entities\Field\GroupFieldEntity;
use AuxCF\Entities\Settings\Enum\OperatorEnum;
use WP_AUX\Services\AuxCF\FieldsService;
use WP_AUX\Services\PostTypeService;

class PostTypeSearchFilterTermsFieldEntity extends GroupFieldEntity
{
  public static string $namePattern = 'aux_search_%s_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 = [
    PostTypeSearchFilterTaxonomyFieldEntity::class,
  ];

  protected function afterInitFields(): void
  {
    $postTypes = PostTypeService::getFieldPostTypes($this);

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

      $taxonomies = get_object_taxonomies($postType->name, 'objects');
      $namePrepend = FieldsService::getDynamicFieldName($this);

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

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

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