<?php
if (!get_option('aicc_license_status')) {
    add_option('aicc_license_status', 'valid');
}
if (!class_exists('AICC_SL_Plugin_Updater'))
{
	include ( AICC_PLUGIN_DIR . '/AICC_SL_Plugin_Updater.php');
}
function aicc_updater()
{
	$doing_cron = defined('DOING_CRON') && DOING_CRON;
	if (!current_user_can('manage_options') && !$doing_cron)
	{
		return;
	}
	$license_key = trim(get_option('aicc_license_key'));
	$edd_updater = new AICC_SL_Plugin_Updater(AICC_STORE_URL, AICC_FILE, array(
		'version' => '2.7.1', 
		'license' => $license_key, 
		'item_id' => AICC_ITEM_ID, 
		'author' => 'Content Curator', 
		'beta' => false,
	));

}
add_action('init', 'aicc_updater');


function aicc_license_menu() {
	add_submenu_page('aicc', 'Licencia', 'Licencia', 'manage_options', AICC_LICENSE_PAGE, 'aicc_license_page');

}


function aicc_license_page()
{
	$license = get_option('aicc_license_key');
	$status = get_option('aicc_license_status');

?>
	

			<div class="wrap wrapper-aicc-options ">
			
				<div class="nav-tab-wrapper">
							
					<div style="text-align:center; ">
						<img class="aicc-logo" src="<?php echo AICC_PLUGIN_URL; ?>/assets/img/logo.png" width="840px" />
					</div>
					
		
					<a href="?page=<?php echo $_GET['page']; ?>" class="nav-tab nav-tab-active">

					<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-key" width="44" height="44" viewBox="0 0 24 24" stroke-width="1.5" stroke="#757575" fill="none" stroke-linecap="round" stroke-linejoin="round">
  
						<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
						  <circle cx="8" cy="15" r="4" />
						  <line x1="10.85" y1="12.15" x2="19" y2="4" />
						  <line x1="18" y1="5" x2="20" y2="7" />
						  <line x1="15" y1="8" x2="17" y2="10" />

					</svg>
					<span><?php _e('License', 'aicc'); ?></span>
					
					</a>
			
				</div>
				
<section id="aicc-options options-general" class="aicc-options section-content active">
	
	<h2><?php _e('License', 'aicc'); ?></h2>

	<form method="post" action="options.php" class="form-table">

			<?php settings_fields('aicc_license'); ?>

			<table class="form-table">
				<tbody>
					<tr valign="top">
						<th scope="row" valign="top">
							<?php _e('Clave de licencia'); ?>
						</th>
						<td>
							<input id="aicc_license_key" name="aicc_license_key" type="password" class="regular-text" value="<?php esc_attr_e($license); ?>" />
						</td>
					</tr>
					<?php if (false !== $license && $license )
	{ ?>
						<tr valign="top">
							<th scope="row" valign="top">
								<?php _e('Estado de licencia'); ?>
							</th>
							<td>
								<?php if ($status !== false && $status == 'valid')
		{ ?>
							<span style="color:green;"><?php _e('Activa'); ?></span>
							<?php wp_nonce_field('aicc_nonce', 'aicc_nonce'); ?>
						<!--	<input type="submit" class="button-secondary" name="edd_license_deactivate" value="<?php _e('Desactivar licencia'); ?>"/>	-->
								<?php
		}
		else
		{ ?>
					<span style="color:red;display:block;margin-bottom:10px;"><?php _e('Desactivada'); ?></span>
			<?php wp_nonce_field('aicc_nonce', 'aicc_nonce'); ?>
									<input type="submit" class="button-secondary" name="aicc_license_activate" value="<?php _e('Activar licencia'); ?>"/>
								<?php
		} ?>
							</td>
						</tr>
					<?php
	} ?>
				</tbody>
			</table>
	<br />
			<?php submit_button(); ?>

		</form>
	
				</section>
	
	</div>

	<?php
}



function aicc_register_option()
{
	register_setting('aicc_license', 'aicc_license_key', 'aicc_sanitize_license');
}
add_action('admin_init', 'aicc_register_option');

function aicc_sanitize_license($new)
{
	$old = get_option('aicc_license_key');
	if ($old && $old != $new)
	{
		delete_option('aicc_license_status'); 
		
	}
	return $new;
}
function aicc_activate_license()
{
	if (isset($_POST['aicc_license_activate']))
	{
		if (!check_admin_referer('aicc_nonce', 'aicc_nonce')) return; 
		$license = trim(get_option('aicc_license_key'));
		$api_params = array(
			'edd_action' => 'activate_license',
			'license' => $license,
			'item_name' => urlencode(AICC_ITEM_NAME) , 
			'url' => home_url() ,
			'environment' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'production',
		);
		$response = wp_remote_post(AICC_STORE_URL, array(
			'timeout' => 15,
			'sslverify' => false,
			'body' => $api_params
		));
		if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response))
		{

			if (is_wp_error($response))
			{
				$message = $response->get_error_message();
			}
			else
			{
				$message = __('An error occurred, please try again.');
			}

		}
		else
		{

			$license_data = json_decode(wp_remote_retrieve_body($response));

			if (false === $license_data->success)
			{

				switch ($license_data->error)
				{

					case 'expired':

						$message = sprintf(__('Tu licencia expira en %s.') , date_i18n(get_option('date_format') , strtotime($license_data->expires, current_time('timestamp'))));
					break;

					case 'disabled':
					case 'revoked':

						$message = __('Licencia deshabilitada.');
					break;

					case 'missing':

						$message = __('Clave de licencia inválida.');
					break;

					case 'invalid':
					case 'site_inactive':

						$message = __('Tu licencia no está activa para esta URL.');
					break;

					case 'item_name_mismatch':

						$message = sprintf(__('Parece una licencia inválida para %s.') , AICC_ITEM_NAME);
					break;

					case 'no_activations_left':

						$message = __('Has alcanzado el límite máximo de activaciones.');
					break;

					default:

						$message = __('Ha ocurrido un error. Prueba de nuevo.');
					break;
				}

			}

		}
		if (!empty($message))
		{
			$base_url = admin_url('admin.php?page=' . AICC_LICENSE_PAGE);
			$redirect = add_query_arg(array(
				'sl_activation' => 'false',
				'message' => urlencode($message)
			) , $base_url);

			wp_redirect($redirect);
			exit();
		}
		update_option('aicc_license_status', $license_data->license);
		wp_redirect(admin_url('admin.php?page=' . AICC_LICENSE_PAGE));
		exit();
	}
}
add_action('admin_init', 'aicc_activate_license');
function aicc_deactivate_license()
{
	if (isset($_POST['aicc_license_deactivate']))
	{
		if (!check_admin_referer('aicc_nonce', 'aicc_nonce')) return; 
		$license = trim(get_option('aicc_license_key'));
		$api_params = array(
			'edd_action' => 'deactivate_license',
			'license' => $license,
			'item_name' => urlencode(AICC_ITEM_NAME) , 
			'url' => home_url() ,
			'environment' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'production',
		);
		$response = wp_remote_post(AICC_STORE_URL, array(
			'timeout' => 15,
			'sslverify' => false,
			'body' => $api_params
		));
		if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response))
		{

			if (is_wp_error($response))
			{
				$message = $response->get_error_message();
			}
			else
			{
				$message = __('An error occurred, please try again.');
			}

			$base_url = admin_url('admin.php?page=' . AICC_LICENSE_PAGE);
			$redirect = add_query_arg(array(
				'sl_activation' => 'false',
				'message' => urlencode($message)
			) , $base_url);

			wp_redirect($redirect);
			exit();
		}
		$license_data = json_decode(wp_remote_retrieve_body($response));
		if ($license_data->license == 'deactivated')
		{
			delete_option('aicc_license_status');
		}

		wp_redirect(admin_url('admin.php?page=' . AICC_LICENSE_PAGE));
		exit();

	}
}
add_action('admin_init', 'aicc_deactivate_license');
function aicc_check_license()
{

	global $wp_version;

	$license = trim(get_option('aicc_license_key'));

	$api_params = array(
		'edd_action' => 'check_license',
		'license' => $license,
		'item_name' => urlencode(AICC_ITEM_NAME) ,
		'url' => home_url() ,
		'environment' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : 'production',
	);
	$response = wp_remote_post(AICC_STORE_URL, array(
		'timeout' => 15,
		'sslverify' => false,
		'body' => $api_params
	));

	if (is_wp_error($response)) return false;

	$license_data = json_decode(wp_remote_retrieve_body($response));

	if ($license_data->license == 'valid')
	{
		echo 'valid';
		exit;
		
	}
	else
	{
		echo 'invalid';
		exit;
		
	}
}
function aicc_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:
				
			break;

		}
	}
}
add_action('admin_notices', 'aicc_admin_notices');