<?php
declare(strict_types=1);

namespace WP_AUX\Services\AuxFramework;

use AuxCF\Entities\FieldGroupEntity;

class PageFieldGroupsService
{
  /**
   * Remove 'aux_page_' from settings keys
   */
  public static function reindexSettingsFromRequest(mixed $data, string $removeKey = ''): mixed
  {
    if (is_scalar($data) || is_null($data)) {
      return $data;
    }

    foreach ($data as $dataKey => $dataValue) {
      if (is_int($dataKey)) {
        if (is_scalar($dataValue)) {
          continue;
        }

        $isListArray = true;
        foreach ($dataValue as $key => $value) {
          if (!is_int($key)) {
            $isListArray = false;
            break;
          }
        }

        if (!$isListArray) {
          $data[$dataKey] = self::reindexSettingsFromRequest($dataValue, $removeKey);
        }

        continue;
      }

      if (is_array($dataValue)) {
        $dataValue = self::reindexSettingsFromRequest($dataValue, $dataKey);
      }

      if (preg_match('/' . $removeKey . '(_|--)(.*)/', $dataKey, $matches)) {
        $newDataKey = $matches[2];
        unset($data[$dataKey]);
        $data[$newDataKey] = $dataValue;
      }
    }

    return $data;
  }

  protected static function getRequestedPageBuilder(): ?FieldGroupEntity
  {
    $pageFieldGroups = acf_get_field_groups(['post_id' => get_the_ID()]);

    foreach ($pageFieldGroups as $fieldGroup) {
      if ($pageFieldGroup = \WP_AUX::instance()->getPageFieldGroupEntity($fieldGroup['key'])) {
        return $pageFieldGroup;
      }
    }

    return null;
  }

  /**
   * Get page builder settings as an array
   */
  public static function getSettingsFromRequest(): array
  {
    $settings = [
      'excerpt' => get_the_excerpt(),
    ];

    $pageBuilderEntity = self::getRequestedPageBuilder();

    if (!$pageBuilderEntity) {
      return $settings;
    }

    if ($fields = $pageBuilderEntity->getFields()) {
      foreach ($fields as $field) {
        $settingsKey = $field::$nickname;

        if (!$settingsKey) {
          $settingsKey = $field::$name;
        }

        $settings[$settingsKey] = self::reindexSettingsFromRequest(
          aux_get_field($field::$name),
          $field::$name
        );
      }
    }

    return $settings;
  }
}
