<?php
declare(strict_types=1);

namespace WP_AUX\Entities\Admin\AuxComponents;

use AuxCF\Entities\FieldGroupEntity;
use AuxCF\Services\FieldGroupService;

class AuxComponentsAuditComponentEntity
{
  public string $key;
  public AuxComponentAuditFileEntity $file;
  public FieldGroupEntity $fieldGroup;
  public string $title;
  public array $blockConfig;
  public int $fieldsCount;
  public int $allFieldsCount;
  public string $state;
  public bool $isActive;

  /**
   * @var AuxComponentsAuditFieldEntity[]
   */
  public array $auditFields;

  public function __construct(string $groupEntityPath) {
    $fieldGroupsEntity = \WP_AUX::fileObjectPath($groupEntityPath);

    $this->file = new AuxComponentAuditFileEntity($groupEntityPath);

    $this->key = $fieldGroupsEntity::$key;
    $this->fieldGroup = (new $fieldGroupsEntity);

    $title = $this->fieldGroup->getTitle();
    if (strpos($title, 'AUX ') === 0) {
      $title = substr($this->fieldGroup->getTitle(), 4);
    }
    $this->title = $title;

    $fieldArray = $this->fieldGroup->getArray();

    $this->blockConfig = (array) $this->fieldGroup->getBlockConfig();
    $this->fieldsCount = count($fieldArray['fields']);
    $this->allFieldsCount = self::getAllFieldsCount($fieldArray);
    $this->state = $fieldGroupsEntity::$state;
    $this->isActive = $fieldGroupsEntity::isActive();

    $this->prepareFields();
  }

  protected function prepareFields() {
    $this->auditFields = [];

    $fields = $this->fieldGroup->getFields();

    foreach ($fields as $field) {
      $auditField = new AuxComponentsAuditFieldEntity($field);
      $auditField->setParentEntity($this);

      $this->auditFields[] = $auditField;
    }
  }

  /**
   * @return AuxComponentsAuditFieldEntity[]
   */
  public function getAuditFields() {
    return $this->auditFields;
  }

  protected static function getAllFieldsCount($array): int
  {
    $count = 0;

    $fields = $array['sub_fields'] ?? @$array['fields'];

    if (!empty($fields)) {
      $count = count($fields);

      foreach ($fields as $field) {
        $count += self::getAllFieldsCount($field);
      }
    }

    return $count;
  }

  public function getDocumenationUrl(): string
  {
    return FieldGroupService::documentationUrl($this->fieldGroup);
  }
}
