<?php 
defined('ABSPATH') or die('No direct access permitted');

/** License management 
*/
class maxLicense
{
	protected static $instance; 
	
	protected $product_id = "maxbuttons-pro"; 
	protected $license_key = null;
	protected $license_activated = null;
	protected $license_lastcheck = null;
	protected $api_url = 'https://maxbuttons.com';
	protected $update_url = 'https://maxbuttons.com/maxupdate';
	

	public function __construct() 
	{
		$this->load_license(); 
	}

	public static function getInstance()
	{
		if (is_null(self::$instance)) 
			self::$instance = new maxLicense(); 
		
		return self::$instance; 	
	}
		
	protected function load_license()
	{
		$this->license_key = get_option('maxbuttons_pro_license_key');
		$this->license_lastcheck = get_transient('maxbuttons_pro_license_lastcheck');
		$this->license_activated = (bool) get_option('maxbuttons_pro_license_activated');
	}
		
	/** Function called at plugin notice time. Will check the license, will check the validity and trigger periodical checks for expiration. */
	public function display_license() 
	{
		if (! $this->license_activated)
		{	
	 		MB()->add_notice('error', __("No valid active license found. Please activate your license for support, updates, free packs and more","maxbuttons-pro") );
	 		
		}
	}
	
	public function get_key() 
	{
		return $this->license_key;
	}

	public function is_activated() 
	{
		return $this->license_activated;
	}

	/** Check for plugin updates via the WP update system */ 
	public function update_check() {

		if ($this->license_activated ) 
		{
			new maxUpdater100($this->update_url, 
							  plugin_basename(MAXBUTTONS_PRO_ROOT_FILE)  // check this							   
							 ); 
		}
	}

	public static function ajax_activate()
	{
		$license = self::getInstance();
		$license->activate_license();
	
	}
	
	/** Check the given license against the system */ 
	public function activate_license()
	{
		$nonce = $_POST["activate_license"];
		$error = false; // error handling
		if (! wp_verify_nonce( $nonce, 'activate-license' ))
		{
			$error = true; 
			$error_body = array("status" => "error",
								"error" => __("Wrong nonce","maxbuttons-pro"), 
								"code" => 0, 
								"additional_info" => __("Nonce field was not passed or invalid.","maxbuttons-pro")
							); 
		}
		
		$product_id = $this->product_id; 
		$api_url = $this->api_url;

		$args = array(
				"edd_action" => "activate_license",
				"request" => "activation", 
				"item_name" => $this->product_id ); 
		
		//$email = (isset($_POST["email"])) ? sanitize_email($_POST["email"]) : ''; 
		
		$license_key = (isset($_POST["license_key"])) ? sanitize_text_field($_POST["license_key"]) : ''; 

		if ( $product_id == '')
		{
			$error = true; 
			$error_body = array(
							"status" => "error",
							"error" => __("Missing fields","maxbuttons-pro"), 
							 "code" => 0, 
							 "addition_info" => __("Not all required fields were filled out","maxbuttons-pro")
						);  
 		}
		//$args["email"] = $email;
		$args["license"] = $license_key;  
		$args["url"] = home_url();
		
		$free_created = get_option("MBFREE_CREATED"); 
		$free_url = get_option("MBFREE_HOMEURL"); 
		
		if ($free_created != '') 
			$args["free_created"] = $free_created;
		if ($free_url != '')
			$args["free_url"] = $free_url;
		
		$api_url = add_query_arg($args, $api_url); 
 
		header('Content-Type: application/json');
		
		if ($error) // errors before the request
		{
			echo json_encode($error_body); 
			exit();
		}

		$result = wp_remote_post( $this->api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $args ) );
		
		if ( is_wp_error( $result ) || 200 !== wp_remote_retrieve_response_code( $result ) ) 
		{
			$error = $result->get_error_message();
			$message =  ( is_wp_error( $result ) && ! empty( $error ) ) ? $error : __( 'An connection error occurred, please try again.' );
			$result = array('status' => 'error', 
							'error' => $message, 
							"additional_info" => $message, 
							); 	
			echo json_encode($result);
			
			exit();
		}			

		$data = json_decode( wp_remote_retrieve_body( $result ) );
		
		if (isset($data->license) && $data->license == 'valid') 
		{
			$result  = array("status" => 'success'); // clean output 
			update_option('maxbuttons_pro_license_key', $license_key, true);
			update_option('maxbuttons_pro_license_activated', true, true);		
			
		}
		else
		{
			$new_result = array(); // clean output;

			$new_result["status"] = "error"; 
			$new_result["error"] = (isset($data->error)) ? $data->error : ''; 
 
			switch( $data->error ) {
					case 'expired' :
						$message = sprintf(
							__( 'Your license key expired on %s.', 'maxbuttons-pro' ),
							date_i18n( get_option( 'date_format' ), strtotime( $data->expires, current_time( 'timestamp' ) ) )
						);
						break;
					case 'revoked' :
						$message = __( 'Your license key has been disabled.','maxbuttons-pro');
						break;
					case 'missing' :
						$message = __( 'Invalid license.', 'maxbuttons-pro');
						break;
					case 'invalid' :
					case 'site_inactive' :
						$message = __( 'Your license is not active for this URL.', 'maxbuttons-pro' );
						break;
					case 'item_name_mismatch' :
						$message = sprintf( __( 'This appears to be an invalid license key for %s.', 'maxbuttons-pro' ), EDD_SAMPLE_ITEM_NAME );
						break;
					case 'no_activations_left':
						$message = __( 'Your license key has reached its activation limit.','maxbuttons-pro' );
						break;
					default :
						$message = __( 'An error occurred, please try again.', 'maxbuttons-pro' );
						break;
			}
			$new_result["additional_info"] = $message ;
			$result = $new_result;
			
		
		}	
		
		echo json_encode($result); 
		
		exit();
	}
	
	/** Check if the license is valid. Don't check more than given amount of days. */ 
	public function check_license()
	{	
		
		if (! $this->license_activated) 
			return false; // not activated,  no further checks needed
			
		if ($this->license_lastcheck === false)		
			$remote_result = $this->get_remote_license(); 
		else
			return $this->license_activated; // if transient exists, return status quo


		$this->load_license(); // reinit;
 
		
		$reason = (isset($remote_result)) ? $remote_result : '';
			
		if($this->license_activated) 
		{
			return true;
		} 
		else
			return false;
 
	}
	
	public function update_license_checked_time($seconds = false)
	{
		 if (! $seconds)
		 {
		 	$seconds = WEEK_IN_SECONDS; 
		 }
		 set_transient('maxbuttons_pro_license_lastcheck',true, $seconds );
	}
	
	public function get_remote_license()
	{	
		$args = array(
				"edd_action" => "check_license",
				"license" => $this->license_key,
				"item_name" => $this->product_id, 
				"url" => home_url(),
		);
 
		$request = wp_remote_post($this->api_url,  array( 'body' => $args, 'timeout' => 15, 'sslverify' => false ) ); 

		if(is_wp_error($request)) 
		{
			// failed - defer check three hours - prevent check license flood
			$this->update_license_checked_time( (3*HOUR_IN_SECONDS) );
			error_log("MBPRO - License server failed to respond");
			return "Request failed"; 
		}
		
		$data = json_decode( wp_remote_retrieve_body( $request ) ); 
 
		if (isset($data->license) && $data->license == 'valid')
		{
			$this->update_license_checked_time();
			return true;
		}
		else
		{
			update_option('maxbuttons_pro_license_activated', false, true); 
			$this->update_license_checked_time();
			return false;
		}
	}

} // Class
