<?php

use ArraySubs\Supports\Config;

defined('ABSPATH') || exit;

/**
 * Plugin Name: ArraySubs - Subscription Manager for WooCommerce
 * Description: Subscriptions manager with recurring billing, self-service customer portal and membership restrictions for WooCommerce.
 * Plugin URI: https://wordpress.org/plugins/arraysubs/
 * Author: Emran
 * Version: 1.8.9
 * Author URI: https://profiles.wordpress.org/emranio/
 * License: GPLv3 or later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 * Requires at least: 6.0
 * Tested up to: 7.0
 * Requires PHP: 8.1
 * WC requires at least: 8.0
 * WC tested up to: 10
 *
 * Text Domain: arraysubs
 * Domain Path: /languages
 */


// define version constant 
if (!defined('ARRAYSUBS_VERSION')) {
	define('ARRAYSUBS_VERSION', '1.8.9');
}

// plugin prefix constant
if (!defined('ARRAYSUBS_PREFIX')) {
	define('ARRAYSUBS_PREFIX', 'arraysubs');
}

// database table prefix constant: wpdb prefix + plugin prefix
if (!defined('ARRAYSUBS_DB_PREFIX')) {
	global $wpdb;
	define('ARRAYSUBS_DB_PREFIX', $wpdb->prefix . ARRAYSUBS_PREFIX . '_');
}


final class ArraySubs
{
	protected static $pluginDir;
	protected static $initiated;

	public function __construct()
	{
		// initiate only once
		if (self::$initiated === true) {
			return;
		}
		self::$initiated = true;
		self::$pluginDir = plugin_dir_path(__FILE__);

		add_action('plugins_loaded', [$this, 'initiate'], 10);
		add_filter('plugin_row_meta', [$this, 'addPluginRowMeta'], 10, 2);
		register_activation_hook(__FILE__, [$this, 'activatePlugin']);
		register_deactivation_hook(__FILE__, [$this, 'deactivatePlugin']);
	}

	public static function manageConfig()
	{
		// Add plugin configurations individually
		// src path is added from Boot.php
		Config::add('plugin.name', 'ArraySubs');
		Config::add('plugin.version', ARRAYSUBS_VERSION);
		Config::add('plugin.path', trailingslashit(plugin_dir_path(__FILE__)));
		Config::add('plugin.url', trailingslashit(plugin_dir_url(__FILE__)));
		Config::add('plugin.public_url', trailingslashit(plugin_dir_url(__FILE__)) . 'public/');
		Config::add('plugin.public_path', trailingslashit(plugin_dir_path(__FILE__)) . 'public/');
		Config::add('plugin.resources_url', trailingslashit(plugin_dir_url(__FILE__)) . 'src/resources/');
		Config::add('plugin.resources_path', trailingslashit(plugin_dir_path(__FILE__)) . 'src/resources/');
		Config::add('plugin.text_domain', 'arraysubs');
		Config::add('plugin.prefix', ARRAYSUBS_PREFIX);
		Config::add('plugin.file', __FILE__);
		// WordPress related configurations
		Config::add('wp.wp_version', get_bloginfo('version'));
		Config::add('wp.wp_upload_dir', wp_upload_dir());
		// wp-admin dashboard url
		Config::add('wp.wp_admin_url', admin_url());

		// Load user settings into config (merged with defaults)
		$settings = arraysubs_get_settings();
		Config::add('settings', $settings);
	}

	public static function loadFunctions()
	{
		// include all files from functions directory: src/functions/*.php
		// could not use autoloader's classmap due to prefixing vendors.
		foreach (glob(self::$pluginDir . 'src/functions/*.php') as $file) {
			include_once $file;
		}
	}

	public function initiate()
	{
		// dependency check
		include_once self::$pluginDir . 'dependency_check.php';
		$fails = arraysubs_check_dependency();
		if (!empty($fails)) {
			add_action('admin_notices', function () use ($fails) {
?>
				<div class="notice notice-error">
					<h4><?php esc_html_e('ArraySubs plugin is not activated due to the following dependency errors:', 'arraysubs'); ?></h4>
					<ul>
						<?php foreach ($fails as $fail) : ?>
							<li>
								<?php
								printf(
									/* translators: 1: platform name, 2: platform name, 3: required version */
									esc_html__('The %1$s version is not supported or installed. Please upgrade/ install your %2$s to at least %3$s.', 'arraysubs'),
									esc_html($fail['dependency']),
									esc_html($fail['dependency']),
									esc_html($fail['required_version'])
								);
								?>
							</li>
						<?php endforeach; ?>
					</ul>
				</div>
<?php
			});
			return;
		}

		// Declare HPOS compatibility
		add_action('before_woocommerce_init', function () {
			if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
				\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
			}
		});

		// autoload composer dependencies
		// check if self::$pluginDir . 'vendor-prefixed/' dir exists
		if (is_dir(self::$pluginDir . 'vendor-prefixed/')) {
			require_once self::$pluginDir . 'vendor-prefixed/scoper-autoload.php';
		} else {
			require_once self::$pluginDir . 'vendor/scoper-autoload.php';
		}

		self::loadFunctions();
		self::manageConfig();

		do_action('arraysubs_before_boot');
		new \ArraySubs\Boot();
		do_action('arraysubs_after_boot');
	}


	public function activatePlugin()
	{
		// include all files from activation directory by name asc: self::$pluginDir . 'src/plugin-lifecycle/activate-plugin/*-worker.php'
		foreach (glob(self::$pluginDir . 'src/plugin-lifecycle/activate-plugin/*-worker.php') as $file) {
			include_once $file;
		}
	}

	public function deactivatePlugin() {}

	/**
	 * Add extra links to the plugin row in the Plugins list table.
	 *
	 * @param string[] $links Existing row meta links.
	 * @param string   $plugin_file Plugin basename.
	 * @return string[]
	 */
	public function addPluginRowMeta(array $links, string $plugin_file): array
	{
		if (plugin_basename(__FILE__) !== $plugin_file) {
			return $links;
		}

		$links[] = '<a href="https://support.arrayhash.com/arraysubs/" target="_blank" rel="noopener noreferrer">' . esc_html__('User Manual', 'arraysubs') . '</a>';
		$links[] = '<a href="https://arrayhash.com/deals/arraysubs" target="_blank" rel="noopener noreferrer">' . esc_html__('Website', 'arraysubs') . '</a>';

		return $links;
	}
}

new  ArraySubs();
