<?php

namespace IGD;

defined( 'ABSPATH' ) || exit;

class Integrations {

	private static $instance = null;

	public function __construct() {

		// Classic editor
		if ( $this->is_active( 'classic-editor' ) ) {
			include_once IGD_INCLUDES . '/class-tinymce.php';
		}

		// Block editor
		if ( $this->is_active( 'gutenberg-editor' ) ) {
			include_once IGD_INCLUDES . '/blocks/class-blocks.php';
		}

		// Divi
		if ( $this->is_active( 'divi' ) ) {
			include_once IGD_INCLUDES . '/divi/divi.php';
		}


		add_action( 'plugins_loaded', function () {


			// Load CF7 integration
			if ( $this->is_active( 'cf7' ) && defined( 'WPCF7_VERSION' ) && version_compare( WPCF7_VERSION, '5.0', '>=' ) ) {
				include_once IGD_INCLUDES . '/integrations/class-cf7.php';
			}

			// Elementor
			if ( ( $this->is_active( 'elementor' ) )
			     || $this->is_active( 'elementor-form' )
			     || $this->is_active( 'metform' )
			) {
				include_once IGD_INCLUDES . '/elementor/class-elementor.php';
			}

		} );

		add_filter( 'igd_should_enqueue_admin_scripts', [ $this, 'maybe_enqueue_admin_scripts' ], 10, 2 );

	}

	public function maybe_enqueue_admin_scripts( $should_enqueue, $hook ) {

		if ( $this->is_active( 'gutenberg-editor' ) ) {
			if ( igd_is_block_editor() ) {
				return true;
			}
		}

		if ( $this->is_active( 'elementor' ) ) {
			if ( igd_is_elementor_editor() ) {
				return true;
			}
		}

		if ( $this->is_active( 'divi' ) ) {
			if ( igd_is_divi_builder() ) {
				return true;
			}
		}

		if ( $this->is_active( 'cf7' ) ) {
			if ( in_array(  $hook, [ 'toplevel_page_wpcf7', 'contact_page_wpcf7-new' ] ) ) {
				return true;
			}
		}


		return $should_enqueue;

	}

	/**
	 * Check if integration is active
	 *
	 * @param $key
	 *
	 * @return bool
	 */
	public function is_active( $key ) {

		$integrations = igd_get_settings( 'integrations', [
			'classic-editor',
			'gutenberg-editor',
			'elementor',
			'cf7',
		] );

		return in_array( $key, $integrations );
	}

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self;
		}

		return self::$instance;
	}

}

Integrations::instance();
