<?php

namespace Limb_Chatbot\Includes\Integrations;

use Limb_Chatbot\Includes\Traits\SingletonTrait;
use Limb_Chatbot\Includes\Integrations\WPML\WPML;

/**
 * Centralized integrations manager.
 *
 * Handles registration and initialization of all plugin integrations.
 *
 * @package Limb_Chatbot\Includes\Integrations
 *
 */
class Integrations {
	use SingletonTrait;

	/**
	 * Registered integrations.
	 *
	 * @var array<string, object>
	 *
	 */
	private array $integrations = [];

	/**
	 * Initialize all integrations.
	 *
	 *
	 * @return void
	 */
	public function init(): void {
		$this->register_integrations();
		$this->initialize_integrations();
	}

	/**
	 * Register all available integrations.
	 *
	 *
	 * @return void
	 */
	private function register_integrations(): void {
		if ( $this->is_wpml_active() ) {
			$this->register_integration( 'wpml', \Limb_Chatbot\Includes\Integrations\WPML\WPML::class );
		}
	}

	/**
	 * Register a single integration.
	 *
	 *
	 * @param  string  $id  Integration identifier.
	 * @param  string  $class_name  Integration class name.
	 *
	 * @return void
	 */
	private function register_integration( string $id, string $class_name ): void {
		if ( ! class_exists( $class_name ) ) {
			return;
		}

		$this->integrations[ $id ] = new $class_name();
	}

	/**
	 * Check if WPML is active.
	 *
	 * @return bool True if WPML String Translation API is available.
	 */
	private function is_wpml_active(): bool {
		return has_action( 'wpml_register_single_string' ) || function_exists( 'icl_object_id' ) || defined( 'ICL_SITEPRESS_VERSION' );
	}

	/**
	 * Initialize all registered integrations.
	 *
	 *
	 * @return void
	 */
	private function initialize_integrations(): void {
		foreach ( $this->integrations as $integration_id => $integration_instance ) {
			if ( method_exists( $integration_instance, 'init' ) ) {
				$integration_instance->init();
			}
		}
	}

	/**
	 * Get a registered integration instance.
	 *
	 *
	 * @param  string  $id  Integration identifier.
	 *
	 * @return object|null Integration instance or null if not found.
	 */
	public function get_integration( string $id ): ?object {
		return $this->integrations[ $id ] ?? null;
	}

	/**
	 * Get all registered integrations.
	 *
	 *
	 * @return array<string, object> Array of integration instances.
	 */
	public function get_integrations(): array {
		return $this->integrations;
	}

	/**
	 * Check if an integration is registered.
	 *
	 *
	 * @param  string  $id  Integration identifier.
	 *
	 * @return bool True if integration is registered, false otherwise.
	 */
	public function has_integration( string $id ): bool {
		return isset( $this->integrations[ $id ] );
	}
}