<?php

declare(strict_types=1);

namespace KimaAI\Admin\Integrations;

defined('ABSPATH') || exit;

class IntegrationManager {

  /**
   * Registered integrations.
   *
   * @var IntegrationInterface[]
   */
  public array $integrations = [];

  /**
   * Integration manager constructor.
   *
   * @param WooCommerceIntegration $woocommerce The WooCommerce integration.
   */
  public function __construct(
    WooCommerceIntegration $woocommerce,
    // phpcs:ignore
    // ElasticPressIntegration $elasticPress,
    // GravityFormsIntegration $gravityForms,
    // ContactForm7Integration $contactForm7,
  ) {
    $this->addIntegration($woocommerce);
    // phpcs:ignore
    // $this->addIntegration($gravityForms);
    // $this->addIntegration($contactForm7);
    // $this->addIntegration($elasticPress);
  }

  /**
   * Adds an integration.
   *
   * @param IntegrationInterface $integration The integration instance.
   */
  public function addIntegration(IntegrationInterface $integration): void {
    $this->integrations[$integration->getKey()] = $integration;
  }

  /**
   * Gets plugin status details.
   *
   * @param string $pluign_id The plugin ID.
   */
  public function pluginStatus($pluign_id): array {
    $integration = $this->integrations[$pluign_id];

    if (!$integration) {
      return [];
    }

    return [
      'pluginKey' => $integration->getKey(),
      'pluginName' => $integration->getLabel(),
      'isDetected' => $this->isDetected($integration, $pluign_id),
      'isActive' => $integration->isActive(),
    ];
  }

  /**
   * Checks whether a plugin is detected.
   *
   * @param IntegrationInterface $integration The integration instance.
   * @param string $plugin The plugin slug.
   */
  public function isDetected(IntegrationInterface $integration, string $plugin): bool {
    if ($integration->isActive()) {
      return true;
    }

    $plugins = get_plugins();

    return isset($plugins["$plugin/$plugin.php"]);
  }
}
