<?php
if( ! defined( 'ABSPATH' ) ) exit;

/**
 * The WeePie Framework plugin folder/file
 *
 * @var string
 *
 * @since 3.2.9
 */
define( 'WPIE_FW_FILE_OLD', 'weepie-framework/weepie-framework.php' );

/**
 * The WeePie Framework new folder/file (since 2.0)
 *
 * @var string
 *
 * @since 3.2.9
 */
define( 'WPIE_FW_FILE_NEW', 'framework/weepie-framework.php' );

if( !class_exists( 'WeePieFramework' ) ) {
	if( file_exists( $file = dirname( __FILE__ ) . '/' . WPIE_FW_FILE_NEW ) ) {
		require_once $file;
	} else {
		throw new \Exception( __( 'WeePie Framework main file not found.', 'weepie' ) );
	}
}
if( version_compare( WeePieFramework::VERSION , '2.0', '<' ) ) {
	throw new \Exception( sprintf( __( 'A version of the WeePie Framework plugin (v%s) is still active. Please deactivate and delete this plugin and try again.' ),
			WeePieFramework::VERSION
		)
	);
}
if( file_exists( dirname( __FILE__ ) . '/../' . WPIE_FW_FILE_OLD ) ) {
	add_action( 'admin_print_footer_scripts-plugins.php', function() {
	?>
	<script>
	(function($) {
		$(document).on('wp-plugin-delete-success', function(r) {
			window.location = '<?php echo self_admin_url( 'plugins.php' ); ?>';
		});
	})(jQuery);
	</script>
	<?php
	} );

	throw new \Exception( __( 'WeePie Framework plugin still in plugins list. Please delete the WeePie Framework plugin entirely.', 'weepie' ) );
}

/**
 * Handle and display the Exception errors from above
 *
 * @uses wp_die() when not on the plugins.php page
 *
 * @param string $msg
 *
 * @since 3.2.9
 */
function wpiefw_check_display_errors( $msg )
{
	if( wp_doing_ajax() ) {
		return;
	}

	// Need to wrap all logic in the init hook
	// to have all WordPress functions available
	add_action( 'init', function() use( $msg ) {
		global $pagenow;

		$msg = str_replace( [ 'deactivate', 'delete' ], [ '<strong>deactivate</strong>', '<strong>delete</strong>' ], $msg );

		if( 'plugins.php' !== $pagenow ) {
			wp_die( $msg . ' Go to <a href="' . self_admin_url( 'plugins.php' ) . '">Plugins page</a>.', 'WeePie Framework > Error' );
		} else {
			add_action( 'all_admin_notices', function() use ( $msg ) {
				$fileOld = urlencode( WPIE_FW_FILE_OLD );

				$url = ( is_multisite() )
					? network_admin_url( 'plugins.php' )
					: admin_url( 'plugins.php' );

				$urlDeactivate = add_query_arg( [
					'action' => 'deactivate',
					'plugin' => $fileOld
					], $url );

				$urlDelete = add_query_arg( [
					'action' => 'delete-selected',
					'checked[]' => $fileOld
					], $url );

				$msg = str_replace( 'deactivate', sprintf( '<a href="%s" class="deactivate">deactivate</a>', wp_nonce_url( $urlDeactivate, 'deactivate-plugin_' . WPIE_FW_FILE_OLD ) ), $msg );
				$msg = str_replace( 'delete', sprintf( '<a href="%s" class="delete">delete</a>', wp_nonce_url( $urlDelete, 'bulk-plugins' ) ), $msg );

				printf( '<div class="%1$s"><p>%2$s</p></div>', 'notice notice-error', $msg );
			} );
		}
	} );
}