<?php
namespace Barn2\Plugin\WC_Product_Tabs_Pro;

use Barn2\Plugin\WC_Product_Tabs_Pro\Dependencies\Setup_Wizard\Starter;
use Barn2\Plugin\WC_Product_Tabs_Pro\Dependencies\Lib\Plugin\Licensed_Plugin;
use Barn2\Plugin\WC_Product_Tabs_Pro\Dependencies\Lib\Plugin\Plugin_Activation_Listener;
use Barn2\Plugin\WC_Product_Tabs_Pro\Dependencies\Lib\Registerable;

/**
 * Hook into the plugin activation process.
 *
 * @package   Barn2\woocommerce-product-tabs-pro
 * @author    Barn2 Plugins <support@barn2.com>
 * @license   GPL-3.0
 * @copyright Barn2 Media Ltd
 */
class Plugin_Setup implements Plugin_Activation_Listener, Registerable {

	/**
	 * Plugin's entry file
	 *
	 * @var string
	 */
	private $file;

	/**
	 * Plugin instance
	 *
	 * @var Plugin
	 */
	private $plugin;

	/**
	 * Wizard starter
	 *
	 * @var Starter
	 */
	private $starter;

	/**
	 * Get things started
	 *
	 * @param string $file
	 * @param Licensed_Plugin $plugin
	 */
	public function __construct( $file, Licensed_Plugin $plugin ) {
		$this->file    = $file;
		$this->plugin  = $plugin;
		$this->starter = new Starter( $this->plugin );
	}

	/**
	 * Register the service
	 *
	 * @return void
	 */
	public function register(): void {
		register_activation_hook( $this->plugin->get_basename(), [ $this, 'on_activate' ] );
		add_action( 'admin_init', [ $this, 'after_plugin_activation' ] );
	}

	/**
	 * On plugin activation
	 *
	 * @return void
	 */
	public function on_activate(): void {
		// if ( ! $this->plugin->check_all_requirements() ) {
			// set_transient( $this->plugin->get_basename() . '_abort_activation', true );
			// return;
		// }

		// if ( $this->starter->should_start() ) {
		// 	$this->starter->create_transient();
		// }
	}

	/**
	 * Do nothing.
	 *
	 * @return void
	 */
	public function on_deactivate(): void {}

	/**
	 * Detect the transient and redirect to wizard.
	 *
	 * @return void
	 */
	public function after_plugin_activation(): void {
		if ( get_transient( $this->plugin->get_basename() . '_abort_activation' ) && isset( $_GET['activate'] ) ) {
			deactivate_plugins( $this->plugin->get_basename() );
			delete_transient( $this->plugin->get_basename() . '_abort_activation' );
			unset( $_GET['activate'] );

			return;
		}

		if ( ! $this->starter->detected() ) {
			return;
		}

		$this->starter->delete_transient();
		$this->starter->redirect();
	}
}
