<?php

namespace Limb_Chatbot\Includes\Integrations;

use Limb_Chatbot\Includes\Integrations\JetEngine\JetEngine;
use Limb_Chatbot\Includes\Integrations\Slack\Slack;
use Limb_Chatbot\Includes\Traits\SingletonTrait;

/**
 * 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 {
		// Register Slack integration (always available)
		$this->register_integration( 'slack', Slack::class );
		if ( $this->is_jetengine_active() ) {
			$this->register_integration( 'jetengine', JetEngine::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 JetEngine plugin is active.
	 *
	 *
	 * @return bool True if JetEngine is active, false otherwise.
	 */
	private function is_jetengine_active() {
		return class_exists( '\Jet_Engine' ) || function_exists( 'jet_engine' );
	}

	/**
	 * 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 ] );
	}
}