<?php
declare(strict_types=1);

namespace WP_AUX\Services;

use AuxCF\Entities\FieldEntity;
use WP_AUX\Entities\AuxCF\OptionsFields\PostType\PostTypeArchiveFieldEntity;
use WP_AUX\Entities\AuxCF\OptionsFields\PostType\PostTypeSearchFieldEntity;
use WP_AUX\Services\AuxFramework\PageFieldGroupsService;
use WP_AUX\Services\AuxCF\FieldsService;

class PostTypeService
{
  protected static function getPostTypeOption(string $fieldSet, string $postType, ?string $optionField, mixed $default = ''): mixed
  {
    $fieldName = FieldsService::getDynamicFieldName($fieldSet, $postType);

    $optionKey = null;
    if ($optionField) {
      $optionKey = FieldsService::getDynamicFieldName($optionField, $postType);
    }

    $options = get_field($fieldName, 'option');

    if (!is_null($optionKey)) {
      $options = $options[$optionKey] ?? $default;
    }

    if (is_array($options)) {
      return PageFieldGroupsService::reindexSettingsFromRequest($options, $optionKey ?? $fieldName);
    }

    return $options;
  }

  public static function getArchiveOption(string $postType, string $optionKey, mixed $default = ''): mixed
  {
    return self::getPostTypeOption(PostTypeArchiveFieldEntity::class, $postType, $optionKey, $default);
  }

  public static function getSearchOption(string $postType, ?string $optionField, mixed $default = ''): mixed
  {
    return self::getPostTypeOption(PostTypeSearchFieldEntity::class, $postType, $optionField, $default);
    $fieldName = FieldsService::getDynamicFieldName(PostTypeSearchFieldEntity::class, $postType);

    $optionKey = null;
    if ($optionField) {
      $optionKey = FieldsService::getDynamicFieldName($optionField, $postType);
    }

    $options = get_field($fieldName, 'option');

    if (!is_null($optionKey)) {
      $options = $options[$optionKey] ?? $default;
    }

    if (is_array($options)) {
      return PageFieldGroupsService::reindexSettingsFromRequest($options, $optionKey ?? $fieldName);
    }

    return $options;
  }

  /**
   * @return \WP_Post_Type[]
   * @since 1.0.0
   */
  public static function getFieldPostTypes(FieldEntity $field): array
  {
    $rootWildcard = $field->getRootWildcard();

    if ($rootWildcard) {
      $postTypes = [ get_post_type_object($rootWildcard) ];
    } else {
      $postTypes = get_post_types(
        [
          'exclude_from_search' => false,
          'has_archive' => true,
        ],
        'objects'
      );
    }

    return $postTypes;
  }
}
