<?php
namespace WpieFw\Wpie;

use WpieFw\Templates\Files\WpieTemplatesFileFinder;
use WpieFw\Templates\WpieTemplate;
use WpieFw\Exceptions\WpieExceptionLogger;
use WpieFw\Exceptions\WpieExceptionInterface;
use WpieFw\Helpers\WpieMiscHelper;
use WpieFw\Helpers\WpieMultisiteHelper;

if( ! defined( 'ABSPATH' ) ) exit;

final class WpieAutoUpdate
{
	/**
	 * The TB_iframe popup template file name
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	const TEMPL_NAME_WPIE_AUTO_UPDATE = 'wpie-tpl-auto-update.php';

	/**
	 * The TB_iframe popup title
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	const POPUP_TITLE = 'Auto update plugin';

	/**
	 * The plugin action link text
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	const PLUGIN_ACTION_LINK_AUTO_UPDATE = 'Enable auto updates';

	/**
	 * The Envato Market plugin dir/file
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	const ENVATO_MARKET_PLUGIN_FILE = 'envato-market/envato-market.php';

	/**
	 * The Envato Market plugin URL
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	const ENVATO_MARKET_PLUGIN_URL = 'https://envato.com/market-plugin/';

	/**
	 * The Envato Market plugin download URL
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	const ENVATO_MARKET_PLUGIN_DOWNLOAD_URL = 'https://envato.github.io/wp-envato-market/dist/envato-market.zip';

	/**
	 * Query parameter to flag that the modal is requested
	 * 
	 * @since 2.0.15
	 * 
	 * @var string
	 */
	const WPIE_MODAL_QUERY_PARAM = 'wpie_modal';

	/**
	 * WpieGlobals instance
	 *
	 * @since 2.0
	 *
	 * @var WpieGlobals
	 */
	private $globals;

	/**
	 * The page slug prefix
	 *
	 * The plugin namespace should be appended
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	private $pageSlugPrefix = 'page-wpie-auto-update-';

	/**
	 * The unique page slug for the admin page
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	private $slug = '';

	/**
	 * The admin sub page hook fix
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	private $hookSuffix = '';

	/**
	 * Action for auto updating
	 *
	 * @since 2.0
	 *
	 * @var string
	 */
	private $actionUpdate = 'wpieautoupdate';

	/**
	 * Constructor
	 *
	 * @param WpieGlobals $globals
	 *
	 * @uses self::handleRequest()
	 * @uses self::hook()
	 *
	 * @access public
	 */
	public function __construct( WpieGlobals $globals )
	{
		if( !\WpieFw\Helpers\WpieMiscHelper::fontType( $globals->nameSpace ) ) {
			throw new \WpieFw\Exceptions\WpieFyException( '' );
		}

		$this->globals = $globals;
		// create the unique plugin page slug
		$this->slug = $this->pageSlugPrefix.$this->globals->nameSpace;

		$this->handleRequest();
		$this->hook();
	}

	/**
	 * Callback for the admin_enqueue_scripts hook
	 *
	 * @access public
	 *
	 * @param string $hook_suffix
	 *
	 * @since 2.0
	 *
	 * @uses wp_enqueue_style()
	 */
	public function setStylesAdmin( $hook_suffix )
	{
		if( $hook_suffix === $this->hookSuffix ) {
			wp_enqueue_style( 'wpie-forms',  $this->globals->get( 'wfCssUri' ) .'/form.css' );
			wp_enqueue_style( 'wpie-auto-update',  $this->globals->get( 'wfCssUri' ) .'/auto-update.css' );
		}
	}

	/**
	 * Callback for the plugin_action_links_{$pluginFile} hook
	 *
	 * @access public
	 *
	 * @param array $actions
	 *
	 * @since 2.0
	 *
	 * @return array
	 */
	public function setPluginActionLink( $actions )
	{
		if( ! is_plugin_active( self::ENVATO_MARKET_PLUGIN_FILE ) ) {
			$actions[$this->actionUpdate] = $this->getUpdateLink();
		}

		return $actions;
	}

	/**
	 * Callback for the network_admin_plugin_action_links_{$pluginFile} hook
	 *
	 * @access 	public
	 *
	 * @param array $actions
	 * @param string $pluginFile
	 * @param array $pluginData
	 * @param string $context
	 *
	 * @since 2.0
	 *
	 * @return	array
	 */
	public function setPluginActionLinkNetwork( $actions, $pluginFile, $pluginData, $context )
	{
		if( ! is_plugin_active( self::ENVATO_MARKET_PLUGIN_FILE ) ) {
			$actions[$this->actionUpdate] = $this->getUpdateLink();
		}

		return $actions;
	}

	/**
	 * Callback for the admin_menu hook
	 *
	 * create a WP page without admin menu (parent is null)
	 *
	 * @access public
	 *
	 * @uses add_submenu_page
	 *
	 * @since 2.0
	 */
	public function addPage()
	{
		// Only register the menu when requesting the iFrame popup modal
		if( isset( $_REQUEST[SELF::WPIE_MODAL_QUERY_PARAM] ) ) {
			$this->hookSuffix = add_menu_page( self::POPUP_TITLE, self::POPUP_TITLE, 'manage_options', $this->slug, [ $this, 'renderPage' ] );			
		}		
	}

	/**
	 * Render the TB_iframe content page
	 *
	 * @access public
	 *
	 * @uses WpieTemplatesFileFinder
	 * @uses WpieTemplate::render()
	 * @uses WpieMiscHelper::getPluginData()
	 *
	 * @since 2.0
	 */
	public function renderPage()
	{
		$envatoMarket = new \stdClass();
		$envatoMarket->url = self::ENVATO_MARKET_PLUGIN_URL;
		$envatoMarket->downloadUrl = self::ENVATO_MARKET_PLUGIN_DOWNLOAD_URL;
		$pluginFilePath = $this->globals->get( 'pluginPathFile' );

		try {
			$finder = new WpieTemplatesFileFinder( $this->globals->get( 'wfTemplPath' ), '', '', self::TEMPL_NAME_WPIE_AUTO_UPDATE, false );
			$template = new WpieTemplate( $finder, self::TEMPL_NAME_WPIE_AUTO_UPDATE );

			// set vars for the template
			$template->setVar( 'envato_market', $envatoMarket );
			$template->setVar( 'logo_uri', $this->globals->get( 'wfImgUri' ) . '/logo.svg' );
			$template->setVar( 'plugin_name', WpieMiscHelper::getPluginData( $pluginFilePath, 'Name' ) );

		} catch( WpieExceptionInterface $e ) {
			WpieExceptionLogger::log( $e, true );
			wp_die( $e->getMessage() );
		} catch( \Throwable $e ) {
			WpieExceptionLogger::log( $e, true );
			wp_die( $e->getMessage() );
		}

		$template->render();
	}

	/**
	 * Handle requests
	 *
	 * @access	private
	 *
	 * @since 	1.2.3
	 */
	private function handleRequest()
	{
		if( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === $this->slug ) {
			if( !defined( 'IFRAME_REQUEST' ) ) {
				// setting IFRAME_REQUEST removes the top admin bar
				define( 'IFRAME_REQUEST', true );
			}
		}
	}

	/**
	 * Add all hooks
	 *
	 * @access private
	 *
	 * @since 2.0
	 */
	private function hook()
	{
		if( WpieMultisiteHelper::isMs() && current_user_can( 'manage_network_plugins' ) ) {
			add_action( 'network_admin_menu', [ $this, 'addPage' ] );
			add_filter( 'network_admin_plugin_action_links_' . $this->globals->get( 'pluginFile' ), [ $this, 'setPluginActionLinkNetwork' ], 9999, 4 );
		} elseif( !WpieMultisiteHelper::isMs() && current_user_can( 'manage_options' ) ) {
			add_action( 'admin_menu', [ $this, 'addPage' ] );
			add_filter( 'plugin_action_links_' .$this->globals->get( 'pluginFile' ), [ $this, 'setPluginActionLink' ], 9999 );
		}
		add_action( 'admin_enqueue_scripts', [ $this, 'setStylesAdmin' ] );
	}

	/**
	 * Get the HTML for the auto update link
	 *
	 * @access private
	 *
	 * @since 2.0
	 *
	 * @return string
	 */
	private function getUpdateLink()
	{
		$arialabel = '';
		$title = '';

		if( WpieMultisiteHelper::isMs() ) {
			$url = network_admin_url( sprintf( 'index.php?page=%s&action=%s&%s=true&TB_iframe=true&width=%d&height=%d', $this->slug, $this->actionUpdate, SELF::WPIE_MODAL_QUERY_PARAM, 600, 300 ) );
		} else {
			$url = admin_url( sprintf( 'admin.php?page=%s&action=%s&%s=true&TB_iframe=true&width=%d&height=%d', $this->slug, $this->actionUpdate, SELF::WPIE_MODAL_QUERY_PARAM, 600, 300 ) );
		}

		$link = sprintf( '<a class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s" href="%s">%s</a>', $arialabel, $title, $url, __( self::PLUGIN_ACTION_LINK_AUTO_UPDATE, 'weepie' ) );

		return $link;
	}
}