<?php

function organic_widgets_pro_activate_license() {

	// Listen for our activate button to be clicked.
	if ( isset( $_POST['organic_widgets_pro_license_activate'] ) ) {

		// Run a quick security check.
		if ( ! check_admin_referer( 'organic_widgets_pro_nonce', 'organic_widgets_pro_nonce' ) ) {
			return; // Get out if we didn't click the Activate button.
		}

		// Retrieve the license from the database.
		$license = trim( get_option( 'organic_widgets_pro_license_key' ) );

		// Data to send in our API request.
		$api_params = array(
			'edd_action' => 'activate_license',
			'license'    => $license,
			'item_id'    => ORGANIC_WIDGETS_PRO_PRODUCT_ID,
			'item_name'  => rawurlencode( 'Builder Widgets Pro' ), // The name of our product in EDD.
			'url'        => home_url(),
		);

		// Call the custom API.
		$response = wp_remote_post(
			ORGANIC_WIDGETS_PRO_OT_STORE_URL,
			array(
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $api_params,
			)
		);

		// Make sure the response came back okay.
		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(
							__( 'Your license key expired on %s.' ),
							date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
						);
						break;

					case 'disabled':
					case 'revoked':
						$message = __( 'Your license key has been disabled.' );
						break;

					case 'missing':
						$message = __( 'Invalid license.' );
						break;

					case 'invalid':
					case 'site_inactive':
						$message = __( 'Your license is not active for this URL.' );
						break;

					case 'item_name_mismatch':
						$message = sprintf( __( 'This appears to be an invalid license key for %s.' ), 'Builder Widgets Pro' );
						break;

					case 'no_activations_left':
						$message = __( 'Your license key has reached its activation limit.' );
						break;

					default:
						$message = __( 'An error occurred, please try again.' );
						break;
				}
			}
		}

		// Check if anything passed on a message constituting a failure.
		if ( ! empty( $message ) ) {
			$base_url = admin_url( 'admin.php?page=' . ORGANIC_WIDGETS_PRO_LICENSE_PAGE );
			$redirect = add_query_arg(
				array(
					'sl_activation' => 'false',
					'message'       => urlencode( $message ),
				),
				$base_url
			);

			wp_redirect( $redirect );
			exit();
		}

		// $license_data->license will be either "valid" or "invalid"

		update_option( 'organic_widgets_pro_license_status', $license_data->license );
		wp_redirect( admin_url( 'admin.php?page=' . ORGANIC_WIDGETS_PRO_LICENSE_PAGE ) );
		exit();
	}
}
add_action( 'admin_init', 'organic_widgets_pro_activate_license' );

function organic_widgets_pro_deactivate_license() {

	// Listen for our activate button to be clicked.
	if ( isset( $_POST['organic_widgets_pro_license_deactivate'] ) ) {

		// Run a quick security check.
		if ( ! check_admin_referer( 'organic_widgets_pro_nonce', 'organic_widgets_pro_nonce' ) ) {
			return; // Get out if we didn't click the Activate button.
		}

		// Retrieve the license from the database.
		$license = trim( get_option( 'organic_widgets_pro_license_key' ) );

		// Data to send in our API request.
		$api_params = array(
			'edd_action' => 'deactivate_license',
			'license'    => $license,
			'item_name'  => urlencode( 'Builder Widgets Pro' ), // The name of our product in EDD.
			'url'        => home_url(),
		);

		// Call the custom API.
		$response = wp_remote_post(
			ORGANIC_WIDGETS_PRO_OT_STORE_URL,
			array(
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $api_params,
			)
		);

		// Make sure the response came back okay.
		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=' . ORGANIC_WIDGETS_PRO_LICENSE_PAGE );
			$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 "deactivated" or "failed"
		if ( $license_data->license == 'deactivated' ) {
			delete_option( 'organic_widgets_pro_license_status' );
		}

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

	}
}
add_action( 'admin_init', 'organic_widgets_pro_deactivate_license' );

/**
 * This is a means of catching errors from the activation method above and displaying it to the customer
 */
function organic_widgets_pro_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;

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