<?php

namespace ModernFields\FieldGroups\Entities;

/**
 * Base Entity class
 * 
 * Provides common functionality for entities that have meta data.
 * 
 * @since 1.0.0
 */
abstract class Entity
{
  /**
   * @var array
   */
  protected array $meta;

  /**
   * Get the meta data.
   * 
   * @return array
   */
  public function getMeta(): array
  {
    return $this->meta;
  }

  /**
   * Prepare meta data for JSON serialization.
   * Unserializes serialized arrays and handles WordPress meta format.
   *
   * @since 1.0.0
   * @return array<string, mixed>
   */
  protected function prepareMetaForJson(): array
  {
    $prepared = [];

    foreach ($this->meta as $key => $values) {
      # WordPress meta can have multiple values per key
      if (!is_array($values)) {
        $values = [$values];
      }

      # Unserialize each value
      $unserialized = array_map(function ($value) {
        return is_string($value) ? maybe_unserialize($value) : $value;
      }, $values);

      # If there's only one value, return it directly (not wrapped in array)
      # Otherwise return the array of values
      $prepared[$key] = count($unserialized) === 1 ? $unserialized[0] : $unserialized;
    }

    return $prepared;
  }

  /**
   * Convert the entity to an array representation.
   * 
   * @return array<string, mixed>
   */
  abstract public function toArray(): array;
}
