<?php

namespace ModernFields;

use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\Kernel\Container;
use ModernFields\FieldGroups\Services\FieldService;
use ModernFields\FieldGroups\Services\FieldGroupsService;

/**
 * Main class for the plugin
 *
 * @since 1.0
 */
class Plugin
{
  /**
   * Singleton instance of the class
   *
   * @var Plugin|null
   */
  protected static ?Plugin $_instance = null;

  /**
   * Container instance
   *
   * @var Container|null
   */
  protected ?Container $container = null;

  /**
   * Fields service instance
   *
   * @var FieldService|null
   */
  protected ?FieldService $fields = null;

  /**
   * Field Groups service instance
   *
   * @var FieldGroupsService|null
   */
  protected ?FieldGroupsService $fieldGroups = null;

  /**
   * @since 1.0
   */
  public function __construct()
  {
    $this->run();
  }

  /**
   * @since 1.0
   */
  public function run(): void
  {
    $this->container = new Container();
    $built_container = $this->container->getContainer();

    $taggedServices = $built_container->findTaggedServiceIds('wordpress.hooks');

    foreach ($taggedServices as $serviceId => $tags) {
      $service = $built_container->get($serviceId);

      if ($service instanceof Hooks) {
        $service->registerHooks();
      }
    }

    $this->fields      = $built_container->get(FieldService::class);
    $this->fieldGroups = $built_container->get(FieldGroupsService::class);
  }

  /**
   * @since 1.0
   * @return Plugin
   */
  public static function getInstance(): Plugin
  {
    if (self::$_instance === null) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

  /**
   * @since 1.0.0
   */
  public function getFieldsService(): FieldService
  {
    return $this->fields;
  }

  /**
   * @since 1.0.0
   */
  public function getFieldGroupsService(): FieldGroupsService
  {
    return $this->fieldGroups;
  }

  /**
   * @since 1.0.0
   */
  public function __get(string $name): mixed
  {
    if ($name === 'fields') {
      return $this->getFieldsService();
    }
    if ($name === 'fieldGroups') {
      return $this->getFieldGroupsService();
    }
    return null;
  }
}
