<?php
/**
 * This class manage all plugin integrations
 *
 * @package YITH\DynamicPricingAndDiscount\Classes
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class that manage all integration
 */
class YITH_YWDPD_Integrations {
	use YWDPD_Singleton_Trait;

	/**
	 * The plugin list
	 *
	 * @var array
	 */
	private $plugins = array();

	/**
	 * The integrations class
	 *
	 * @var array
	 */
	private $integrations = array();

	/**
	 * YITH_YWDPD_Integrations constructor.
	 */
	private function __construct() {
		add_action( 'plugins_loaded', array( $this, 'load_plugins' ), 15 );
	}

	/**
	 * Load the list of integrations
	 *
	 * @author YITH <plugins@yithemes.com>
	 * @since  3.0.0
	 */
	public function load_plugins() {
		$this->plugins = require_once 'plugins-list.php';
		$this->load();
	}

	/**
	 * Load and instance the active integration
	 *
	 * @since  3.0.0
	 */
	private function load() {

		foreach ( $this->plugins as $slug => $plugin_info ) {

			$filename  = YITH_YWDPD_INC . '/integrations/class-yith-ywdpd-' . $slug . '-integration.php';
			$classname = 'YITH_YWDPD_' . implode( '_', array_map( 'ucfirst', explode( '-', $slug ) ) ) . '_Integration';
			if ( file_exists( $filename ) && $this->plugin_is_active( $slug ) ) {
				require_once $filename;
				$this->integrations[ $slug ] = new $classname();
			}
		}
	}

	/**
	 * Check if the current plugin is active to instance the integration class
	 *
	 * @param string $slug The plugin slug.
	 *
	 * @return bool
	 * @since  3.0.0
	 */
	public function plugin_is_active( $slug ) {
		$is_active = false;

		if ( isset( $this->plugins[ $slug ] ) ) {
			$plugin = $this->plugins[ $slug ];

			if ( 'wpml' === $slug ) {
				global $sitepress;
				$is_active = ! empty( $sitepress );
			} else {
				if ( isset( $plugin['premium'] ) && defined( $plugin['premium'] ) ) {

					$current_version = constant( $plugin['installed_version'] );
					$min_version     = $plugin['min_version'];
					$compare         = $plugin['compare'];

					if ( version_compare( $current_version, $min_version, $compare ) ) {

						$is_active = true;
					}
				}
			}
		}

		return $is_active;
	}

	/**
	 * Return the integration instance
	 *
	 * @param string $integration The integration slug to get.
	 *
	 * @return false|mixed
	 */
	public function get_integration( $integration ) {
		return $this->integrations[ $integration ] ?? false;
	}
}

YITH_YWDPD_Integrations::get_instance();
