<?php
if ( ! class_exists( 'SftcyWordformUpgrade' ) ) {
	class SftcyWordformUpgrade {
		private static $initiated       = false;
		public static $licensekey       = null; 
		//private static $licenseemail  = null; 	
		public  static $licenseurl      = null;
		public  static $plugin_slug     = null;  // plugin-dir/plugin-name.php
		public  static $slug            = null;  // plugin-name
		public  static $name            = null; 
		public  static $textdomain      = null;
		public  static $version         = null;  
		public  static $url             = null;
		public  static $package         = null;
		public  static $tested          = 6.5;	
		public  static $remote_response = array();

		public static $success_icon = '<i class="fa-regular fa-circle-check"></i>';
		public static $error_icon   = '<i class="fa-regular fa-circle-xmark"></i>';
		public static $info_icon    = '<i class="fa-solid fa-circle-info"></i>';
		public static $output       = array();		
			
		public function __construct() {
			if ( ! self::$initiated ) {
				self::initiate_hooks();
			}		
		}
		/**
		 * Init Hooks
		 *
		 * @return void
		 */
		public static function initiate_hooks() {		
			add_action( 'admin_enqueue_scripts', array( __CLASS__, 'sc_wordform_admin_required_license_scripts' ) );
			// Ajax: License : License Key Data Save
			add_action( 'wp_ajax_sc_wordform_settings_wordform_license_key_save', array( __CLASS__, 'sc_wordform_settings_wordform_license_key_save' ) );	
			// Ajax: License : License Key Data Refresh
			add_action( 'wp_ajax_sc_wordform_settings_wordform_license_key_data_refresh', array( __CLASS__, 'sc_wordform_settings_wordform_license_key_data_refresh' ) );
			add_action( 'wp_ajax_sc_wordform_upgrade_to_pro', array( __CLASS__, 'sc_wordform_upgrade_to_pro' ) );


			self::$initiated = true;			
		}

		/**
		 * Enqueue License scripts
		 * Loaded only specifically for license page
		 */
		public static function sc_wordform_admin_required_license_scripts() {		
			global $pagenow;
			if ( $pagenow == 'admin.php' && isset( $_GET['page'] ) && $_GET['page'] == 'wordform-license' ) {								
				$nonce = wp_create_nonce( 'scwordform_wpnonce' );
				wp_enqueue_script( 'wordform-admin-license-page-script', plugins_url( '../admin/js/wordform-license-script.js', __FILE__ ), array( 'jquery' ), SFTCY_WORDFORM_VERSION, true );	
				
				wp_enqueue_style('wordform-admin-license-page-style', plugins_url( '../admin/css/wordform-license-styles.css', __FILE__ ) , array(), SFTCY_WORDFORM_VERSION, 'all' );					
				
				$localize_data = array(
					'adminajax_url'                 => admin_url( 'admin-ajax.php' ),									
					'pagenow'						=> $pagenow,
					'nonce'                         => $nonce,
					'support_page_url'              => admin_url( 'admin.php?page=wordform-support' ),
					'softcoy_support_url'           => 'https://softcoy.com/support',
				);

				// Localize script
				wp_localize_script( 'wordform-admin-license-page-script', 'wordform_admin_view_license_page_script_obj', $localize_data );
			}
			
		}


		
	/**
		* Local plugin information
		*
		* @return void
		*/
		public static function local_plugin_data() {		
			// if ( is_admin() && ! function_exists( 'get_plugin_data' ) ) {		
				// require_once ABSPATH . 'wp-admin/includes/plugin.php';
			// }			

			// if ( ! isset( self::$plugin_slug ) || ! isset( self::$slug ) || ! isset( self::$version ) || ! isset( self::$name ) ) {		
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
				// $plugin_data = get_plugin_data( dirname( __FILE__ ) . '/wordform-pro.php' );			
				$plugin_data = get_plugin_data( SFTCY_WORDFORM_PLUGIN_FILE );
				self::$name = $plugin_data['Name'];
				self::$textdomain = $plugin_data['TextDomain'];
				self::$version = $plugin_data['Version'];		
				self::$url = $plugin_data['PluginURI'];
				// self::$plugin_slug = plugin_basename( dirname( __FILE__ ) . '/wordform-pro.php' );
				self::$plugin_slug = plugin_basename( SFTCY_WORDFORM_PLUGIN_FILE );
				self::$slug = basename( self::$plugin_slug, '.php' );
				// Get User License info
				self::$licensekey = ! empty( self::$licensekey )? self::$licensekey : get_option( 'softcoy_wordform_pro_license_key', '' );
				self::$licenseurl = get_home_url();
				
			// }		
		}
		
		/**
		 * Fetch Remote Plugin new version information if available
		 *
		 * @return void
		 */
		public static function get_remote_release_versioninfo() {		
			self::local_plugin_data();
			$params = array( 
							'licensekey'    => self::$licensekey, 						 
							'licenseurl' => self::$licenseurl,
							//'licenseemail'  => self::$licenseemail,
							'pluginslug'    => self::$slug );
			// $api_url = self::$upgrade_api.'?'. http_build_query( $params ); 		
			$api_url = SFTCY_PRODUCT_UPGRADE_API .'?'. http_build_query( $params ); 		
			
			// wp_die( $api_url );		
			if ( ! isset( self::$remote_response ) || ! array_filter( self::$remote_response ) ) {			
				$remote_data = wp_remote_get( $api_url );
				if ( is_array( $remote_data ) && ! is_wp_error( $remote_data ) ) {								
						self::$remote_response = json_decode( $remote_data['body'], true );						
				}
				else {
					// var_dump( $remote_data->get_error_message() );
				}
			}		
		}

		/**
		 * Generate update plugin information when new License key added / saved
		 */
		public static function generate_plugin_update_info_object() {
			// Initialization local and remote release plugin data
			self::local_plugin_data();
			self::get_remote_release_versioninfo();	
			$obj = new stdClass();
			$obj->id = self::$plugin_slug; // wordform-pro/wordform-pro.php
			$obj->plugin = self::$plugin_slug; // wordform-pro/wordform-pro.php
			$obj->slug = self::$slug;
			$obj->name = self::$name;
			$obj->new_version = self::$remote_response['version'];
			$obj->tested = self::$tested;
			$obj->url = self::$url;
			$obj->package = self::$remote_response['download_url'];
			return $obj;
		}


		/**
		 * 'pre_set_site_transient_update_plugins' hook callback method
		 * Add plugin update information after checking with remote server
		 */
		public static function wordform_set_site_transient( $transient ) {		
			// Query premium / private server for updates
			self::local_plugin_data();
			self::get_remote_release_versioninfo();			
			// $update = myplugin_check_for_updates( 'my-plugin' );
			$obj = new stdClass();
			$obj->id = self::$plugin_slug; // wordform-pro/wordform-pro.php
			$obj->plugin = self::$plugin_slug; // wordform-pro/wordform-pro.php
			$obj->slug = self::$slug;
			$obj->name = self::$name;
			$obj->new_version = self::$remote_response['version'];
			$obj->tested      = self::$tested;
			$obj->url = self::$url;
			$obj->package = self::$remote_response['download_url'];

			// Compare running and new released versions
			if ( version_compare( self::$version, self::$remote_response['version'], '<' ) ) {
				// Update is available		
				// $transient->response['my-plugin/my-plugin.php'] = $obj;	
				$transient->response[$obj->plugin] = $obj;		
			} else {
				// No update is available
				// $transient->no_update['my-plugin/my-plugin.php'] = $obj;
				$transient->no_update[$obj->plugin] = $obj;
			}
		
			return $transient;
		}	

		/**
		 * Plugins info display
		 *
		 * @param boolean $false
		 * @param string $action
		 * @param object $response
		 * @return object - $response
		 */
		// public static function wordform_set_plugin_info( $false, $action, $response ) {		  			
			public static function wordform_set_plugin_info( $result, $action, $args ) {		  			
			// do nothing if you're not getting plugin information right now
			if( 'plugin_information' !== $action ) {
				return $result;
			}

			// do nothing if it is not our plugin
			if( 'wordform-pro' !== $args->slug ) {
				return $result;
			}

			// Initialization local and remote release plugin data
			self::local_plugin_data();
			self::get_remote_release_versioninfo();							
			$result = new stdClass();	
			// Parse Markdown texts
			$markdown = new SFTCY_Wordform_Parsedown();
			$descriptions = $markdown->parse( self::$remote_response['sections']['description'] );
			$changelogs = $markdown->parse( self::$remote_response['sections']['changelog'] );
			self::$remote_response['sections'] = array( 'description' => $descriptions,
														'changelog'   =>  $changelogs);
			
			$result->last_updated = self::$remote_response['last_updated'];
			$result->slug = self::$slug;
			$result->name  = self::$name;
			$result->version = self::$remote_response['version'];
			$result->author = self::$remote_response['author'];
			$result->homepage = self::$remote_response['homepage'];
			$result->download_link = self::$remote_response['download_url'];
			$result->tested = self::$remote_response['tested'];
			$result->requires = self::$remote_response['requires'];
			$result->upgrade_notice = self::$remote_response['upgrade_notice'];
			$result->sections = self::$remote_response['sections'];				  
			$result->banners = self::$remote_response['banners'];
				
			return $result;
		}
		
		public static function wordform_post_install( $response, $hook_extra, $result ) {		
		}



		/**
		 * Ajax - Request
		 * Save License Key
		 * Store as option - 'wordform_pro_license_data' - remote license server's API return license information data
		 * Store as option - License key - 'softcoy_wordform_pro_license_key'
		 * return json
		 */
		public static function sc_wordform_settings_wordform_license_key_save() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output     = array();
			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( $_POST['params']['formData'] ) : '';
			wp_parse_str( $sanitized_params, $params );

			// License Key
			// $current_license_key = get_option( 'softcoy_wordform_pro_license_key', '' );
			if ( isset( $params['wordform-pro-license-key'] ) && ! empty( $params['wordform-pro-license-key'] ) ) {
				$wordform_pro_license_key = strtolower( trim( sanitize_text_field( $params['wordform-pro-license-key'] ) ) );
			} else {
				$wordform_pro_license_key = '';
			}

			if ( empty( $wordform_pro_license_key ) ) {
				self::$output['status']  = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' Please enter new License Key.';
			}
			else if ( ! empty( $wordform_pro_license_key ) ) {
				// First Query to license server to check entered license key is valid - exist in license server then allow to save / update at user end
				// Fetch & Check License information from License server
				$params['body'] = [ 'licensekey' => $wordform_pro_license_key, 
									'pluginslug' => 'wordform-pro', 
									'useremail'  => get_option('admin_email'), 
									'licenseurl' => get_option('home'),
									'allow_released_reactivation' => 1 ];
				self::fetch_n_store_valid_licensse_info( $wordform_pro_license_key, $params );					
			}

			echo wp_json_encode( self::$output );
			wp_die();
		}

		/**
		 * Ajax Request
		 * Refresh License information data
		 * @return json 
		 */
		public static function sc_wordform_settings_wordform_license_key_data_refresh() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			self::$output     = array();
			$wordform_pro_license_key = sanitize_text_field( get_option( 'softcoy_wordform_pro_license_key', '' ) );
			// First Query to license server to check entered license key is valid - exist in license server then allow to save / update at user end
			// Fetch & Check License information from License server
			$params['body'] = [ 'licensekey' => $wordform_pro_license_key, 
								'pluginslug' => 'wordform-pro', 
								'useremail'  => get_option('admin_email'), 
								'licenseurl' => get_option('home') 
								];
			self::fetch_n_store_valid_licensse_info( $wordform_pro_license_key, $params );					
			echo wp_json_encode( self::$output );
			wp_die();
		}

		/**
		 * Fetch and store valid license information data into users end
		 * @param string $wordform_pro_license_key
		 * @param array $params
		 */
		public static function fetch_n_store_valid_licensse_info( $wordform_pro_license_key = null, $params = [] ) {
			$remote_server_license_data = self::wordform_store_fetched_license_data( $params ); 			
			if ( isset( $remote_server_license_data['status'] ) && $remote_server_license_data['status'] === 'success' ) {	
				// Set or Update Remote License server info into user end
				self::$output['storedLicenseRemoteData'] = update_option( 'wordform_pro_license_data', $remote_server_license_data );				
				if ( update_option( 'softcoy_wordform_pro_license_key', $wordform_pro_license_key ) ) {
					self::$output['status']  = 'success';
					self::$output['successMsg'] = self::$success_icon .  ' License Key saved successfully.';	
				}
				else {
					self::$output['status']  = 'warning';
					self::$output['warningMsg'] = self::$info_icon .  ' Nothing changes.';	
				}
			}
			else {
				self::$output['status']  = 'fail';
				$remote_fail_message = ! empty( $remote_server_license_data['failMsg'] ) ? wp_kses_post( $remote_server_license_data['failMsg'] ) : '';
				$default_fail_message = self::$error_icon . ' License key not valid or something went wrong while validating the license. If it continues then please contact <a href="https://www.softcoy.com/support" target="_blank">support</a>';
				self::$output['failMsg'] = ! empty( $remote_fail_message ) ? $remote_fail_message : $default_fail_message;
			}
		}

		/**
		 * Fetch License Key Information data from License Server		 
		 * @param Array $params - POST API call parameters
		 * @return Array - result
		 */
		public static function wordform_store_fetched_license_data( $params = [] ) {
			$response_array_data = [];
			// $response = wp_remote_post( self::$license_registration_endpoint, $params );
			$response = wp_remote_post( SFTCY_PRODUCT_REGISTRATION_API, $params );
			if ( is_wp_error( $response ) ) {
				$error_message = $response->get_error_message();				
				$response_array_data['status'] = 'fail';
				$response_array_data['error'] = $error_message;
			} else {
				$response_body = wp_remote_retrieve_body( $response );
				$response_array_data = json_decode( $response_body, true );												
			}
			return $response_array_data;
		}

		public static function sc_wordform_upgrade_to_pro() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			self::$output = array();
			$sanitized_params = isset( $_POST['params']['formData'] ) ? sanitize_text_field( $_POST['params']['formData'] ) : '';
			wp_parse_str( $sanitized_params, $params );

			$license_key = '';
			if ( isset( $params['wordform-pro-license-key'] ) && ! empty( $params['wordform-pro-license-key'] ) ) {
				$license_key = strtolower( trim( sanitize_text_field( $params['wordform-pro-license-key'] ) ) );
			}

			if ( empty( $license_key ) ) {
				$license_key = strtolower( trim( sanitize_text_field( (string) get_option( 'softcoy_wordform_pro_license_key', '' ) ) ) );
			}

			if ( empty( $license_key ) ) {
				self::$output['status'] = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' Enter a valid WordForm Pro license key before upgrading.';
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$params = array(
				'body' => array(
					'licensekey' => $license_key,
					'pluginslug' => 'wordform-pro',
					'useremail'  => get_option( 'admin_email' ),
					'licenseurl' => get_option( 'home' ),
					'allow_released_reactivation' => 1,
				),
			);

			self::fetch_n_store_valid_licensse_info( $license_key, $params );

			if ( ! isset( self::$output['status'] ) || 'success' !== self::$output['status'] && 'warning' !== self::$output['status'] ) {
				echo wp_json_encode( self::$output );
				wp_die();
			}

			$upgrade_result = self::install_wordform_pro_package( $license_key );

			if ( is_wp_error( $upgrade_result ) ) {
				self::$output['status'] = 'fail';
				self::$output['failMsg'] = self::$error_icon . ' ' . $upgrade_result->get_error_message();
			} else {
				self::$output['status'] = 'success';
				self::$output['successMsg'] = self::$success_icon . ' WordForm Pro installed and activated successfully.';
				self::$output['redirectUrl'] = admin_url( 'admin.php?page=wordform-license' );
			}

			echo wp_json_encode( self::$output );
			wp_die();
		}

		private static function install_wordform_pro_package( $license_key ) {
			if ( ! function_exists( 'plugins_api' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
			}
			if ( ! function_exists( 'deactivate_plugins' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
			}
			require_once ABSPATH . 'wp-admin/includes/file.php';
			require_once ABSPATH . 'wp-admin/includes/misc.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

			$pro_plugin_file = 'wordform-pro/wordform-pro.php';
			$download_url = add_query_arg(
				array(
					'licensekey' => $license_key,
					'pluginslug' => 'wordform-pro',
					'licenseurl' => get_option( 'home' ),
					'response' => 'stream',
				),
				SFTCY_PRODUCT_DOWNLOAD_API
			);

			WP_Filesystem();

			if ( ! file_exists( WP_PLUGIN_DIR . '/wordform-pro/wordform-pro.php' ) ) {
				$skin = new Automatic_Upgrader_Skin();
				$upgrader = new Plugin_Upgrader( $skin );
				$installed = $upgrader->install( $download_url );
				if ( is_wp_error( $installed ) ) {
					return $installed;
				}
				if ( ! $installed ) {
					return new WP_Error( 'wordform_pro_install_failed', 'WordForm Pro package could not be installed.' );
				}
			}

			if ( is_plugin_active( 'wordform/wordform.php' ) ) {
				deactivate_plugins( 'wordform/wordform.php', true );
			}

			if ( function_exists( 'delete_plugins' ) && file_exists( WP_PLUGIN_DIR . '/wordform/wordform.php' ) ) {
				delete_plugins( array( 'wordform/wordform.php' ) );
			}

			$active_plugins = (array) get_option( 'active_plugins', array() );
			$active_plugins = array_values(
				array_filter(
					$active_plugins,
					function( $plugin ) {
						return 'wordform/wordform.php' !== $plugin;
					}
				)
			);

			if ( ! in_array( $pro_plugin_file, $active_plugins, true ) ) {
				$active_plugins[] = $pro_plugin_file;
			}

			update_option( 'active_plugins', $active_plugins );
			update_option( 'softcoy_wordform_pro_needs_activation', 1 );
			wp_clean_plugins_cache( true );

			return true;
		}

			
	}// End class
}
