<?php
	
	/**********************************************************************
    	WPRichSnippets plugin settings
    /**********************************************************************/
	
	if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
	
	if( !class_exists( 'WPRS_SL_Plugin_Updater' ) ) {
		// load our custom updater
		include_once( 'includes/misc/WPRS_SL_Plugin_Updater.php' );
	}
	
	if( !class_exists( 'WPRS_Tracking' ) ) {
		// load our custom updater
		include_once( 'includes/misc/wprs-tracking.php' );
	}
	
    add_action('init','wprs_admin_page_init');
	/*
		load admin page init
		*/	
    function wprs_admin_page_init(){      
        
			add_action( 'admin_menu',									'wprs_add_plugin_admin_page'	); 
			add_action( 'admin_menu',									'wprs_documentation_menu'		); 
			add_action( 'admin_menu',									'wprs_support_menu'				);
			add_action( 'admin_print_styles-post-new.php',				'wprs_enqueue'					);
			add_action( 'admin_print_styles-post.php',					'wprs_enqueue'					);
			add_action(	'admin_footer',									'wprs_raty_scripts'				);
			add_action( 'admin_menu',									'wprs_add_box'					);
			add_action( 'save_post',									'wprs_save_data'				);
			
			// display only for users with manage_options capability
			if ( ! current_user_can( 'manage_options' ) ) return;
			$license_status = trim( get_option( 'wprs_license_status' ) );
			$website_url = get_site_url();
			if ( $license_status == '' && 'https://wprichsnippets.com' == $website_url ) {
            add_action( 'admin_notices', create_function(''," echo \"<div id='message' class='update-nag wprs_message'>".__('Please Validate the')." <a href='".admin_url().'admin.php?page=wprs-license'."'>".__(WPRICHSNIPPETS_PLUGINNAME)."</a> plugin to get access to updates and support!</div>\";") );
			}

    }


	/*
		Add plugin admin page
		*/
    function wprs_add_plugin_admin_page(){		
		
		if ( is_admin() && current_user_can('manage_options') ) {
			
			add_menu_page(	__('Rich Snippets', 'wprs'),
							__('Rich Snippets', 'wprs'),
							'administrator',
							'wprs',
							'wprs_options_page',
							plugin_dir_url(  WPRICHSNIPPETS_IMG_URL.'dash-icon.png' , __FILE__ ).'dash-icon.png'
						);
			
			add_submenu_page('wprs', 
							__('Plugin Settings', 'wprs'), 
							__('Settings', 'wprs'),
							'manage_options', 
							'wprs', 
							'wprs_options_page');
			
			add_submenu_page('wprs',
							__('License', 'wprs'),
							__('License', 'wprs'),
							'manage_options',
							'wprs-license',
							'wprs_license_page'
						);
						
			add_submenu_page('wprs',
							__('All Entries', 'wprs'), 
							__('All Entries', 'wprs'), 
							'manage_options',
							'wprs-list',
							'wprs_render_list_page'
						);
						
			add_submenu_page('wprs',
							__('Blog News', 'wprs'), 
							__('Blog News', 'wprs'),
							'manage_options',
							'wprs-news',
							'wprs_display_news_page'
						);
			
			add_submenu_page('wprs', 
							__('import / export', 'wprs'), 
							__('Import / Export', 'wprs'),
							'manage_options', 
							'wprs-import-export', 
							'wprs_import_export_page'
						);
			
		}
    }

	

	function wprs_support_menu() {
    	global $submenu;
			$submenu['wprs'][504] = array(
													'Support',
													'administrator' ,
													'https://wprichsnippets.com/support/'
											);
	}

	function wprs_documentation_menu() {
    	global $submenu;
			$submenu['wprs'][604] = array(
													'Documentation',
													'administrator' ,
													'https://wprichsnippets.com/docs/'
											);
	}
	
	//add_action( 'admin_head', 'wprs_settings_page_add_admin_head');
	//add_action( 'admin_footer', 'wprs_settings_page_add_admin_footer');
	add_action( 'admin_footer', 'wprs_add_target_blank_to_support_menu_item');
	
	function wprs_settings_page_add_admin_head() {
        ?>
        <style>
            .wprs_message {
                position: relative;
				padding-right: 40px;
            }
            .wprs_message .dashicons-no {
                cursor: pointer;
                margin-top: -.5em;
                position: absolute;
                right: 10px;
                top: 50%;
            }
        </style>
        <?php
    
	}
	
	function wprs_settings_page_add_admin_footer() { ?>
    	<script>
           	(function( $ ) {
               	var message = $( '.wprs_message' );
               	message.append( '<span class="dashicons dashicons-no"></span>' );
               	message.find( '.dashicons-no' ).on( 'click', function() {
                   	message.slideUp();
               	} );
           	})( jQuery );
       	</script>
		<?php

	}

	function wprs_add_target_blank_to_support_menu_item() { ?>
    		<script type="text/javascript"> jQuery(document).ready(function($) {
				$('.wp-submenu-wrap li a[href*="wprichsnippets.com/support"]').attr('target', '_blank');
				$('.wp-submenu-wrap li a[href*="wprichsnippets.com/docs"]').attr('target', '_blank');});
			</script>
            <?php

	}


	// ------------------------------------------------------------------------
	// admin links
	// ------------------------------------------------------------------------
	function wprs_admin_links() { ?>
	
        <div class="wprs_admin_link">
            <ul>
				<li><p>
                	<a href="http://wordpress.org/extend/plugins/author-hreview/" target="_blank"><p>Rate the plugin 5<span class="icon-star"></span> on WordPress.org</p></a></p>
				</li>
                <li class="wprs_blog"><p>
                	<a href="https://wprichsnippets.com/blog/" title="WPRichSnippets Blog" target="_blank"><p>Blog about it and link to the plugin site</p></a></p>
				</li>
                
                <li class="wprs_testimonials"><p>
                		<a href="https://wprichsnippets.com/testimonials/" title="Send a Testimonial" target="_blank">
                    		Send a Testimonial</a> (& probably get featured)
					</p>
				</li>
                
                <li class="wprs_affiliate"><p>
                		<a href="https://wprichsnippets.com/affiliate/" title="Affiliate Program" target="_blank">
                    		Get your affiliate link</a> (earn 33% commission)
					</p>
				</li>
			</ul>              
 		</div>
<?php
	}



/************************************
* the code below is just a standard
* options page. Substitute with 
* your own.
*************************************/

function wprs_license_menu() {
	add_plugins_page( 'Plugin License', 'Plugin License', 'manage_options', 'wprs-license', 'wprs_license_page' );
}
//add_action('admin_menu', 'wprs_license_menu');

function wprs_license_page() {
	$license 	= get_option( 'wprs_license_key' );
	$status 	= get_option( 'wprs_license_status' );
	?>
	<div class="wrap">
		<?php echo '<h2>'.WPRICHSNIPPETS_PLUGINNAME.' '.__('License', 'wprs').' <span style="font-size:10px;">'.__('Ver', 'wprs').' '.WPRICHSNIPPETS_VER.'</span></h2>'; ?>
		<form method="post" action="options.php">
		
			<?php settings_fields('wprs_license'); ?>
			
			<table class="form-table">
				<tbody>
					<tr valign="top">	
						<th scope="row" valign="top">
							<?php _e('License Key'); ?>
						</th>
						<td>
                        	
							<input id="wprs_license_key" name="wprs_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $license ); ?>" />
                           
							<label class="description" for="wprs_license_key">
							
                            <?php if ($license) { ?> 						
                            
                            <?php if( $status !== false && $status == 'valid' ) { ?>
									
									<?php wp_nonce_field( 'wprs_nonce', 'wprs_nonce' ); ?>
									<input type="submit" class="button-secondary" name="wprs_license_deactivate" value="<?php _e('Deactivate License'); ?>"/>
                                    <span style="color:green;"><?php _e(' Your license is valid!'); ?></span>
                           
                            <?php } elseif( 'expired' === $status && ! empty( $license ) ) {
									
									 $html_btn = '<a href="https://wprichsnippets.com/pricing/" class="button-primary">' . _e('Renew Your License') . '</a>';
									 echo $html_btn;
									 ?>
                                    <span style="color:red;"><?php _e('Expired, please renew your license!'); ?></span>
                            
							<?php } else {
									wp_nonce_field( 'wprs_nonce', 'wprs_nonce' ); ?>
									<input type="submit" class="button-secondary" name="wprs_license_activate" value="<?php _e('Activate License'); ?>"/> 
                                    <br />
                                    <span style="color:red;"><?php _e('Please, activate your license key!'); ?></span>
                           
							<?php } ?>
                            
                             <?php } else { submit_button('Save License'); } ?>
                            
                            </label>
                            
                            <p class="description">Please enter your WPRichSnippoets plugin specific license key. An active license key is needed for automatic plugin updates and <a href="https://wprichsnippets.com/support/" target="_blank">support</a>.</p>
						</td>
					</tr>
				</tbody>
			</table>	
			<?php if ($license) { submit_button('Save License'); } ?>
		
		</form>
	<?php
}


add_action('admin_init', 'wprs_register_option');
/*
	Register options
	*/
function wprs_register_option() {
	// creates our settings in the options table
	register_setting('wprs_license', 'wprs_license_key', 'wprs_sanitize_license' );
}


function wprs_sanitize_license( $new ) {
	$old = get_option( 'wprs_license_key' );
	if( $old && $old != $new ) {
		delete_option( 'wprs_license_status' ); // new license has been entered, so must reactivate
	}
	return $new;
}


add_action('admin_init', 'wprs_activate_license');
/*
	Activate a license key
	*/
function wprs_activate_license() {

	// listen for our activate button to be clicked
	if( isset( $_POST['wprs_license_activate'] ) ) {

		// run a quick security check 
	 	if( ! check_admin_referer( 'wprs_nonce', 'wprs_nonce' ) ) 	
			return; // get out if we didn't click the Activate button

		// retrieve the license from the database
		$license = trim( get_option( 'wprs_license_key' ) );
			

		// data to send in our API request
		$api_params = array( 
			'edd_action'=> 'activate_license', 
			'license' 	=> $license, 
			'item_name' => urlencode( WPRICHSNIPPETS_PLUGINNAME ), // the name of our product in EDD
			'url'       => home_url()
		);
		
		// Call the custom API.
		$response = wp_remote_get( add_query_arg( $api_params, WPRICHSNIPPETS_WEBSITE_URL ), array( 'timeout' => 15, 'sslverify' => false ) );
		
		// make sure the response came back okay
		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			$error_message = $response->get_error_message();
			$message =  ( is_wp_error( $response ) && ! empty( $error_message ) ) ? $error_message : __( 'An error occurred, please try again and make sure you are using a valid and correct license key.', 'wprs' );
		} else {
			$license_data = json_decode( wp_remote_retrieve_body( $response ) );
			
			if ( false === $license_data->success ) {
				switch( $license_data->error ) {
					case 'expired' :
						$message = sprintf(
							__( 'Your license key expired on %s.', 'wprs' ),
							date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
						);
						break;
					case 'revoked' :
						$message = __( 'Your license key has been disabled.', 'wprs' );
						break;
					case 'missing' :
						$message = __( 'Invalid license.', 'wprs' );
						break;
					case 'invalid' :
					case 'site_inactive' :
						$message = __( 'Your license is not active for this URL.', 'wprs' );
						break;
					case 'item_name_mismatch' :
						$message = sprintf( __( 'This appears to be an invalid license key for %s.', 'wprs' ), WPRICHSNIPPETS_PLUGINNAME );
						break;
					case 'no_activations_left':
						$message = __( 'Your license key has reached its activation limit.', 'wprs' );
						break;
					default :
						$message = __( 'An error occurred, please try again!', 'wprs' );
						break;
				}
			}
		}
		
		// Check if anything passed on a message constituting a failure
		if ( ! empty( $message ) ) {
			$base_url = admin_url( 'admin.php?page=wprs-license' );
			$redirect = add_query_arg( array( 'sl_activation' => 'false', 'message' => urlencode( $message ) ), $base_url );
			wp_redirect( $redirect );
			exit();
		}

		// decode the license data
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
		
		// $license_data->license will be either "valid" or "invalid"

		update_option( 'wprs_license_status', $license_data->license );
		
		wp_redirect( admin_url( 'admin.php?page=wprs-license' ) );
		exit();

	}
}



add_action('admin_init', 'wprs_deactivate_license');
/* 
	Deactivate the license key.
	*/
function wprs_deactivate_license() {

	// listen for our activate button to be clicked
	if( isset( $_POST['wprs_license_deactivate'] ) ) {

		// run a quick security check 
	 	if( ! check_admin_referer( 'wprs_nonce', 'wprs_nonce' ) ) 	
			return; // get out if we didn't click the Activate button

		// retrieve the license from the database
		$license = trim( get_option( 'wprs_license_key' ) );
			

		// data to send in our API request
		$api_params = array( 
			'edd_action'=> 'deactivate_license', 
			'license' 	=> $license, 
			'item_name' => urlencode( WPRICHSNIPPETS_PLUGINNAME ), // the name of our product in EDD
			'url'       => home_url()
		);
		
		// Call the custom API.
		$response = wp_remote_get( add_query_arg( $api_params, WPRICHSNIPPETS_WEBSITE_URL ), array( 'timeout' => 15, 'sslverify' => false ) );

		// make sure the response came back okay
		if ( is_wp_error( $response ) )
			return false;

		// decode the license data
		$license_data = json_decode( wp_remote_retrieve_body( $response ) );
		
		// $license_data->license will be either "deactivated" or "failed"
		if( $license_data->license == 'deactivated' )
			delete_option( 'wprs_license_status' );

	}
}


add_action( 'admin_notices', 'wprs_license_activation_admin_notices' );
/**
 * This is a means of catching errors from the activation method above and displaying it
 *
 * @since 1.4.4
 */
function wprs_license_activation_admin_notices() {
	if ( isset( $_GET['sl_activation'] ) && ! empty( $_GET['message'] ) ) {
		switch( $_GET['sl_activation'] ) {
			case 'false':
				$message = urldecode( $_GET['message'] );
				?>
				<div class="error">
					<p><?php echo $message; ?></p>
				</div>
				<?php
				break;
			case 'true':
			default:
				// Developers can put a custom success message here for when activation is successful if they way.
				break;
		}
	}
}
