<?php

// Create a Menu for Activate License
function amike_admin_menu() {
    if (is_admin()) {
        add_menu_page( __( 'Activate License', 'amike' ),  __( 'Activate License', 'amike' ), 'manage_options', 'activate-license','amike_activate_license_page_content', 'dashicons-admin-network', 10 );
    }
}
add_action('admin_menu','amike_admin_menu' );

// Settings Page for Activate License ( callback function )
function amike_activate_license_page_content() { ?>
    <div class="wrap">               
    	<h1><?php echo esc_html__( 'Activate License', 'amike' ) ?></h1>

		<div class="update-nag">
			<?php echo esc_html__('Please visit the', 'amike' ); ?>
			<a target="_blank" href="https://help.market.envato.com/hc/en-us/articles/202822600-Where-Is-My-Purchase-Code-"><?php echo esc_html__('Where Is My Purchase Code?', 'amike' ); ?></a>
			<?php echo esc_html__('documentation page for full setup instructions.', 'amike' ); ?>
		</div>

        <form action='options.php' method='post'>
	        <?php
	        settings_fields('amike_activate_license_group');
	        do_settings_sections('amike_activate_license_section');
	        submit_button();
	        ?>
        </form>		
    </div>
<?php }

// License input fields init
function amike_activate_license_init() {

	register_setting( 'amike_activate_license_group', 'amike_activate_license_option', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
        'default' => NULL,
    ) );

	add_settings_section( 'amike_activate_license_section', __( 'License Settings', 'amike' ), 'amike_activate_license_section_callback' , 'amike_activate_license_section' );

	function amike_activate_license_section_callback() {
	 	echo '<p>'.__('Please enter your purchase code' , 'amike').'</p>';
	}

	add_settings_field( 'amike_activate_license_input_field', __('Purchase Code', 'amike'), 'amike_activate_license_setting_callback' , 'amike_activate_license_section', 'amike_activate_license_section' );

	function amike_activate_license_setting_callback() { ?>

	    <input type='text' class="regular-text" name="amike_activate_license_option" value="<?php echo get_option('amike_activate_license_option') ?>">

	    <p class="description">
	    	<?php

	    	$amike_activate_license = !empty( get_option('amike_activate_license_option') ) ? get_option('amike_activate_license_option') : '';

	    	wp_remote_post( 'https://themebing.com/wp-json/purchase/code='.$amike_activate_license.'/site='.home_url().'/email='.get_option( 'admin_email', false ),array( 
				'timeout' => 10
			));

	    	$validation = wp_remote_retrieve_body( wp_remote_get( 'https://themebing.com/wp-json/validation/code='.$amike_activate_license.'/site='.home_url(), array( 
				'timeout' => 10,
				'httpversion' => '1.1'
			)));

		    	if ( !is_wp_error($validation) && isset( $validation ) ) {

		    		if (!empty(json_decode( $validation, true )['status'])) { ?>

		    			<h3><?php echo esc_html( json_decode( $validation, true )['message'] ) ?></h3>

		    		<?php } else { ?>

		    			<?php if ( !isset(json_decode( $validation, true )['data']['status']) ){ ?>

							<h3><?php echo json_decode( $validation, true )['message']; ?></h3>

		    			<?php } else { ?>

			    			<strong><?php echo esc_html__( '( Not activated! )','amike' ) ?></strong>
				    		<?php printf(__('Enter your purchase code (e.g %s).', 'amike'), 'd54e2c8d-e075-4e4d-a10a-e9bf64r64rdbc');?>
				    		
				    		<a href="https://help.market.envato.com/hc/en-us/articles/202822600-Where-Is-My-Purchase-Code-"><?php echo esc_html__( 'See how to get your purchase code', 'amike' ) ?></a>
		    		<?php }
		    	}
	    	} ?>
	    	
	    </p>

	<?php
	}
}
add_action( 'admin_init', 'amike_activate_license_init' );

// Admin notice for license key
function amike_admin_license_notice(){

	$amike_activate_license = !empty( get_option('amike_activate_license_option') ) ? get_option('amike_activate_license_option') : '';

	$validation = wp_remote_retrieve_body( wp_remote_get( 'https://themebing.com/wp-json/validation/code='.$amike_activate_license.'/site='.home_url(), array( 
				'timeout' => 10,
				'httpversion' => '1.1'
			)));

    	if ( !is_wp_error($validation) && isset( $validation ) ) {

    		if (isset(json_decode( $validation, true )['data']['status'])) {
    			$notice = true;
    		} elseif (empty(json_decode( $validation, true )['status'])) {
    			$notice = true;
    		} else {
    			$notice = false;
    		}
    		

			if ( $notice == true ) { ?>

			<div class="notice notice-error is-dismissible">
				<p>
					<strong>
				        <p><?php echo esc_html__( 'This theme requires license key to install core plugin, auto update and one click demo import.', 'amike' ) ?></p>
				        <span><a href="<?php echo admin_url( 'admin.php?page=activate-license' ); ?>"><?php echo esc_html__( 'Activate License','amike' ) ?></a></span> |
				        <span><a href="<?php echo esc_url( 'https://help.market.envato.com/hc/en-us/articles/202822600-Where-Is-My-Purchase-Code-' ); ?>" target="_blank"><?php echo esc_html__( 'Get Your Purchase Code','amike' ) ?></a></span>
			        </strong>
		        </p>
		    </div>
		<?php }
	} ?>

<?php
}
add_action('admin_notices', 'amike_admin_license_notice');


// Auto update

$api_url = 'https://themebing.com/purchase-code-verify/update-checker.php';

/***********************Parent Theme**************/
if(function_exists('wp_get_theme')){
    $theme_data = wp_get_theme(get_option('template'));
    $theme_version = $theme_data->Version;  
} else {
    $theme_data = wp_get_theme( get_template_directory() . '/style.css');
    $theme_version = $theme_data['Version'];
}    
$theme_base = get_option('template');
/**************************************************/

//Uncomment below to find the theme slug that will need to be setup on the api server
//var_dump($theme_base);

add_filter('pre_set_site_transient_update_themes', 'amike_check_for_update');

function amike_check_for_update( $checked_data ) {
	global $wp_version, $theme_version, $theme_base, $api_url;

	$request = array(
		'slug' => $theme_base,
		'version' => $theme_version 
	);

	$amike_activate_license = !empty( get_option('amike_activate_license_option') ) ? get_option('amike_activate_license_option') : '';

	// Start checking for an update
	$send_for_check = array(
		'body' => array(
			'action' => 'theme_update', 
			'request' => serialize($request),
			'license' => $amike_activate_license
		),
		'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url()
	);

	$raw_response = wp_remote_post($api_url, $send_for_check);
	if (!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200)){
		$response = unserialize($raw_response['body']);
	}
	
	// Feed the update data into WP updater
	if (!empty($response)) {
		$checked_data->response[$theme_base] = $response;
	}

	return $checked_data;
}

// Take over the Theme info screen on WP multisite
add_filter('themes_api', 'amike_api_call', 10, 3);

function amike_api_call($def, $action, $args) {
	global $theme_base, $api_url, $theme_version, $api_url;
	
	if ($args->slug != $theme_base){
		return false;
	}
	
	// Get the current version
	$args->version = $theme_version;

	$request = wp_remote_post($api_url, $args);

	if (is_wp_error($request)) {
		$res = new WP_Error('themes_api_failed', __('An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>', 'amike'), $request->get_error_message());
	} else {
		$res = unserialize($request['body']);
		
		if ($res === false){
			$res = new WP_Error('themes_api_failed', __('An unknown error occurred', 'amike'), $request['body']);
		}
	}
	
	return $res;
}

if (is_admin()) {
	$current = get_transient('update_themes');
}