<?php

namespace Barn2\Plugin\Password_Protected_Categories\Admin;

use Barn2\Plugin\Password_Protected_Categories\Dependencies\Setup_Wizard\Starter;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Plugin\Licensed_Plugin;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Plugin\Plugin_Activation_Listener;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Registerable;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Service\Core_Service;
use Barn2\Plugin\Password_Protected_Categories\PPC_Util;;

/**
 * Plugin setup.
 * 
 * @package   Barn2\password-protected-categories
 * @author    Barn2 Plugins <support@barn2.com>
 * @license   GPL-3.0
 * @copyright Barn2 Media Ltd
 */
class Plugin_Setup implements Plugin_Activation_Listener, Registerable, Core_Service {
	/**
	 * Plugin's entry file
	 *
	 * @var string
	 */
	private $file;

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

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

	/**
	 * Get things started
	 *
	 * @param string $file
	 */
	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() {
		add_action( 'admin_init', [ $this, 'after_plugin_activation' ] );
	}

	/**
	 * On plugin activation determine if the setup wizard should run.
	 *
	 * @param bool $network_wide Whether the plugin is being activated network-wide.
	 * @return void
	 */
	public function on_activate( $network_wide = false ) {
		// Network wide.
		// phpcs:disable
		$network_wide = ! empty( $_GET['networkwide'] )
			? (bool) $_GET['networkwide']
			: false;
		// phpcs:enable

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

		// When license not activated and ppc_options were not saved
		$ppc_options = get_option( PPC_Util::OPTION_NAME );
		if ( $ppc_options === false && !$this->plugin->has_valid_license() ) {
			PPC_Util::update_options( PPC_Util::default_options() );
		}
	}

	/**
	 * Do nothing.
	 *
	 * @param bool $network_wide Whether the plugin is being deactivated network-wide.
	 * @return void
	 */
	public function on_deactivate( $network_wide = false ) {}

	/**
	 * Detect the transient and redirect to wizard.
	 *
	 * @return void
	 */
	public function after_plugin_activation() {
		if ( ! $this->starter->detected() ) {
			return;
		}

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