<?php
/**
 * Seventhqueen\Typer\Base_Support\Component class
 *
 * @package typer
 */

namespace Seventhqueen\Typer\Required_Plugins;

use Seventhqueen\Typer\Component_Interface;
use function Seventhqueen\Typer\typer;


/**
 * Class for adding basic theme support, most of which is mandatory to be implemented by all themes.
 *
 * Exposes template tags:
 * * `typer()->get_version()`
 * * `typer()->get_asset_version( string $filepath )`
 */
class Component implements Component_Interface {

	private $tgm_plugins;
	private $api_url = 'https://updates.seventhqueen.com/check/';

	/**
	 * Gets the unique identifier for the theme component.
	 *
	 * @return string Component slug.
	 */
	public function get_slug() {
		return 'required-plugins';
	}

	/**
	 * Adds the action and filter hooks to integrate with WordPress.
	 */
	public function initialize() {

		$this->tgm_plugins = $this->get_required_plugins();
		/* Load required plugins library */
		require_once __dir__ . '/lib/class-tgm-plugin-activation.php';
		add_action( 'tgmpa_register', [ $this, 'required_plugins' ] );

		$api_url = $this->api_url;
		add_filter( 'http_request_args', static function ( $args, $url ) use ( $api_url ) {
			if ( strpos( $url, $api_url ) !== false ) {
				$args['headers']['Theme-Version'] = typer()->get_version();
				$args['headers']['Theme-Id']      = typer()->get_config( 'item_id' );
				$args['headers']['Package-Code']  = typer()->get_purchased_code();
			}

			return $args;
		}, 10, 2 );

	}

	/**
	 * Check if we want to get the plugins version
	 * When doing AJAX and on modules page
	 * @return bool
	 */
	private function is_addons_page() {
		$in_ajax = wp_doing_ajax() && isset( $_POST['action'] ) && $_POST['action'] === 'sq_do_plugin_action';
		$on_page = isset( $_GET['page'] ) && is_admin() &&
		           ( $_GET['page'] === 'install-required-plugins' || $_GET['page'] === typer()->get_config( 'slug' ) . '-addons' );

		return $in_ajax || $on_page;
	}


	/**
	 * @return array
	 */
	private function get_required_plugins() {
		$required_plugins = [
			[
				'name'               => 'Typer Core',
				'slug'               => 'typer-core',
				'version'            => '1.6.3',
				'required'           => true,
				'force_activation'   => false,
				'force_deactivation' => false,
				'external_url'       => '',
				'description'        => 'Enables Importing and advanced features for Typer.',
				'pro'                => false
			],
			/*[
				'name'               => 'STAX Header Builder',
				'slug'               => 'stax',
				'version'            => '1.3.0',
				'required'           => false,
				'force_activation'   => false,
				'force_deactivation' => false,
				'external_url'       => '',
				'description'        => 'Build your header with an advanced Drag & Drop interface',
				'pro'                => false
			],*/
			[
				'name'               => 'Elementor Page Builder',
				'slug'               => 'elementor',
				'version'            => '2.6.0',
				'required'           => false,
				'force_activation'   => false,
				'force_deactivation' => false,
				'external_url'       => '',
				'description'        => 'Build your pages with an advanced Drag & Drop interface',
				'pro'                => false
			],
			[
				'name'               => 'Visibility Logic Elementor',
				'slug'               => 'visibility-logic-elementor',
				'version'            => '1.0.0',
				'required'           => false,
				'force_activation'   => false,
				'force_deactivation' => false,
				'external_url'       => '',
				'description'        => 'Hide/Show Elementor widgets for logged in, guest or a specific user role.',
				'pro'                => false
			],
			[
				'name'               => 'Import/Export theme settings',
				'slug'               => 'customizer-export-import',
				'required'           => false,
				'version'            => '0.8',
				'force_activation'   => false,
				'force_deactivation' => false,
				'external_url'       => '',
				'description'        => 'Adds a section to the Customizer to import/export options.',
				'pro'                => false
			],
		];

		$required_plugins = apply_filters( 'typer-required-plugins', $required_plugins );

		foreach ( $required_plugins as $key => $plugin ) {
			if ( ! isset( $plugin['source'] ) && isset( $plugin['pro'] ) && $plugin['pro'] ) {
				$required_plugins[ $key ]['source'] = $this->get_plugin_url( $plugin['slug'] );
			}
		}


		return $required_plugins;
	}

	/**
	 * @param $name
	 *
	 * @return string
	 */
	private function get_plugin_url( $name ) {

		$api_url = add_query_arg( 'action', 'download', $this->api_url );
		$api_url = add_query_arg( 'slug', $name . '.zip', $api_url );

		return $api_url;
	}


	/**
	 * Method to register TGMPA plugins
	 */
	public function required_plugins() {
		/**
		 * Array of configuration settings. Amend each line as needed.
		 * If you want the default strings to be available under your own theme domain,
		 * leave the strings uncommented.
		 * Some of the strings are added into a sprintf, so see the comments at the
		 * end of each line for what each argument will be.
		 */
		$config = [
			'id'           => 'tgmpa-typer-' . typer()->get_version(),
			'default_path' => '',                           // Default absolute path to pre-packaged plugins
			//'parent_menu_slug'  => 'themes.php',         // Default parent menu slug
			//'parent_url_slug'   => 'themes.php',         // Default parent URL slug
			'menu'         => 'install-required-plugins',   // Menu slug
			'has_notices'  => true,                         // Show admin notices or not
			'message'      => '',               // Message to output right before the plugins table
			'strings'      => [
				'page_title'                      => esc_html__( 'Install Required Plugins', 'typer' ),
				'menu_title'                      => esc_html__( 'Install Plugins', 'typer' ),
				'installing'                      => esc_html__( 'Installing Plugin: %s', 'typer' ),
				// %1$s = plugin name
				'oops'                            => esc_html__( 'Something went wrong with the plugin API.', 'typer' ),
				'notice_can_install_required'     => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_can_install_recommended'  => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_cannot_install'           => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_can_activate_required'    => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_cannot_activate'          => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_ask_to_update'            => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'typer' ),
				// %1$s = plugin name(s)
				'notice_cannot_update'            => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.', 'typer' ),
				// %1$s = plugin name(s)
				'install_link'                    => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'typer' ),
				'activate_link'                   => _n_noop( 'Activate installed plugin', 'Activate installed plugins', 'typer' ),
				'return'                          => esc_html__( 'Return to Required Plugins Installer', 'typer' ),
				'plugin_activated'                => esc_html__( 'Plugin activated successfully.', 'typer' ),
				'complete'                        => esc_html__( 'All plugins installed and activated successfully. %s', 'typer' )
				// %1$s = dashboard link
			]
		];

		tgmpa( $this->tgm_plugins, $config );
	}

}
