<?php

$this->sections['License'] = array(
	'title' => __( 'Product License', 'intense' ),
	'desc' => __( '<p class="description">This allows you to turn on automatic updates with the inclusion of your purchase information.</p>', 'intense' ),
	'icon' => 'el-icon-retweet',
	'icon_class' => 'icon-large',
	'fields' => array(
		array(
			'id'=>'intense_auto_update',
			'type' => 'switch',
			'title' => __( "Automatic Updates", "intense" ),
			'desc' => __( "This will turn on or off the automatic updates for the Intense plugin.", "intense" ),
			'default' => 0,
		),
		array(
			'id'=>'intense_envato_username',
			'type' => 'text',
			'title' => __( "Envato Username", "intense" ),
			'desc' => __( "This is your Envato username.", "intense" ),
			'default' => '',
		),		
		array(
			'id'=>'intense_api_key',
			'type' => 'text',
			'title' => __( "Envato API Key", "intense" ),
			'desc' => __( "You can find API key by visiting your Envato Account page, then clicking the My Settings tab. At the bottom of the page you'll find your account's API key.", "intense" ),
			'default' => '',
		),
		array(
			'id'=>'intense_purchase_code',
			'type' => 'text',
			'title' => __( "Purchase Code", "intense" ),
			'desc' => __( "Please enter your CodeCanyon Intense WordPress Plugin purchase code, you can find your purchase code by downloading the \"License certificate & purchase code\" for the product from your downloads page.", "intense" ),
			'default' => '',
		),
		array(
			'id'=>'intense_license_email',
			'type' => 'text',
			'title' => __( "Email", "intense" ),
			'desc' => __( "Please include an email address to associate with your activation.", "intense" ),
			'default' => '',
		),
		array(
			'id'=>'intense_license_first_name',
			'type' => 'text',
			'title' => __( "First Name", "intense" ),
			'desc' => __( "Please include a first name to associate with your activation.", "intense" ),
			'default' => '',
		),
		array(
			'id'=>'intense_license_last_name',
			'type' => 'text',
			'title' => __( "Last Name", "intense" ),
			'desc' => __( "Please include a last name to associate with your activation.", "intense" ),
			'default' => '',
		),		
		array(
            'id'        => 'opt-custom-callback',
            'type'      => 'callback',
            'title'     => __('Activation', 'intense'),
            'subtitle'  => '',
            'callback'  => 'intense_activation_code_field'
        ),
	)
);

/**
  Custom function for the callback referenced above
 */
if (!function_exists('intense_activation_code_field')):
    function intense_activation_code_field($field, $value) {
    	global $intense_visions_options;
    	global $intense_visions_multisite_options;

		if ( is_multisite() ) {
			$options = $intense_visions_multisite_options;
		} else {
			$options = $intense_visions_options;
		}

    	$all_required = true;
    	$ivwp = new IVersionWP_Client( INTENSE_ACTIVATION_SERVER, INTENSE_PRODUCT_KEY, 'intense/intense.php', INTENSE_PLUGIN_VERSION );

        echo '<fieldset id="intense_activation_field" class="redux-field-container redux-field redux-field-init redux-container-text ">';

        $required_fields = array(
        	'intense_envato_username',
        	'intense_license_email',
        	'intense_api_key',
        	'intense_purchase_code'
    	);

        foreach ($required_fields as $key => $value) {
    		$all_required = !empty( $options[ $value ] ) && $all_required;
        }

        $ajax_nonce = wp_create_nonce( "intense-plugin-noonce" ); 
        echo '<input type="hidden" id="nonce" value="' . $ajax_nonce . '" />';

        if ( $all_required && !$ivwp->is_activated() ) {
        	echo '<button id="activation" class="button">' . __('Activate', 'intense') .'</button><div class="subscribe-field description field-desc"><input type="checkbox" id="subscribe" checked="checked">' . __( "Receive email notifications about product updates.", "intense" ) . '</div><div class="status-update description field-desc"></div>';
        } else if ( $all_required && $ivwp->is_activated() ) {
        	echo '<button id="activation" class="button activated">' . __('Deactivate', 'intense') .'</button><div style="display: none;" class="subscribe-field description field-desc"><input type="checkbox" id="subscribe" checked="checked">' . __( "Receive email notifications about product updates.", "intense" ) . '</div><div class="status-update description field-desc"></div>';
    	} else {
        	echo '<div class="description field-desc">';
        	_e('A username, api key, purchase code, email, first name, and last name are required for activation. Start by entering these values and saving your changes. After the values have been saved, refresh the page and an activation button will appear here.', 'intense');
        	echo '</div>';
    	}

    	?>
    	<style>
        	#intense_activation_field .dashicons-before {
				display: inline-block;
        	}
        	#intense_activation_field .dashicons-before:before {
        		font-size: 15px;
				width: 15px;
				height: 15px;
				margin-top: 5px;
				-webkit-animation: 1.5s linear 0s normal none infinite spin;
				animation: 1.5s linear 0s normal none infinite spin;
        	}

        	@-moz-keyframes spin {
			    from { -moz-transform: rotate(0deg); }
			    to { -moz-transform: rotate(360deg); }
			}
			@-webkit-keyframes spin {
			    from { -webkit-transform: rotate(0deg); }
			    to { -webkit-transform: rotate(360deg); }
			}
			@keyframes spin {
			    from {transform:rotate(0deg);}
			    to {transform:rotate(360deg);}
			}
        	</style>
        	<script>
        		(function($){        			
        			$(document).on('click', '#activation', function(e) {        				
        				e.preventDefault();

        				var $el = $(this);
        				var isActivated = $(this).hasClass('activated');
        				var activateText = '<?php _e('Activate', 'intense'); ?>';
        				var deActivateText = '<?php _e('Deactivate', 'intense'); ?>';
        				var subscribe = $('#subscribe').prop('checked');

        				$el.prop('disabled', 'disabled');
        				$('.status-update').html('');
        				$el.append(' <div class="dashicons-before dashicons-update"><br></div>')
        				$('.subscribe-field').hide();

        				$.ajax({
							type: 'POST',
							url: ajaxurl + '?action=intense_licence_activation',
							cache: false,
							dataType: 'json',
							data: {
								security: $('#nonce').val(),
								mode: ( !isActivated ? 'activate' : 'deactivate' ),
								subscribe: subscribe
							},							
							success: function(data) {
								$el.prop('disabled', '');
								$el.children('.dashicons-before').remove();

								$('.status-update').html(data.description);
								
								if (data.status === 'Success') {
									isActivated = !isActivated;

									if (isActivated) {
										$el.addClass('activated');
										$el.html(deActivateText);
										$('.subscribe-field').hide();
									} else {
										$el.removeClass('activated');
										$el.html(activateText);
										$('.subscribe-field').show();
									}
								} else {
									$('.subscribe-field').show();
								}
							}
						});
        			});        			
        		})(jQuery);
        	</script>
        	<?php   

        echo '</fieldset>';
    }
endif;

if (!function_exists('intense_licence_activation')):
	add_action( 'wp_ajax_intense_licence_activation', 'intense_licence_activation' );
	function intense_licence_activation() {
		global $intense_visions_options;
		global $intense_visions_multisite_options;

		if ( is_multisite() ) {
			$options = $intense_visions_multisite_options;
		} else {
			$options = $intense_visions_options;
		}

		check_ajax_referer( 'intense-plugin-noonce', 'security' );

		//check permissions
		if ( !current_user_can( 'install_plugins' ) ) {
			die( __( "You are not allowed to be here" ) );
		}

		$username = $options['intense_envato_username'];
		$email = $options['intense_license_email'];
		$first_name = $options['intense_license_first_name'];
		$last_name = $options['intense_license_last_name'];
		$api_key = $options['intense_api_key'];
		$purchase_code = $options['intense_purchase_code'];	
		$subscribe = isset( $_POST['subscribe'] ) ? $_POST['subscribe'] : false;

		$ivwp = new IVersionWP_Client( INTENSE_ACTIVATION_SERVER, INTENSE_PRODUCT_KEY, 'intense/intense.php', INTENSE_PLUGIN_VERSION );

		if ( $_POST['mode'] == 'activate' ) {		
			$result = $ivwp->activate( $username, $api_key, $purchase_code, $email, $first_name, $last_name, $subscribe );
		} else {
			$result = $ivwp->deactivate();
		}

		echo json_encode( $result );

		die();
	}
endif;
