<?php
if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! function_exists( 'fs_lite_dynamic_init' ) ) {
	function fs_lite_dynamic_init( $module ) {
		if ( \function_exists( 'fs_dynamic_init' ) ) {
			return fs_dynamic_init( $module );
		}
		return PEVFSLite::instance( $module );
	}
}

require_once dirname( __FILE__ ) . '/includes/Persistence.php';
require_once dirname( __FILE__ ) . '/includes/API.php';
require_once dirname( __FILE__ ) . '/includes/Licensing.php';
require_once dirname( __FILE__ ) . '/includes/OptIn.php';
require_once dirname( __FILE__ ) . '/includes/Assets.php';

if ( ! class_exists( 'PEVFSLite' ) ) {
	class PEVFSLite {
		private static $instances = array();
		private $id, $public_key, $secret_key, $slug, $version, $type, $name, $params, $plugin_basename;
		private $plugin_path, $plugin_url;
		private $sdk_version = '1.0.0';

		public static function instance( $module ) {
			$slug = $module['slug'];
			if ( ! isset( self::$instances[ $slug ] ) ) {
				self::$instances[ $slug ] = new self( $module );
			}
			return self::$instances[ $slug ];
		}

		private function __construct( $module ) {
			$this->plugin_path = \dirname( __FILE__ );
			$this->plugin_url = \plugins_url( '', __FILE__ );

			$this->params = $module;
			$this->id = $module['id'];
			$this->public_key = $module['public_key'];
			$this->secret_key = $module['secret_key'] ?? $this->public_key;
			$this->slug = $module['slug'];
			$this->version = $module['version'] ?? '1.0.0';
			$this->type = $module['type'] ?? 'plugin';
			$this->name = $module['menu']['page_title'] ?? $this->slug;

			if ( $this->is_plugin() ) {
				$file = $module['plugin_file'] ?? $this->slug . '/' . $this->slug . '.php';
				$this->plugin_basename = \plugin_basename( $file );
			}

			$this->init();
		}

		use \PEVFSLite\Persistence, \PEVFSLite\API, \PEVFSLite\Licensing, \PEVFSLite\OptIn, \PEVFSLite\Assets;

		private function init() {
			$this->init_persistence();
			$this->init_optin();
			$this->init_assets();
		}

		public function is_anonymous() {
			$anon = $this->get_plugin_data( 'is_anonymous', false );
			return is_array( $anon ) ? (bool)$anon['is'] : (bool)$anon;
		}

		public function get_opt_in_url() {
			return \add_query_arg( array(
				'fs_action'	=> $this->slug . '_activate_new',
				'_wpnonce'	=> \wp_create_nonce( 'fs_activate_' . $this->slug ),
			), \admin_url( 'plugins.php' ) );
		}

		public function set_basename( $is_premium, $file ) {
			if ( $is_premium && ! $this->is_premium() ) {
				if ( ! function_exists( 'deactivate_plugins' ) ) {
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
				}
				\deactivate_plugins( $this->plugin_basename );
			}
			return $this;
		}
	}
}