<?php 

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

if ( ! function_exists( 'wphave_admin_activation_js' ) ) :

	function wphave_admin_activation_js( $hook ) {

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

		// Load the following JS files only on theme welcome page
		if( $hook != 'tools_page_wphave-admin-purchase-code' ) {
			return;
		}

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

		wp_localize_script( 
			'wphave-admin-activation', 'wp_ajax_data', array( 'wp_ajax_url' => admin_url( 'admin-ajax.php' ),
		));

		// Localize the script with new data
		$vars = wphave_admin_activation_localized_script_vars();
		wp_localize_script( 'wphave-admin-activation', 'WP_JS_Theme_Activation', $vars );

	}

endif;

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


/*
 *******************
 * PLUGIN [LICENSE SERVER] CONNECTION TEST
 *******************
 *
 *	Function to check if the connection to the license server failed or not.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_server_connect' ) ) :

	function wphave_admin_license_server_connect() {

		// License server API url
		$url = 'https://license.wphave.com/api/wphave-license/v1/lock/';	
		$curl = curl_init( $url );

		$header = array();
		//$header[] = 'Authorization: Bearer ' . $token;
		//$header[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:41.0) Gecko/20100101 Firefox/41.0';
		$header[] = 'User-Agent: Envato purchase code verification';
		$header[] = 'timeout: 20';

		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt( $curl, CURLOPT_HTTPHEADER, $header );	
		$serverData = curl_exec( $curl );			

		// Check for curl error
		if( $serverData === false ) {
			// Send server connection failed (downtime)
			return 'connection_failed';
		}

		curl_close( $curl );
		$serverData = json_decode( $serverData );

		// Connection successfull
		return true;			

	}

endif;


/*
 *******************
 * PLUGIN [SERVER] LICENSE API CONNECTION
 *******************
 *
 *	Function to connect the license server API.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_server_api' ) ) :

	function wphave_admin_license_server_api( $purchase_code, $installation_url, $action = '' ) {	

		if( ! $action ) {
			$action = 'lock';
		}

		$ip_address = '';
		
		/*
		if( $action === 'lock' ) {		
			$ip_address = $_SERVER['REMOTE_ADDR'];
			$ip_address = '&ip_address=' . $ip_address;
		}
		*/

		// Create a pasword hash to authenticate this process
		// In this way, we can't use the API directly without adding the correct pasword hash
		$wp_verify = '$2y$10$rR4gBSlR3X3tMNueQmD19eiTKBrULBPv/yKQkEWgf1BRYLXaTi7mW';	

		$data_args = array(
			'timeout' => 30,
		);

		// Access the license server API to do actions and get response data
		$url = 'https://license.wphave.com/api/wphave-license/v1/' . $action . '/?purchase_code=' . $purchase_code . '&installation_url=' . $installation_url . '&product_id=' . WPHAVE_ADMIN_ENVATO_ID . '&wp_verify=' . $wp_verify . $ip_address;	
		$response = wp_remote_get( $url, $data_args );

		// Check the response code
		$response_code = wp_remote_retrieve_response_code( $response );

		// Get the response data
		$data = json_decode( wp_remote_retrieve_body( $response ), true );
		
		// Check for API error response
		$is_error = isset( $data['error'] ) ? $data['error'] : '';

		if( $is_error ) {
			return $is_error;
		}
		
		// Get API response
		$data = isset( $data['success'] ) ? $data['success'] : 'ERROR';
		
		return $data;

	}

endif;


/*
 *******************
 * PLUGIN [SERVER] PURCHASE CODE AJAX CHECK
 *******************
 *
 *	Function to activate the passed purchase code via AJAX.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_install_process' ) ) :

	function wphave_admin_license_install_process() {

		// --> !!! For security check and verify wp_nonce() before saving new values from AJAX request
		check_ajax_referer( 'verify_sec_request', 'security' );

		if( $_POST ) {		

			// Get user purchase code from theme validation check
			$request = json_decode( stripslashes( $_POST['fieldData'] ) );

			if( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
				$code = $request[0]->purchase_code;
				$root_url = $request[0]->purchase_root_url;
			}

			$license_action = __( 'Something went wrong', 'wphave-admin' );

			// 1. Check if there is a connection to the license server
			if( wphave_admin_license_action( 'license_server' )['status'] == 'success' ) {	

				// 2. Send install license notice (if process is successfully set theme license to active)
				$license_action = wphave_admin_license_action( 'install', $code, $root_url );

			} else {

				// 2. License Server connection failed
				// Cancel license installation and send server connection notice
				$license_action = wphave_admin_license_action( 'license_server' );

			}

			wp_send_json( array(
				//'success' => 'SUCCESS',
				//'fieldData' => $request,
				'license_action' => $license_action['notice'],
				'license_status' => $license_action['status']
			) );			

		}

		die();

	}

endif;

add_action( 'wp_ajax_wphave_admin_license_install_process', 'wphave_admin_license_install_process' );
add_action( 'wp_ajax_nopriv_wphave_admin_license_install_process', 'wphave_admin_license_install_process' );


/*
 *******************
 * PLUGIN [SERVER] UNLOCK PURCHASE CODE AJAX
 *******************
 *
 *	Function to unlock the current used purchase code via AJAX.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_uninstall_process' ) ) :

	function wphave_admin_license_uninstall_process() {

		// --> !!! For security check and verify wp_nonce() before saving new values from AJAX request
		check_ajax_referer( 'verify_sec_request', 'security' );

		if( $_POST ) {		

			// Get client action to uninstall license
			$request = json_decode( stripslashes( $_POST['fieldData'] ) );

			if( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
				$action = $request[0]->command;
				$code = $request[0]->purchase_code;
				$root_url = $request[0]->purchase_root_url;
			}

			$license_action = __( 'Something went wrong', 'wphave-admin' );

			// 1. Check for client unlocking license request
			if( $action == 'unlock_purchase_code' ) {

				// 2. Check if there is a connection to the license server
				if( wphave_admin_license_action( 'license_server' )['status'] == 'success' ) {	

					// 3. Send uninstall license notice (if process is successfully set theme license to inactive)
					$license_action = wphave_admin_license_action( 'uninstall', $code, $root_url );				

				} else {			

					// 3. License Server connection failed
					// Cancel license uninstallation and send server connection notice
					$license_action = wphave_admin_license_action( 'license_server' );

				}
			}

			wp_send_json( array(
				//'success' => 'SUCCESS',
				'license_action' => $license_action['notice'],
				'license_status' => $license_action['status'],
			) );			

		}

		die();

	}

endif;

add_action( 'wp_ajax_wphave_admin_license_uninstall_process', 'wphave_admin_license_uninstall_process' );
add_action( 'wp_ajax_nopriv_wphave_admin_license_uninstall_process', 'wphave_admin_license_uninstall_process' );


/*
 *******************
 * PLUGIN [SERVER] RESET LICENSE / PURCHASE CODE AJAX
 *******************
 *
 *	Function to reset the current used purchase code via AJAX.
 *
 *  @type	action
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_reset_process' ) ) :

	function wphave_admin_license_reset_process() {

		// --> !!! For security check and verify wp_nonce() before saving new values from AJAX request
		check_ajax_referer( 'verify_sec_request', 'security' );

		if( $_POST ) {		

			// Get client action to reset license
			$request = json_decode( stripslashes( $_POST['fieldData'] ) );

			if( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
				$action = $request[0]->command;
			}

			$license_action = __( 'Something went wrong', 'wphave-admin' );		

			// 1. Check for client reset license request
			if( $action == 'reset_purchase_code' ) {		

				// Reset the license and send reset notice
				$license_action = wphave_admin_license_action( 'reset' );

			}

			wp_send_json( array(
				//'success' => 'SUCCESS',
				'license_action' => $license_action['notice'],
				'license_status' => $license_action['status'],
			) );			

		}

		die();

	}

endif;

add_action( 'wp_ajax_wphave_admin_license_reset_process', 'wphave_admin_license_reset_process' );
add_action( 'wp_ajax_nopriv_wphave_admin_license_reset_process', 'wphave_admin_license_reset_process' );


/*
 *******************
 * PLUGIN [SERVER] VERIFY LICENSE PERIODICALLY
 *******************
 *
 *	Function to periodically verify the active license (update the purchase details) and to unlock, if the installation is no more registered by the license server.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_verify' ) ) :

	function wphave_admin_license_verify() {

		if( wphave_admin_plugin_with_theme() ) {
			// Do not perform, if the plugin is combinated with the assigned theme
			return false;
		}
	
		/*
		******/
		
		$option = get_option( 'wphave_data' );
		$activation_status = isset( $option['wphave_admin_license'] ) ? $option['wphave_admin_license'] : '';

		// Check for theme license has not been activated yet or is "inactive"
		if( $activation_status !== 'active' ) {
			// So this function can only be fired if the theme is already activated
			// --> This avoids MySQL connections on every backend request
			return false;
		}
	
		/*
		******/

		// Get transient name
		$transient_name = WPHAVE_ADMIN_NAMESPACE . '_plugin_license_verify';

		// Get the purchase code
		$purchase_code = isset( $option['wphave_admin_envato_purchase_code'] ) ? $option['wphave_admin_envato_purchase_code'] : '';		
		
		// Check if license has been verificated in the last 14 days
		if( get_transient( $transient_name ) != 'verificated' ) {
			// Verificate license
			wphave_admin_license_action( 'verify', $purchase_code, wphave_admin_root_url() );
		}

		// Transient does not exist, so create a new transient
		// --> Asking for transient avoids MySQL connections on every backend request, if the theme license is already "active"
		if( false === ( $data = get_transient( $transient_name ) ) ) {

			// Transient key
			$data = 'verificated';

			// Call Envato user data from purchase code each 14 days and resave it to trasient
			$verify_code = '';
			if( $purchase_code ) {
				$verify_code = $purchase_code;
			}			
			wphave_admin_purchase_details( $verify_code );

			// Save the new transient for 14 days
			// --> After creating the new transient, verify the theme license again
			set_transient( $transient_name, $data, 14 * DAY_IN_SECONDS );

		}

	}

endif;

add_action('admin_init', 'wphave_admin_license_verify');


/*
 *******************
 * PLUGIN [SERVER] UNINSTALL LICENSE IF THE THEME HAS BEEN DEACTIVATED / UNINSTALLED
 *******************
 *
 *	Function to automatically uninstall the license if the assigned theme has been deactivated.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_uninstall_after_theme_deactivation' ) ) :

	function wphave_admin_license_uninstall_after_theme_deactivation() {

		$option = get_option( 'wphave_data' );
		$activation_status = isset( $option['wphave_admin_license'] ) ? $option['wphave_admin_license'] : '';

		// Check for theme license is already "inactive"
		if( $activation_status === 'inactive' ) {
			// So this function can only be fired once directly after deactivation of the theme
			// --> This avoids MySQL connections on every backend request
			return false;
		}
	
		/*
		******/

		// Define required theme
		$theme_is_active = function_exists( 'wphave_theme_is_activated' );

		// Check if the currently activated theme does not match the main theme name of "wphave"
		// --> If an other theme is detected 
		if( ! $theme_is_active ) {

			// --> Uninstall theme licence automatically after deactivating or uninstalling the theme
			return wphave_admin_license_action( 'uninstall' );

		}

		return false;

	}

endif;

//add_action('admin_init', 'wphave_admin_license_uninstall_after_theme_deactivation'); // ------------------------------------------------------------> CURRENTLY DEACTIVATED !


/*
 *******************
 * PLUGIN [SERVER] UNINSTALL LICENSE AFTER THEME SWITCH
 *******************
 *
 *	Function to automatically uninstall the license if the active theme has been switched.
 *
 *  @type	function
 *  @date	06/18/19
 *  @since	2.0
 *
 *  @param	N/A
 *  @return	N/A
 *
*/

if ( ! function_exists( 'wphave_admin_license_uninstall_after_theme_switch' ) ) :

	function wphave_admin_license_uninstall_after_theme_switch() {

		$option = get_option( 'wphave_data' );
		$activation_status = isset( $option['wphave_admin_license'] ) ? $option['wphave_admin_license'] : '';

		// Check for theme license is already "inactive"
		if( $activation_status === 'inactive' ) {
			// So this function can only be fired once directly after switching the theme
			// --> This avoids a unnecessary MySQL connections
			return false;
		}
	
		/*
		******/

		// --> Uninstall theme licence automatically after switching the theme
		wphave_admin_license_action( 'uninstall' );

	}

endif;

//add_action('after_switch_theme', 'wphave_admin_license_uninstall_after_theme_switch'); // ------------------------------------------------------------> CURRENTLY DEACTIVATED !