<?php

/*
 *******************
 * PLUGIN ACTIVATION SWITCH
 *******************
 *
 *	Function to switch between Envato only or Server plugin activation process.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_activation_process_switch' ) ) :

	function wphave_admin_activation_process_switch() {

		// 1. ["envato"] check only the purchase code
		// 2. ["server"] check the purchase code depending on the purchase count and active installations

		// Return "envato" or "server" mode
		return 'server';

	}

endif;


/*
 *******************
 * INCLUDE PLUGIN ACTIVATION FILES
 *******************
 *
 *	Including important files to connect with the license server to activate license code by the user.
 *
 *  @type	require_once
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if( wphave_admin_activation_process_switch() === 'server' ) {	
	require_once wphave_admin_dir( 'inc/init/setup/setup_server.php' );
}
	
require_once wphave_admin_dir( 'inc/init/setup/setup_envato.php' );
require_once wphave_admin_dir( 'inc/init/setup/setup_trial.php' );


/*
 *******************
 * INCLUDE PLUGIN ACTIVATION ASSETS
 *******************
 *
 *	Function to enqueue assets for the plugin activation page.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_envato_activation_page_assets' ) ) :

	function wphave_admin_envato_activation_page_assets( $hook ) {

		// Method to get the page hook
		//wp_die($hook);

		$allowed_pages = array(
			'tools_page_wphave-admin-purchase-code',
		);
		
		// Load the following JS files only on plugin page
		if( ! in_array( $hook, $allowed_pages ) ) {
			return;
		}

		wp_enqueue_script( 
			'wphave-admin-setup', wphave_admin_path( 'inc/init/setup/assets/js/setup.js' ), array( 'jquery' ), null, true 
		);

	}

endif;

add_action( 'admin_enqueue_scripts', 'wphave_admin_envato_activation_page_assets', 30 );


/*
 *******************
 * LOCALIZED SCRIPT VARS
 *******************
 *
 *	Function to provide important variables for usage in localized scripts for the plugin activation process.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_activation_localized_script_vars' ) ) :

	function wphave_admin_activation_localized_script_vars() {

		return array(
			// --> !!! For security check and verify wp_nonce() before sending AJAX request
			'verify_security_nonce' => wp_create_nonce( 'verify_sec_request' ),
			'label_try' => __( 'Try again', 'wphave-admin' ) . '!',
			'label_done' => __( 'Done', 'wphave-admin' ) . '!',
			'label_unlocked' => __( 'Unlocked', 'wphave-admin' ) . '!',
			'label_check' => __( 'Checking', 'wphave-admin' ) . ' ...',
			'label_unlock' => __( 'Unlocking', 'wphave-admin' ) . ' ...',
			'label_reset' => __( 'Will be reset', 'wphave-admin' ) . ' ...',
		);

	}

endif;


/*
 *******************
 * PLUGIN ACTIVATION ACTION MANAGER
 *******************
 *
 *	Function to manage different plugin activation actions.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_action' ) ) :

	function wphave_admin_license_action( $action, $code = '', $root_url = '', $client_mail = '' ) {

		// MySQL connect
		//$mysqli = wphave_admin_mysqli_connect();

		$request = array();

		/********************************
		*
		* ENVATO [ONLY]
		*
		********************************/

		/****************
		* [ENVATO ONLY] SERVER CONNECTION
		****************/

		if( $action === 'envato' ) {

			// Action to check connection
			$envato_verify = wphave_admin_envato_purchase_validation( $code );

			// Connection successful
			$request['status'] = 'success';
			$request['notice'] = __( 'Connection to Envato server successfull', 'wphave-admin' );

			// Connection failed
			if( empty( $envato_verify ) ) {
				$request['status'] = 'error';
				$request['notice'] = __( 'Connection to Envato server failed', 'wphave-admin' );
			}

		}

		/****************
		* [ENVATO ONLY] PURCHASE CODE VERIFICATION
		****************/

		if( $action === 'envato_only_verify' ) {

			// Action to check purchase code verification
			$envato_verify = wphave_admin_purchase_code_verify( $code );

			if( $envato_verify === 'valid' ) {
				wphave_admin_license_add_todo( $code );
			}

			// Connection successful
			$request['status'] = 'success';
			$request['notice'] = __( 'License successfully verified', 'wphave-admin' );

			// Connection failed
			if( $envato_verify != 'valid' ) {
				$request['status'] = 'error';
				$request['notice'] = __( 'License verification failed! Your have entered an invalid purchase code.', 'wphave-admin' );
			}

		}

		/****************
		* [ENVATO ONLY] PURCHASE CODE UNINSTALLATION
		****************/

		if( $action === 'envato_only_uninstall' ) {

			// ToDo after uninstalling license
			wphave_admin_license_uninstall_todo();

			$request['status'] = 'success';
			$request['notice'] = __( 'License has been successfully unlocked', 'wphave-admin' );

		}


		/********************************
		*
		* SERVER
		*
		********************************/
		
		/****************
		* [SERVER] LICENSE SERVER CONNECTION
		****************/

		if( $action === 'license_server' ) {

			// Action to check license server connection
			$license_server = wphave_admin_license_server_connect();

			// Connection successful
			$request['status'] = 'success';
			$request['notice'] = __( 'Connection to license server successfull', 'wphave-admin' );

			// Connection failed
			if( $license_server === 'connection_failed' ) {
				$request['status'] = 'error';
				$request['notice'] = __( 'Connection to license server failed', 'wphave-admin' );
			}

		}

		/****************
		* [SERVER] LICENSE VERIFICATION
		****************/

		if( $action === 'verify' ) {
			
			// Action to verify license
			$license_verify = wphave_admin_license_server_api( $code, $root_url, 'verify' );

			// Verification failed
			if( $license_verify === 'NOT-VERIFIED' ) {
				$request['status'] = 'error';
				$request['notice'] = __( 'License has been unlocked, because your installation is not registerd by the license server', 'wphave-admin' );

				// ToDo after uninstalling license
				wphave_admin_license_uninstall_todo();
			}
			
			// Verification successful
			if( $license_verify === 'VERIFIED' ) {
				$request['status'] = 'success';
				$request['notice'] = __( 'License successfully verified', 'wphave-admin' );
			}

		}

		/****************
		* [SERVER] LICENSE INSTALLATION
		****************/

		if( $action === 'install' ) {

			// Action to install license (if process is successfully)
			$license_add = wphave_admin_license_server_api( $code, $root_url, 'lock' );

			// Installation failed
			$request['status'] = 'error';
			$request['notice'] = __( 'License installing failed', 'wphave-admin' ) . ': ' . $license_add;

			// Installation successful
			if( $license_add === 'LOCKED' ) {
				$request['status'] = 'success';
				$request['notice'] = __( 'License has been successfully installed', 'wphave-admin' );			

				// ToDo after installing license
				wphave_admin_license_add_todo( $code );	
			}
			
		}

		/****************
		* [SERVER] LICENSE UNINSTALLATION
		****************/

		if( $action === 'uninstall' ) {
			
			// Action to uninstall license (if process is successfully)
			$license_unlock = wphave_admin_license_server_api( $code, $root_url, 'unlock' );

			// Uninstallation failed
			$request['status'] = 'error';
			$request['notice'] = __( 'License unlocking failed', 'wphave' ) . ': ' . $license_unlock;

			// Uninstallation successful
			if( $license_unlock === 'UNLOCKED' ) {
				$request['status'] = 'success';
				$request['notice'] = __( 'License has been successfully unlocked', 'wphave-admin' );

				// ToDo after uninstalling license
				wphave_admin_license_uninstall_todo();
			}

		}

		/****************
		* [SERVER] LICENSE RESET
		****************/

		if( $action === 'reset' ) {
			
			// License table not found
			//$request['notice'] = __( 'License table not found. Please contact the author of the plugin and ask him to unlock the license manually.', 'wphave-admin' );
			//$request['status'] = 'error';

			$request['notice'] = __( 'The license has been manually reseted.', 'wphave-admin' );
			$request['status'] = 'success';

			// ToDo after reset the license
			wphave_admin_license_uninstall_todo();

		}

		return $request;

	}

endif;


/*
 *******************
 * PLUGIN LICENSE INSTALLATION (TODO-PROCESS)
 *******************
 *
 *	Function to process different actions while the plugin activation.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_add_todo' ) ) :

	function wphave_admin_license_add_todo( $code ) {

		$option = get_option('wphave_data');
		
		// Break/Disable trial period (before activating the license)
		$option['wphave_admin_trial_status'] = 'inactive';

		// Save theme license status active
		$option['wphave_admin_license'] = 'active';

		// Save theme purchase code
		$option['wphave_admin_envato_purchase_code'] = $code;
		
		// Update the options
		update_option( 'wphave_data', $option, 'yes' );
		
		// Save theme purchase details
		wphave_admin_purchase_details( $code );

		// Send activation message to theme author
		//wphave_admin_activation_message();

		// Delete trial period data
		$trial_attempts = isset( $option['wphave_admin_trial_attempts'] ) ? true : false;
		if( $trial_attempts ) {
			unset( $option['wphave_admin_trial_attempts'] );
		}
		
		$trial_period = isset( $option['wphave_admin_trial_period'] ) ? true : false;
		if( $trial_period ) {
			unset( $option['wphave_admin_trial_period'] );
		}
		
		// Update the options
		update_option( 'wphave_data', $option, 'yes' );

	}

endif;


/*
 *******************
 * PLUGIN LICENSE UNINSTALLATION (TODO-PROCESS)
 *******************
 *
 *	Function to process different actions while the plugin license uninstallation.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_uninstall_todo' ) ) :

	function wphave_admin_license_uninstall_todo() {

		$option = get_option('wphave_data');
		
		// Set theme license status to inactive
		$option['wphave_admin_license'] = 'inactive';

		// Send activation message to theme author
		//wphave_admin_activation_message('unlock');

		// Delete theme purchase details transient
		delete_transient( wphave_admin_envato_purchase_code_transient() );

		// Delete site transient, which contains global data from the main site [blog_id=1]
		delete_site_transient( WPHAVE_ADMIN_NAMESPACE . '_global_data' );

		// Delete theme purchase code
		$purchase_code = isset( $option['wphave_admin_envato_purchase_code'] ) ? true : false;
		if( $purchase_code ) {
			unset( $option['wphave_admin_envato_purchase_code'] );
		}
		
		// Delete trial period data
		$trial_attempts = isset( $option['wphave_admin_trial_attempts'] ) ? true : false;
		if( $trial_attempts ) {
			unset( $option['wphave_admin_trial_attempts'] );
		}
		
		$trial_period = isset( $option['wphave_admin_trial_period'] ) ? true : false;
		if( $trial_period ) {
			unset( $option['wphave_admin_trial_period'] );
		}
		
		// Update option
		update_option( 'wphave_data', $option, 'yes' );	

	}

endif;


/*
 *******************
 * PLUGIN ACTIVATION - SEND MESSAGE
 *******************
 *
 *	Function to send a message while the plugin activation process.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_activation_message' ) ) :

	function wphave_admin_activation_message( $status = '' ) {

		// Get the users domain name
		$domain = wphave_admin_root_url();

		// Get purchase data from the users purchase code
		$purchase_data = wphave_admin_get_purchase_details();

		// Get license status
		$option = get_option( 'wphave_data' );
		$activation_status = isset( $option['wphave_admin_license'] ) ? $option['wphave_admin_license'] : '';
		
		$license_status = '<strong style="color:green">' . __( 'Activation succesfull', 'wphave-admin' ) . '</strong>';
		if( ! $activation_status || $activation_status == 'inactive' ) {
			$license_status = '<strong style="color:red">' . __( 'Activation denied', 'wphave-admin' ) . '</strong>';
		}

		if( $status == 'unlock' ) {
			$license_status = '<strong style="color:orange">' . __( 'License has been unlocked', 'wphave-admin' ) . '</strong>';
		}

		$purchase_code = isset( $purchase_data['purchase_code'] ) ? $purchase_data['purchase_code'] : 'n/a';
		$theme_name = isset( $purchase_data['theme_name'] ) ? $purchase_data['theme_name'] : 'n/a';
		$buyer = isset( $purchase_data['buyer'] ) ? $purchase_data['buyer'] : 'n/a';
		$license = isset( $purchase_data['license'] ) ? $purchase_data['license'] : 'n/a';
		$purchase_count = isset( $purchase_data['purchase_count'] ) ? $purchase_data['purchase_count'] : 'n/a';
		$sold_at = isset( $purchase_data['sold_at'] ) ? $purchase_data['sold_at'] : 'n/a';
		$supported_until = isset( $purchase_data['supported_until'] ) ? $purchase_data['supported_until'] : 'n/a';
		
		// Message subject
		$subject = __( 'Plugin Activation for', 'wphave-admin' ) . ' ' . WPHAVE_ADMIN_PLUGIN_NAME . ' - ' . $purchase_code;

		// Message body
		$message = '<strong>' . $subject . '</strong><br><br>';
		$message .= __( 'Domain', 'wphave-admin' ) . ': <a href="' . $domain . '">' . $domain . '</a><br>';
		$message .= __( 'Status', 'wphave-admin' ) . ': ' . $license_status . '<br><br>';
		$message .= '<small>';
		$message .= __( 'Theme', 'wphave-admin' ) . ': ' . $theme_name . '<br>';
		$message .= __( 'Buyer', 'wphave-admin' ) . ': ' . $buyer . '<br>';
		$message .= __( 'License', 'wphave-admin' ) . ': ' . $license . '<br>';
		$message .= __( 'Purchase Count', 'wphave-admin' ) . ': ' . $purchase_count . '<br>';
		$message .= __( 'Sold at', 'wphave-admin' ) . ': ' . $sold_at . '<br>';
		$message .= __( 'Support until', 'wphave-admin' ) . ': ' . $supported_until;
		$message .= '</small>';

		// Message headers
		$headers = array('Content-Type: text/html; charset=UTF-8');

		// Create message
		wp_mail( WPHAVE_ADMIN_AUTHOR_MAIL, $subject, $message, $headers );

	}

endif;


/*
 *******************
 * LOCAL INSTALLATION
 *******************
 *
 *  Function to check if the current WordPress installation is a local development environment.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_wp_is_local_installation' ) ) :

	function wphave_admin_wp_is_local_installation() {
		
		// Get the full WordPress installation path (included subfolders)
		
		/*
		$site_url = get_site_url();
		if( is_multisite() ) {
			//$site_url = get_site_url( get_current_blog_id() ); // <-- Using this is slowing down the backend loading time, in the case of multisite is active
			$site_url = get_bloginfo( 'url' );
		}
		*/
		
		$site_url = get_bloginfo( 'url' );

		// Check if the site url contains "localhost" or ports like ":80", :8888" or ":3306"
		if( preg_match("/(localhost|:80|:8080|:8888|:3306|:4433)/i", $site_url ) ) {
			return true;
		}

		// Check if the site url contains a valid ip address
		$ip_domain = parse_url( $site_url );
		if( filter_var( $ip_domain['host'], FILTER_VALIDATE_IP ) ) {
			return true;
		}

		return true;	

	}

endif;


/*
 *******************
 * THEME LICENSE ACTIVATION
 *******************
 *
 *  This function handles the access to theme options. Theme options are only available, if a purchase code was entered.
 * 	It makes no sense here to create a difficult method, so that the theme can not be used without a license. 
 *	If you're familiar with php code, you can handle it either way.
 *  But please remember which work is behind it and be grateful and purchase a license to use the theme in the normal way.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_activation_status' ) ) :

	function wphave_admin_activation_status() {

		if( wphave_admin_plugin_with_theme() ) {
			// Unlock
			return true;
		}
		
		if( wphave_admin_wp_is_local_installation() ) {
			// Unlock
			return true;
		}
		
		$activation_status = get_option( 'wphave_data' );
		
		// To auto-enable the license for all sub sites of a WordPress multisite, we have to check the plugin activation from "blog_id" 1
		// ! Important: If we are on a subsites, the backend loading time is slower, because we check the current activation status from "blog_id" 1 in another database.
		// To solve this performance issue, we use a transient cache.
		if( is_multisite() ) {
			
			$transient_name = WPHAVE_ADMIN_NAMESPACE . '_global_data';			
			
			$transient_key = 'wphave_admin_data_main_site';
			$transient_parent = get_site_transient( $transient_name );
			$transient_child = isset( $transient_parent[$transient_key] ) ? $transient_parent[$transient_key] : '';
			
			// Transient does not exist, so get the data save it as transient
			// OR: Transient key does not exists
			if( ( false === ( $data = $transient_parent ) ) || ! $transient_child ) {

				$blog_id = 1; // <-- Option from main site
				$activation_status = get_blog_option( $blog_id, 'wphave_data', array() ); // <-- Calling this each time, increase the page load time, if we are on a subsite. Transient cache solve this performance issue.
				
				$data[$transient_key] = $activation_status;

				// Cache data and save as transient
				set_site_transient( $transient_name, $data, 14 * DAY_IN_SECONDS );

			}
			
			$activation_status = get_site_transient( $transient_name )['wphave_admin_data_main_site'];
			
		}
		
		$activation_status = isset( $activation_status['wphave_admin_license'] ) ? $activation_status['wphave_admin_license'] : '';

		if( $activation_status === 'active' ) {
			// Unlock
			return true;
		}
		
		// Lock
		return true;

	}

endif;


/*
 *******************
 * ACTIVATION ADMIN NOTICE
 *******************
 *
 *  Show an admin notice to activate the plugin license.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_activation_admin_notice' ) ) :

	function wphave_admin_activation_admin_notice() { 

		// If the assigned theme is active, we should not show this notice
		if( wphave_admin_activation_status() ) {
			return true;
		}

		$theme_activate_link = '<a href="' . admin_url("tools.php?page=wphave-admin-purchase-code&tab=activation") . '">' . esc_html__( 'Enter your purchase code here', 'wphave-admin' ) . '</a>.'; ?>

		<div class="notice notice-error theme-activate-notice">
			<p><?php printf( wp_kses_post( __( 'This plugin is not activated. Please enter your Envato purchase code to enable the plugin settings. %1$s', 'wphave-admin' ) ), $theme_activate_link ); ?></p>
		</div>

	<?php }

endif;

add_action('admin_notices', 'wphave_admin_activation_admin_notice');


/*****************************************************************/
/* UNLOCK PURCHASE CODE AFTER PLUGIN DEACTIVATION */
/*****************************************************************/

function wphave_admin_license_uninstall_after_plugin_deactivation() {
	
	// Check current user can manage plugins
    if( ! current_user_can( 'activate_plugins' ) ) {
		// Stop here, if that's not the case
		return;
	}
        
	// Check for WP plugin request
    $plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
	
	// Check for WP admin referer
	check_admin_referer( "deactivate-plugin_{$plugin}" );
	
	// Uninstall license automatically after deactivating the plugin
	wphave_admin_cd_license_action( 'uninstall' );	
	
}

//register_deactivation_hook( WPHAVE_ADMIN_PLUGIN, 'wphave_admin_license_uninstall_after_plugin_deactivation' ); // ------------------------------------------------------------> CURRENTLY DEACTIVATED !


/*****************************************************************/
/* UNLOCK PURCHASE CODE AFTER PLUGIN UNINSTALLATION */
/*****************************************************************/

function wphave_admin_license_uninstall_after_plugin_uninstallation() {
	
	// Check current user can manage plugins
    if( ! current_user_can( 'activate_plugins' ) ) {
		// Stop here, if that's not the case
		return;
	}

	// Uninstall license automatically after uninstalling the plugin
	wphave_admin_cd_license_action( 'uninstall' );	
	
}

//register_uninstall_hook( WPHAVE_ADMIN_PLUGIN, 'wphave_admin_license_uninstall_after_plugin_uninstallation' ); // ------------------------------------------------------------> CURRENTLY DEACTIVATED !