<?php
/**
 * @license GPL-2.0-or-later
 * @link    https://wordpress.org/plugins/pressio-crm
 */
namespace PressioCRM\Modules;

defined( 'ABSPATH' ) || exit;

use PressioCRM\Framework\Module;
use PressioCRM\Integrations\IntegrationManager;
use PressioCRM\Integrations\Cf7Integration;
use PressioCRM\Integrations\FluentformsIntegration;
use PressioCRM\Integrations\WpformsIntegration;
use PressioCRM\API\RestIntegrations;

class IntegrationsModule extends Module {

	public function register(): void {
		$this->container->singleton(
			'integration.manager',
			fn() => new IntegrationManager()
		);
	}

	public function boot(): void {
		add_action( 'rest_api_init', [ $this, 'register_routes' ] );

		// Priority 20 — all plugins are fully loaded by this point,
		// so class_exists() / defined() checks for CF7 and FF are reliable.
		add_action( 'init', [ $this, 'init_integrations' ], 20 );
	}

	public function register_routes(): void {
		( new RestIntegrations( $this->container ) )->register_routes();
	}

	public function init_integrations(): void {
		$manager = $this->container->make( 'integration.manager' );

		/**
		 * Fires so Pro add-ons and third-party code can register their own integrations.
		 *
		 * @param IntegrationManager $manager
		 */
		do_action( 'pressio_crm_register_integration', $manager );

		if ( class_exists( 'WPCF7' ) ) {
			$manager->register( new Cf7Integration() );
		}

		if ( defined( 'FLUENTFORM' ) ) {
			$manager->register( new FluentformsIntegration() );
		}

		if ( function_exists( 'wpforms' ) ) {
			$manager->register( new WpformsIntegration() );
		}
	}
}
