<?php
if ( ! class_exists( 'SftcyWordaiUpgrade' ) ) {
	class SftcyWordaiUpgrade {
		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_wordai_admin_required_license_scripts' ) );
			// Ajax: License : License Key Data Save
			add_action( 'wp_ajax_sc_wordai_settings_wordai_license_key_save', array( __CLASS__, 'sc_wordai_settings_wordai_license_key_save' ) );	
			// Ajax: License : License Key Data Refresh
			add_action( 'wp_ajax_sc_wordai_settings_wordai_license_key_data_refresh', array( __CLASS__, 'sc_wordai_settings_wordai_license_key_data_refresh' ) );
			add_action( 'wp_ajax_sc_wordai_upgrade_to_pro', array( __CLASS__, 'sc_wordai_upgrade_to_pro' ) );


			self::$initiated = true;			
		}

		/**
		 * Enqueue License scripts
		 * Loaded only specifically for license page
		 */
		public static function sc_wordai_admin_required_license_scripts() {		
			global $pagenow;
			if ( $pagenow == 'admin.php' && isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'wordai-license', 'wordai-get-pro' ), true ) ) {								
				$nonce = wp_create_nonce( 'scwordai_wpnonce' );
				$script_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/wordai-license-script.js';
				$style_path     = SFTCY_WORDAI_PLUGIN_DIR . 'admin/css/wordai-license-styles.css';
				$script_version = file_exists( $script_path ) ? (string) filemtime( $script_path ) : SFTCY_WORDAI_VERSION;
				$style_version  = file_exists( $style_path ) ? (string) filemtime( $style_path ) : SFTCY_WORDAI_VERSION;

				wp_enqueue_script( 'wordai-admin-license-page-script', plugins_url( '../admin/js/wordai-license-script.js', __FILE__ ), array( 'jquery' ), $script_version, true );	
				wp_enqueue_style('wordai-admin-license-page-style', plugins_url( '../admin/css/wordai-license-styles.css', __FILE__ ) , array(), $style_version, 'all' );
				
				$localize_data = array(
					'adminajax_url'                 => admin_url( 'admin-ajax.php' ),					
					'pagenow'						=> $pagenow,
					'nonce'                         => $nonce,
					'support_page_url'              => admin_url( 'admin.php?page=sc-wordai-support' ),
					'softcoy_support_url'           => 'https://softcoy.com/support',
				);

				// Localize script
				wp_localize_script( 'wordai-admin-license-page-script', 'wordai_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__ ) . '/wordai-pro.php' );			
				$plugin_data = get_plugin_data( SFTCY_WORDAI_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__ ) . '/wordai-pro.php' );
				self::$plugin_slug = plugin_basename( SFTCY_WORDAI_PLUGIN_FILE );
				self::$slug = basename( self::$plugin_slug, '.php' );
				// Get User License info
				self::$licensekey = ! empty( self::$licensekey )? self::$licensekey : get_option( 'softcoy_wordai_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 ) ) {								
						$response = json_decode( $remote_data['body'], true );
						self::$remote_response = is_array( $response ) ? $response : array();
				}
				else {
					// var_dump( $remote_data->get_error_message() );
					self::$remote_response = array();
				}
			}		
		}

		/**
		 * 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();	
			if ( empty( self::$remote_response['version'] ) || empty( self::$remote_response['download_url'] ) ) {
				return null;
			}
			$obj = new stdClass();
			$obj->id = self::$plugin_slug; // wordai-pro/wordai-pro.php
			$obj->plugin = self::$plugin_slug; // wordai-pro/wordai-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 wordai_set_site_transient( $transient ) {		
			// Query premium / private server for updates
			self::local_plugin_data();
			self::get_remote_release_versioninfo();			
			if ( empty( self::$remote_response['version'] ) || empty( self::$remote_response['download_url'] ) ) {
				return $transient;
			}
			// $update = myplugin_check_for_updates( 'my-plugin' );
			$obj = new stdClass();
			$obj->id = self::$plugin_slug; // wordai-pro/wordai-pro.php
			$obj->plugin = self::$plugin_slug; // wordai-pro/wordai-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 wordai_set_plugin_info( $false, $action, $response ) {		  			
			public static function wordai_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( 'wordai-pro' !== $args->slug ) {
				return $result;
			}

			// Initialization local and remote release plugin data
			self::local_plugin_data();
			self::get_remote_release_versioninfo();							
			if ( empty( self::$remote_response['version'] ) || empty( self::$remote_response['sections'] ) || ! is_array( self::$remote_response['sections'] ) ) {
				return $result;
			}
			$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'] ?? self::$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'] ?? array();
				
			return $result;
		}
		
		public static function wordai_post_install( $response, $hook_extra, $result ) {		
		}



		/**
		 * Ajax - Request
		 * Save License Key
		 * Store as option - 'wordai_pro_license_data' - remote license server's API return license information data
		 * Store as option - License key - 'softcoy_wordai_pro_license_key'
		 * return json
		 */
		public static function sc_wordai_settings_wordai_license_key_save() {
			check_ajax_referer( 'scwordai_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_wordai_pro_license_key', '' );
			if ( isset( $params['wordai-pro-license-key'] ) && ! empty( $params['wordai-pro-license-key'] ) ) {
				$wordai_pro_license_key = strtolower( trim( sanitize_text_field( $params['wordai-pro-license-key'] ) ) );
			} else {
				$wordai_pro_license_key = '';
			}

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

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

		/**
		 * Ajax Request
		 * Refresh License information data
		 * Fetch latest license information data based on user Refresh request
		 * @return json 
		 */
		public static function sc_wordai_settings_wordai_license_key_data_refresh() {
			check_ajax_referer( 'scwordai_wpnonce', 'security' );
			self::$output     = array();
			$wordai_pro_license_key = sanitize_text_field( get_option( 'softcoy_wordai_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' => $wordai_pro_license_key, 
								'pluginslug' => 'wordai-pro', 
								'useremail'  => get_option('admin_email'), 
								'licenseurl' => get_option('home') 
								];											
			self::fetch_n_store_valid_license_info( $wordai_pro_license_key, $params );					
			echo wp_json_encode( self::$output );
			wp_die();
		}

		/**		 
		 * Fetch and store valid license information data into users end
		 * @param string $wordai_pro_license_key
		 * @param array $params
		 */
		public static function fetch_n_store_valid_license_info( $wordai_pro_license_key = null, $params = [] ) {
			$remote_server_license_data = self::wordai_store_fetched_license_data( $params ); 					
			// var_dump( $remote_server_license_data );			
			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( 'wordai_pro_license_data', $remote_server_license_data );				
				if ( update_option( 'softcoy_wordai_pro_license_key', $wordai_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 not active. Something may also be wrong with the license connection. 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 Remote License Server		 
		 * @param Array $params - POST API call parameters
		 * @return Array - result
		 */
		public static function wordai_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_wordai_upgrade_to_pro() {
			check_ajax_referer( 'scwordai_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['wordai-pro-license-key'] ) && ! empty( $params['wordai-pro-license-key'] ) ) {
				$license_key = strtolower( trim( sanitize_text_field( $params['wordai-pro-license-key'] ) ) );
			}

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

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

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

			self::fetch_n_store_valid_license_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_wordai_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 . ' WordAI Pro installed and activated successfully.';
				self::$output['redirectUrl'] = admin_url( 'admin.php?page=wordai-license' );
			}

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

		private static function install_wordai_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 = 'wordai-pro/wordai-pro.php';
			$download_url = add_query_arg(
				array(
					'licensekey' => $license_key,
					'pluginslug' => 'wordai-pro',
					'licenseurl' => get_option( 'home' ),
					'response' => 'stream',
				),
				SFTCY_PRODUCT_DOWNLOAD_API
			);

			WP_Filesystem();

			if ( ! file_exists( WP_PLUGIN_DIR . '/wordai-pro/wordai-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( 'wordai_pro_install_failed', 'WordAI Pro package could not be installed.' );
				}
			}

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

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

			$active_plugins = (array) get_option( 'active_plugins', array() );
			$active_plugins = array_values(
				array_filter(
					$active_plugins,
					function( $plugin ) {
						return 'wordai/wordai.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_wordai_pro_needs_activation', 1 );
			wp_clean_plugins_cache( true );

			return true;
		}

			
		/**
		 * WordAI License Key Mask Format
		 * @return - string - License Key Mask
		 */
		public static function wordai_pro_license_key_mask_format( $license_key = '' ) {
			// Default - Placeholder display
			$license_key_mask = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
			if ( ! empty( $license_key ) ) {
				$license_key_mask = str_split( $license_key, 2 );	
				array_walk( $license_key_mask, function( &$val, $index ) { $val = ( $index % 2 !== 0 )? str_repeat( '*', strlen( $val )) : $val; } );		
				$license_key_mask = implode('', $license_key_mask );		
			}
			return $license_key_mask;
		}
		
		
	}// End class
}
