<?php
/**
 * MainWP Jetpack Protect
 *
 * This file handles.
 *
 * @package MainWP/Extensions
 */

namespace MainWP\Extensions\JetpackProtect;

/**
 * Class MainWP_Jetpack_Protect
 */
class MainWP_Jetpack_Protect {


	/**
	 * Protected static variable to hold the single instance of the class.
	 *
	 * @var mixed Default null
	 */
	private static $instance = null;

	/**
	 * Method get_instance()
	 *
	 * Create a new public static instance of
	 * MainWP_Jetpack_Protect().
	 *
	 * @return void $instance New public static Instance.
	 */
	static function get_instance() {
		if ( null == self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * MainWP_Jetpack_Protect class constructor.
	 *
	 * @return void
	 */
	public function __construct() {
		add_action( 'admin_init', array( &$this, 'admin_init' ) );
		add_filter( 'mainwp_jetpack_protect_get_reports_data', array( $this, 'hook_get_reports_tokens_value' ), 10, 3 );
	}

	/**
	 * Initiates the admin page when loaded & sets initial Class Variables.
	 */
	public function admin_init() {
		do_action( 'mainwp_ajax_add_action', 'mainwp_jetpack_protect_connect_disconnect', array( &$this, 'ajax_jetpack_connect_disconnect' ) );
		do_action( 'mainwp_ajax_add_action', 'mainwp_jetpack_protect_upgrade_plugintheme', array( &$this, 'ajax_upgrade_item' ) );
		do_action( 'mainwp_ajax_add_action', 'mainwp_jetpack_protect_delete_plugintheme', array( &$this, 'ajax_delete_item' ) );
		$this->handle_settings_post();
	}

	public function handle_settings_post() {
		if ( isset( $_POST['mainwp_jetpack_protect_screen_opts_nonce'] ) ) {
			$secure = apply_filters( 'mainwp_check_security_request', false, 'mainwp_jetpack_protect_screen_opts_nonce', 'mainwp_jetpack_protect_screen_opts_nonce' );
			if ( ! $secure ) {
				wp_die( 'Invalid request.' );
				return;
			}

			$user = wp_get_current_user();

			$show_wids = array();
			if ( isset( $_POST['mainwp_show_widgets'] ) && is_array( $_POST['mainwp_show_widgets'] ) ) {
				$selected_wids = array_map( 'sanitize_text_field', wp_unslash( $_POST['mainwp_show_widgets'] ) );
				foreach ( $selected_wids as $name ) {
					$show_wids[ $name ] = 1;
				}
			}

			if ( isset( $_POST['mainwp_widgets_name'] ) && is_array( $_POST['mainwp_widgets_name'] ) ) {
				$name_wids = array_map( 'sanitize_text_field', wp_unslash( $_POST['mainwp_widgets_name'] ) );
				foreach ( $name_wids as $name ) {
					if ( ! isset( $show_wids[ $name ] ) ) {
						$show_wids[ $name ] = 0;
					}
				}
			}

			if ( $user ) {
				update_user_option( $user->ID, 'mainwp_jetpack_protect_show_widgets', $show_wids, true );
				update_user_option( $user->ID, 'mainwp_number_jetpack_protect_overview_columns', ( isset( $_POST['number_overview_columns'] ) ? intval( $_POST['number_overview_columns'] ) : 2 ), true );
			}

			if ( isset( $_POST['reset_jetpack_protect_overview_settings'] ) && ! empty( $_POST['reset_jetpack_protect_overview_settings'] ) ) {
				update_user_option( $user->ID, 'mainwp_widgets_sorted_mainwp_page_managesitesjetpackprotect', false, true );
			}
		}
	}

	public static function is_managesites_subpage( $tabs = array() ) {
		if ( isset( $_GET['page'] ) && ( 'ManageSitesJetpackProtect' == $_GET['page'] || 'managesites' == $_GET['page'] ) ) {
			return true;
		}
		return false;
	}

	/**
	 * Render extension page.
	 */
	public static function render() {
		self::render_tabs();
	}

	/**
	 * Render extension tabs.
	 */
	public static function render_tabs() {

		$curent_tab = '';

		if ( isset( $_GET['tab'] ) ) {
			if ( 'dashboard' == $_GET['tab'] ) {
				$curent_tab = 'dashboard';
			} else {
				$curent_tab = 'vulnerabilities';
			}
		} else {
			$curent_tab = 'dashboard';
		}
		?>
		<div class="ui labeled icon inverted menu mainwp-sub-submenu" id="mainwp-jetpack-protect-menu">
			<a href="admin.php?page=Extensions-Mainwp-Jetpack-Protect-Extension&tab=dashboard" class="item <?php echo ( $curent_tab == 'dashboard' ? 'active' : '' ); ?>"><i class="tasks icon"></i> <?php esc_html_e( 'Overview', 'mainwp-jetpack-protect-extension' ); ?></a>
			<a href="admin.php?page=Extensions-Mainwp-Jetpack-Protect-Extension&tab=vulnerabilities" class="item <?php echo ( $curent_tab == 'vulnerabilities' ? 'active' : '' ); ?>"><i class="shield alternate icon"></i> <?php esc_html_e( 'Vulnerabilities', 'mainwp-jetpack-protect-extension' ); ?></a>
		</div>
		<?php if ( 'dashboard' == $curent_tab ) : ?>
			<?php self::get_overview_tab(); ?>
		<?php else : ?>
			<?php self::get_vulnerabilities_tab(); ?>
		<?php endif; ?>
		<?php
	}

	/**
	 * Renders the Vulnerabilities tab
	 */
	public static function get_vulnerabilities_tab() {
		$dbwebsites = false;
		$sql_sites  = MainWP_Jetpack_Protect_DB::get_instance()->get_sql_websites_ext_data();

		if ( ! empty( $sql_sites ) ) {
			$dbwebsites = MainWP_Jetpack_Protect_DB::get_instance()->query( $sql_sites );
		}

		$show_no_jp_data_sites = apply_filters( 'show_no_jp_data_sites', false );
		?>
		<div class="ui segment" id="mainwp-jetpack-protect-vulnerabilities">
			<?php if ( MainWP_Jetpack_Protect_Utility::show_mainwp_message( 'protect-info-vulnerabilties-notice' ) ) : ?>
				<div class="ui info message">
					<?php printf( esc_html__( 'The Jetpack Protect Vulnerabilities page allows you to see all your websites where the Jetpack Protect plugin completed at least one scan.', 'mainwp-jetpack-protect-extension' ), '<i class="cog icon"></i>' ); ?><br/><br/>
					<?php printf( esc_html__( 'To see specific site details, click on the website row to toggle the details section. The newly appeared section will show you the breakdown of all detected issues. Here, you can also filter vulnerability details by clicking the number of detected problems in the list of plugins and themes.', 'mainwp-jetpack-protect-extension' ), '<i class="cog icon"></i>' ); ?>
					<i class="close icon mainwp-notice-dismiss" notice-id="protect-info-vulnerabilties-notice"></i>
				</div>
			<?php endif; ?>
			<?php if ( MainWP_Jetpack_Protect_Utility::show_mainwp_message( 'protect-info-dashboard-notice' ) ) : ?>
				<div class="ui info message">
					<?php printf( esc_html__( 'Jetpack Protect automatically scans your child sites once per day. This means that after resolving vulnerability issues, it can take up to 24 hours before the extension reflects changes.', 'mainwp-jetpack-protect-extension' ), '<i class="cog icon"></i>' ); ?>
					<i class="close icon mainwp-notice-dismiss" notice-id="protect-info-dashboard-notice"></i>
				</div>
			<?php endif; ?>
			<table class="ui table" id="mainwp-jetpack-protect-vulnerabilities-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Site', 'mainwp-jetpack-protect-extension' ); ?></th>
						<th class="center aligned"><?php esc_html_e( 'Last Scan', 'mainwp-jetpack-protect-extension' ); ?></th>
						<th class="center aligned"><span data-inverted="" data-position="left center" data-tooltip="<?php esc_attr_e( 'WordPress core threats', 'mainwp-jetpack-protect-extension' ); ?>"><i class="wordpress large icon"></i></span></th> <?php  //phpcs:ignore -- to fix WordPress icon. ?>
						<th class="center aligned"><span data-inverted="" data-position="left center" data-tooltip="<?php esc_attr_e( 'Plugins threats', 'mainwp-jetpack-protect-extension' ); ?>"><i class="plug large icon"></i></span></th>
						<th class="center aligned"><span data-inverted="" data-position="left center" data-tooltip="<?php esc_attr_e( 'Themes threats', 'mainwp-jetpack-protect-extension' ); ?>"><i class="tint large icon"></i></span></th>
						<th class="center aligned"><span data-inverted="" data-position="left center" data-tooltip="<?php esc_attr_e( 'Files threats', 'mainwp-jetpack-protect-extension' ); ?>"><i class="code large icon"></i></span></th>
						<th class="center aligned"><span data-inverted="" data-position="left center" data-tooltip="<?php esc_attr_e( 'Database threats', 'mainwp-jetpack-protect-extension' ); ?>"><i class="border all large icon"></i></span></th>
					</tr>
				</thead>
				<tbody class="ui accordion">
				<?php
				while ( $dbwebsites && ( $website = MainWP_Jetpack_Protect_DB::fetch_object( $dbwebsites ) ) ) {
					$plugins = json_decode( $website->plugins, 1 );
					if ( is_array( $plugins ) && 0 != count( $plugins ) ) {
						foreach ( $plugins as $plugin ) {
							if ( 'jetpack-protect/jetpack-protect.php' == $plugin['slug'] ) {
								$protect_data     = MainWP_Jetpack_Protect_Utility::map_fields( $website, array( 'lasttime_scan', 'hide_plugin', 'scan_time', 'connected', 'is_scan_active', 'num_vulnerabilities', 'num_plugins_vulnerabilities', 'num_themes_vulnerabilities', 'num_core_vulnerabilities' ) );
								$num_vuln         = isset( $protect_data['num_vulnerabilities'] ) ? intval( $protect_data['num_vulnerabilities'] ) : false;
								$num_core_vuln    = isset( $protect_data['num_core_vulnerabilities'] ) ? intval( $protect_data['num_core_vulnerabilities'] ) : false;
								$num_plugins_vuln = isset( $protect_data['num_plugins_vulnerabilities'] ) ? intval( $protect_data['num_plugins_vulnerabilities'] ) : false;
								$num_themes_vuln  = isset( $protect_data['num_themes_vulnerabilities'] ) ? intval( $protect_data['num_themes_vulnerabilities'] ) : false;
								$scan_actived     = isset( $protect_data['is_scan_active'] ) ? intval( $protect_data['is_scan_active'] ) : false;

								$v_color   = MainWP_Jetpack_Protect_Utility::get_vulnerabilities_number_color( $num_core_vuln );
								$vp_color  = MainWP_Jetpack_Protect_Utility::get_vulnerabilities_number_color( $num_plugins_vuln );
								$vth_color = MainWP_Jetpack_Protect_Utility::get_vulnerabilities_number_color( $num_themes_vuln );

								$lasttime_scan = isset( $protect_data['lasttime_scan'] ) ? intval( $protect_data['lasttime_scan'] ) : false;

								$jp_status_data = MainWP_Jetpack_Protect_DB::get_instance()->get_protect_status_by( 'wpid', $website->id, 1 );

								if ( ! empty( $jp_status_data ) ) {
									$jp_data = ! empty( $jp_status_data->status_data ) ? json_decode( $jp_status_data->status_data, true ) : array();
									if ( ! is_array( $jp_data ) ) {
										$jp_data = array();
									}
									$num_files_vuln    = isset( $jp_data['files'] ) ? count( $jp_data['files'] ) : false;
									$num_database_vuln = isset( $jp_data['database'] ) ? count( $jp_data['database'] ) : false;

									$vf_color        = MainWP_Jetpack_Protect_Utility::get_vulnerabilities_number_color( $num_files_vuln );
									$vd_color        = MainWP_Jetpack_Protect_Utility::get_vulnerabilities_number_color( $num_database_vuln );
									$jp_data_details = array(
										'core'     => array(
											'title'    => __( 'WordPress', 'mainwp-jetpack-protect-extension' ),
											'num_vuln' => $num_core_vuln,
											'items'    => isset( $jp_data['core'] ) ? $jp_data['core'] : array(),
										),
										'plugins'  => array(
											'title'    => __( 'Plugins', 'mainwp-jetpack-protect-extension' ),
											'num_vuln' => $num_plugins_vuln,
											'items'    => isset( $jp_data['plugins'] ) ? $jp_data['plugins'] : array(),
										),
										'themes'   => array(
											'title'    => __( 'Themes', 'mainwp-jetpack-protect-extension' ),
											'num_vuln' => $num_themes_vuln,
											'items'    => isset( $jp_data['themes'] ) ? $jp_data['themes'] : array(),
										),
										'files'    => array(
											'title'    => __( 'Files', 'mainwp-jetpack-protect-extension' ),
											'num_vuln' => $num_files_vuln,
											'items'    => isset( $jp_data['files'] ) ? $jp_data['files'] : array(),
										),
										'database' => array(
											'title'    => __( 'Database', 'mainwp-jetpack-protect-extension' ),
											'num_vuln' => $num_database_vuln,
											'items'    => isset( $jp_data['database'] ) ? $jp_data['database'] : array(),
										),
									);
								}

								?>
								<?php
								if ( ! empty( $lasttime_scan ) ) :

									$disabled_tooltip = '';
									if ( ! $scan_actived ) {
										$disabled_tooltip = ' data-inverted="" data-position="left center" data-tooltip="' . esc_html__( 'Jetpack Scan required.', 'mainwp-jetpack-protect-extension' ) . '" ';
										$vf_color         = 'greyed';
										$vd_color         = 'greyed';
									}

									?>
									<tr class="<?php echo $num_vuln > 0 ? 'red' : 'green'; ?> left marked title" >
										<td>
											<a href="admin.php?page=ManageSitesJetpackProtect&id=<?php echo $website->id; ?>" data-tooltip="<?php esc_attr_e( 'Click to jump to the site Jetpack Protect overview page', 'mainwp-jetpack-protect-extension' ); ?>" data-position="right center" data-inverted=""><?php echo $website->name; ?></a>
											<div><span class="ui small text"><a href="<?php echo esc_url( $website->url ); ?>"><?php echo $website->url; ?></a></span></div>
										</td>
										<td class="center aligned"><?php echo MainWP_Jetpack_Protect_Utility::format_timestamp( MainWP_Jetpack_Protect_Utility::get_timestamp( $lasttime_scan ) ); ?></td>
										<td class="center aligned"><span class="ui big basic <?php esc_attr_e( $v_color ); ?> label"><?php echo $num_core_vuln; ?></span></td>
										<td class="center aligned"><span class="ui big basic <?php esc_attr_e( $vp_color ); ?> label"><?php echo $num_plugins_vuln; ?></span></td>
										<td class="center aligned"><span class="ui big basic <?php esc_attr_e( $vth_color ); ?> label"><?php echo $num_themes_vuln; ?></span></td>
										<td class="center aligned"><span class="ui big basic <?php esc_attr_e( $vf_color ); ?> label" <?php echo $disabled_tooltip; ?>><?php echo $num_files_vuln; ?></span></td>
										<td class="center aligned"><span class="ui big basic <?php esc_attr_e( $vd_color ); ?> label" <?php echo $disabled_tooltip; ?>><?php echo $num_database_vuln; ?></span></td>
									</tr>
									<tr class="<?php echo $num_vuln > 0 ? 'red' : 'green'; ?> left marked content">
										<td colspan="7">
											<div class="ui white segment">
												<div class="ui very relaxed grid">
													<div class="eight wide column">
														<table class="ui table accordion" id="mainwp-jetpack-protect-vulnerabilities-type-table" website-id="<?php echo intval( $website->id ); ?>" status-id="<?php echo $jp_status_data ? intval( $jp_status_data->statusid ) : 0; ?>">
															<tbody>
																<tr>
																	<td><?php esc_html_e( 'All Vulnerabilities', 'mainwp-jetpack-protect-extension' ); ?></td>
																	<td class="right aligned"><?php echo $num_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-all-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																</tr>
																<tr class="title">
																	<td><i class="dropdown icon"></i> <?php esc_html_e( 'WordPress', 'mainwp-jetpack-protect-extension' ); ?></td>
																	<td class="right aligned"><?php echo $num_core_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-wp-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_core_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																</tr>
																<tr class="content">
																	<?php
																	foreach ( $jp_data_details as $type => $jp_details ) {
																		$items = $jp_details['items'];
																		if ( ! is_array( $items ) ) {
																			$items = array();
																		}
																		if ( empty( $items ) ) {
																			continue;
																		}
																		if ( 'core' === $type ) {
																			$name     = isset( $items['name'] ) ? esc_html( $items['name'] ) : '';
																			$num_vuln = isset( $items['threats'] ) && is_array( $items['threats'] ) ? count( $items['threats'] ) : false;
																			$version  = isset( $items['version'] ) ? esc_html( $items['version'] ) : '';
																			?>
																			<td>
																				<i class="wordpress large icon"></i> <?php  //phpcs:ignore -- to fix WordPress word. ?>
																				<?php echo esc_html( $name . ' ' . $version ); ?>
																			</td>
																			<td class="right aligned"><?php echo $num_core_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-wp-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_core_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																			<?php
																		}
																	}
																	?>
																</tr>

																<tr class="title">
																	<td><i class="dropdown icon"></i> <?php esc_html_e( 'Plugins', 'mainwp-jetpack-protect-extension' ); ?></td>
																	<td class="right aligned"><?php echo $num_plugins_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-plugins-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_plugins_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																</tr>
																<tr class="content">
																	<td colspan="2">
																		<table class="ui table">
																			<tbody>
																				<?php
																				foreach ( $jp_data_details as $type => $jp_details ) {
																					$items = $jp_details['items'];
																					if ( ! is_array( $items ) ) {
																						$items = array();
																					}
																					if ( empty( $items ) ) {
																						continue;
																					}
																					if ( 'plugins' === $type ) {
																						foreach ( $items as $item ) {
																							$name     = isset( $item['name'] ) ? esc_html( $item['name'] ) : '';
																							$slug     = isset( $item['slug'] ) ? esc_html( $item['slug'] ) : '';
																							$num_vuln = isset( $item['threats'] ) && is_array( $item['threats'] ) ? count( $item['threats'] ) : false;
																							$version  = isset( $item['version'] ) ? esc_html( $item['version'] ) : '';
																							$dir_slug = '';
																							$icon     = '';

																							if ( ! empty( $slug ) ) {
																								$dir_slug = apply_filters( 'mainwp_get_dir_slug', $slug, $slug );
																								$icon     = apply_filters( 'mainwp_get_plugin_icon', '', $dir_slug );
																							}
																							?>
																							<tr>
																								<td><?php echo $icon . ' ' . esc_html( $name . ' ' . $version ); ?></td>
																								<td class="right aligned"><?php echo $num_vuln > 0 ? '<a href="javascript:void(0)" item-slug="' . $slug . '" class="ui circular large red label mainwp-item-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																							</tr>
																							<?php
																						}
																					}
																				}
																				?>
																			</tbody>
																		</table>
																	</td>
																</tr>

																<tr class="title">
																	<td><i class="dropdown icon"></i> <?php esc_html_e( 'Themes', 'mainwp-jetpack-protect-extension' ); ?></td>
																	<td class="right aligned"><?php echo $num_themes_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-themes-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_themes_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																</tr>
																<tr class="content">
																	<td colspan="2">
																		<table class="ui table">
																			<tbody>
																				<?php
																				foreach ( $jp_data_details as $type => $jp_details ) {
																					$items = $jp_details['items'];
																					if ( ! is_array( $items ) ) {
																						$items = array();
																					}
																					if ( empty( $items ) ) {
																						continue;
																					}
																					if ( 'themes' === $type ) {
																						foreach ( $items as $item ) {
																							$name     = isset( $item['name'] ) ? esc_html( $item['name'] ) : '';
																							$slug     = isset( $item['slug'] ) ? esc_html( $item['slug'] ) : '';
																							$num_vuln = isset( $item['threats'] ) && is_array( $item['threats'] ) ? count( $item['threats'] ) : false;
																							$version  = isset( $item['version'] ) ? esc_html( $item['version'] ) : '';
																							$dir_slug = '';
																							$icon     = '';

																							if ( ! empty( $slug ) ) {
																								$dir_slug = apply_filters( 'mainwp_get_dir_slug', $slug, $slug );
																								$icon     = apply_filters( 'mainwp_get_theme_icon', '', $dir_slug );
																							}
																							?>
																							<tr>
																								<td><?php echo $icon . ' ' . esc_html( $name . ' ' . $version ); ?></td>
																								<td class="right aligned"><?php echo $num_vuln > 0 ? '<a href="javascript:void(0)" item-slug="' . $slug . '" class="ui circular large red label" style="color:#fff!important;">' . $num_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																							</tr>
																							<?php
																						}
																					}
																				}
																				?>
																			</tbody>
																		</table>
																	</td>
																</tr>

																<tr>
																	<td><i class="dropdown icon" style="opacity:0"></i> <?php esc_html_e( 'Files', 'mainwp-jetpack-protect-extension' ); ?></td>
																	<td class="right aligned"><?php echo $num_files_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-files-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_files_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																</tr>
																

																<tr>
																	<td><i class="dropdown icon" style="opacity:0"></i> <?php esc_html_e( 'Database', 'mainwp-jetpack-protect-extension' ); ?></td>
																	<td class="right aligned"><?php echo $num_database_vuln > 0 ? '<a href="javascript:void(0)" class="ui circular large red label mainwp-database-jp-vulnerabilities-label" style="color:#fff!important;">' . $num_database_vuln . '</a>' : '<i class="green large check icon"></i>'; ?></td>
																</tr>

															</tbody>
														</table>
													</div>
													<div class="eight wide column">
														<?php if ( ! empty( $jp_data_details ) ) : ?>
															<table class="ui table accordion" id="mainwp-jetpack-protect-vulnerabilities-table" website-id="<?php echo intval( $website->id ); ?>" status-id="<?php echo $jp_status_data ? intval( $jp_status_data->statusid ) : 0; ?>">
																<tbody>
																<?php foreach ( $jp_data_details as $type => $jp_details ) : ?>
																	<?php
																	$items = $jp_details['items'];
																	if ( ! is_array( $items ) ) {
																		$items = array();
																	}
																	if ( empty( $items ) ) {
																		continue;
																	}

																	if ( 'core' === $type ) {
																		$vuln_items = isset( $items['threats'] ) && is_array( $items['threats'] ) ? $items['threats'] : array();
																		if ( empty( $vuln_items ) ) {
																			continue;
																		}
																		self::render_row_detail_data( $vuln_items, $type, $items, $website->id );
																	} elseif ( 'plugins' === $type || 'themes' === $type ) {
																		foreach ( $items as $detail ) :
																			$vuln_items = isset( $detail['threats'] ) && is_array( $detail['threats'] ) ? $detail['threats'] : array();
																			if ( empty( $vuln_items ) ) {
																				continue;
																			}
																			self::render_row_detail_data( $vuln_items, $type, $detail, $website->id );
																		endforeach;
																	} elseif ( 'files' === $type ) {
																		$vuln_items = isset( $items ) && is_array( $items ) ? $items : array();
																		if ( empty( $vuln_items ) ) {
																			continue;
																		}
																		self::render_row_detail_data( $vuln_items, $type, $items, $site_id );
																	}
																	?>
																<?php endforeach; ?>
																</tbody>
															</table>
														<?php endif; ?>
													</div>
												</div>
												<div class="ui vertical divider"></div>
											</div>
										</td>
									</tr>
								<?php elseif ( $show_no_jp_data_sites ) : ?>
									<tr class="yellow left marked">
										<td>
											<a href="admin.php?page=ManageSitesJetpackProtect&id=<?php echo $website_id; ?>" data-tooltip="<?php esc_attr_e( 'Click to jump to the site Jetpack Protect overview page', 'mainwp-jetpack-protect-extension' ); ?>" data-position="right center" data-inverted=""><?php echo $website->name; ?></a>
											<div><span class="ui small text"><a href="<?php echo esc_url( $website->url ); ?>"><?php echo $website->url; ?></a></span></div>
										</td>
										<td colspan="4" class="right aligned">
											<?php esc_html_e( 'Jetpack Protect vulnerability data not found for the site.', 'mainwp-jetpack-protect-extension' ); ?>
											<div><span class="ui small text"><?php esc_html_e( 'Install, activate and connect the Jetpack Protect plugin on the child site to so start scanning it.', 'mainwp-jetpack-protect-extension' ); ?></span></div>
										</td>
									</tr>
								<?php endif; ?>
								<?php
								break;
							}
						}
					}
				}
				?>
				</tbody>
			</table>
		</div>
		<script type="text/javascript">
			jQuery( 'tbody.ui.accordion' ).accordion({
				exclusive : false,
				duration : 50,
			});

		</script>
		<?php
	}

	/**
	 * Individual detail Metabox
	 *
	 * Renders the individual site Overview page widget content.
	 *
	 * @param array  $vuln_items vulnerabilities items.
	 * @param string $type vulnerabilities type.
	 * @param array  $detail protect status detail.
	 * @param int    $site_id The website ID.
	 *
	 * @return void
	 */
	public static function render_row_detail_data( $vuln_items, $type, $detail, $site_id ) {

		$name        = isset( $detail['name'] ) ? esc_html( $detail['name'] ) : '';
		$slug        = isset( $detail['slug'] ) ? esc_html( $detail['slug'] ) : '';
		$version     = isset( $detail['version'] ) ? esc_html( $detail['version'] ) : '';
		$link_detail = '';

		if ( 'plugins' === $type && ! empty( $slug ) ) {
			$dir_slug    = apply_filters( 'mainwp_get_dir_slug', $slug, $slug );
			$link_detail = admin_url() . 'plugin-install.php?tab=plugin-information&plugin=' . rawurlencode( $dir_slug );
		}

		if ( 'plugins' === $type ) {
			$icon = '<span data-inverted="" data-position="left center" data-tooltip="' . esc_attr__( 'Plugin threat', 'mainwp-jetpack-protect-extension' ) . '"><i class="plug large icon"></i></span>';
		} elseif ( 'themes' === $type ) {
			$icon = '<span data-inverted="" data-position="left center" data-tooltip="' . esc_attr__( 'Theme threat', 'mainwp-jetpack-protect-extension' ) . '"><i class="tint large icon"></i></span>';
		} elseif ( 'files' === $type ) {
			$icon = '<span data-inverted="" data-position="left center" data-tooltip="' . esc_attr__( 'File threat', 'mainwp-jetpack-protect-extension' ) . '"><i class="code large icon"></i></span>';
		} elseif ( 'database' === $type ) {
			$icon = '<span data-inverted="" data-position="left center" data-tooltip="' . esc_attr__( 'Database threat', 'mainwp-jetpack-protect-extension' ) . '"><i class="border all large icon"></i></span>';
		} else {
			$icon = '<span data-inverted="" data-position="left center" data-tooltip="' . esc_attr__( 'WP Core threat', 'mainwp-jetpack-protect-extension' ) . '"><i class="wordpress large icon"></i></span>'; //phpcs:ignore -- to fix WordPress word. 
		}

		if ( ! empty( $vuln_items ) ) {
			foreach ( $vuln_items as $vuln_item ) :
				$vuln_id     = isset( $vuln_item['id'] ) ? $vuln_item['id'] : '';
				$title       = isset( $vuln_item['title'] ) ? $vuln_item['title'] : '';
				$fixed_in    = isset( $vuln_item['fixed_in'] ) ? $vuln_item['fixed_in'] : '';
				$description = isset( $vuln_item['description'] ) ? $vuln_item['description'] : '';
				$signature   = isset( $vuln_item['signature'] ) ? $vuln_item['signature'] : '';
				$filename    = isset( $vuln_item['filename'] ) ? $vuln_item['filename'] : '';
				$source      = isset( $vuln_item['source'] ) ? $vuln_item['source'] : '';
				?>
					<tr class="title" type="<?php esc_attr_e( $type ); ?>" item-slug="<?php esc_attr_e( $slug ); ?>">
						<td>
							<h4 class="ui header">
								<?php if ( $version == $fixed_in && 'files' !== $type ) : ?>
								<i class="cog loading icon"></i>
								<?php else : ?>
									<?php echo $icon; ?>
								<?php endif; ?>
								<div class="content">
									<?php
									if ( 'core' === $type ) {
										echo esc_html( $name . ' ' . $version );
									} elseif ( 'plugins' === $type || 'themes' === $type ) {
										if ( 'plugins' === $type && ! empty( $link_detail ) ) {
											?>
											<a href="<?php echo esc_url( $link_detail ); ?>" target="_blank" class="open-plugin-details-modal"><?php echo esc_html( $name . ' ' . $version ); ?></a>
											<?php
										} else {
											echo esc_html( $name . ' ' . $version );
										}
									} elseif ( 'files' === $type ) {
										echo esc_html( $title );
									}
									?>
								<div class="sub header">
									<?php if ( 'files' === $type ) : ?>
										<?php echo esc_html( $signature ); ?>
									<?php else : ?>
										<?php echo esc_html( $title ); ?>
									<?php endif; ?>
								</div>
								</div>
							</h4>
						</td>
					</tr>
					<tr class="content" item-slug="<?php echo esc_attr( $slug ); ?>" type="<?php echo esc_attr( $type ); ?>" item-type="<?php echo esc_attr( $type ); ?>" website-id="<?php echo intval( $site_id ); ?>">
						<td>
							<div class="ui segment">
								<p><strong><?php esc_html_e( 'What is the problem?', 'mainwp-jetpack-protect-extension' ); ?></strong></p>
								<p><?php echo esc_html( $description ); ?></p>
								<?php if ( 'files' !== $type ) : ?>
								<p><?php printf( esc_html__( '%1$sSee more technical details of this vulnerability%2$s', 'mainwp-jetpack-protect-extension' ), '<a href="' . esc_attr( $source ) . '" target="_blank">', '</a>' ); ?></p>
								<?php endif; ?>
								<?php if ( $version == $fixed_in && 'files' !== $type ) : ?>
								<div class="ui info message"><?php esc_html_e( 'Fix submitted. Changes will be reflected after the Jetpack Protect completes rescan process. Please try to resync your MainWP Dashboard later.', 'mainwp-jetpack-protect-extension' ); ?></div>	
								<?php else : ?>
									<?php if ( 'core' !== $type && 'files' !== $type && 'database' !== $type ) { ?>
								<p><strong><?php esc_html_e( 'How to fix it?', 'mainwp-jetpack-protect-extension' ); ?></strong></p>
								<?php } ?>
									<?php if ( 'files' === $type ) : ?>
								<p><strong><?php esc_html_e( 'File:', 'mainwp-jetpack-protect-extension' ); ?></strong></p>
								<p><?php echo esc_html( $filename ); ?></p>
								<?php endif; ?>
								<p>
									<?php if ( ! empty( $fixed_in ) ) { ?>
									<a href="javascript:void(0)" class="ui basic green button mainwp-jetpack-protect-widget-update-item"><?php echo esc_html__( 'Update to', 'mainwp-jetpack-protect-extension' ) . ' ' . esc_html( $name ) . ' ' . esc_html( $fixed_in ); ?></a>
								<?php } ?>
									<?php if ( 'core' !== $type && 'files' !== $type && 'database' !== $type ) { ?>
									<a href="javascript:void(0)" class="ui button mainwp-jetpack-protect-widget-delete-item"><?php echo esc_html__( 'Delete', 'mainwp-jetpack-protect-extension' ) . ' ' . esc_html( $name ) . ' ' . esc_html( $version ); ?></a>
								<?php } ?>
								</p>
								<?php endif; ?>
								<div class="ui active inverted dimmer mainwp-loader-element" style="display:none">
									<div class="ui text loader"><?php esc_html_e( 'Please wait...', 'mainwp-jetpack-protect-extension' ); ?></div>
								</div>
							</div>
						</td>
					</tr>
				<?php
				endforeach;
		}
	}

	/**
	 * Renders the Overview tab
	 */
	public static function get_overview_tab() {
		global $mainJetpackProtectExtensionActivator;

		$filter_groups = false;
		if ( isset( $_GET['group'] ) && ! empty( $_GET['group'] ) ) {
			$filter_groups = explode( '-', $_GET['group'] );
			if ( ! is_array( $filter_groups ) ) {
				$filter_groups = array();
			}
		}

		?>
		<?php MainWP_Jetpack_Protect_Plugin::get_instance()->gen_actions_bar( $filter_groups ); ?>
		<div class="ui segment" id="mainwp-jetpack-protect-dashboard">
		<?php if ( MainWP_Jetpack_Protect_Utility::show_mainwp_message( 'protect-info-dashboard-notice' ) ) : ?>
			<div class="ui info message">
				<?php printf( esc_html__( 'Jetpack Protect automatically scans your child sites once per day. This means that after resolving vulnerability issues, it can take up to 24 hours before the extension reflects changes.', 'mainwp-jetpack-protect-extension' ), '<i class="cog icon"></i>' ); ?>
				<i class="close icon mainwp-notice-dismiss" notice-id="protect-info-dashboard-notice"></i>
			</div>
		<?php endif; ?>
			<?php MainWP_Jetpack_Protect_Plugin::get_instance()->gen_dashboard_table( $filter_groups ); ?>
		</div>
		<?php
	}

	/**
	 * Method ajax_showhide_plugin()
	 *
	 * Ajax show/hide plugin.
	 */
	public function ajax_jetpack_connect_disconnect() {
		do_action( 'mainwp_secure_request', 'mainwp_jetpack_protect_connect_disconnect' );

		$siteid = isset( $_POST['websiteId'] ) ? intval( $_POST['websiteId'] ) : null;
		$status = isset( $_POST['connect_status'] ) ? $_POST['connect_status'] : '';

		$result = $this->handle_connect_disconnect( $siteid, $status );

		if ( ! empty( $result ) ) {
			die( json_encode( $result ) );
		} else {
			wp_die( 'Invalid request.' );
		}

	}

	/**
	 * Method handle_connect_disconnect()
	 *
	 * Ajax show/hide plugin.
	 */
	public function handle_connect_disconnect( $siteid, $status ) {

		if ( ! empty( $siteid ) && ( 'connect' === $status || 'disconnect' === $status ) ) {
			global $mainJetpackProtectExtensionActivator;
			$post_data   = array(
				'mwp_action' => 'set_connect_disconnect',
				'status'     => $status,
			);
			$information = apply_filters( 'mainwp_fetchurlauthed', $mainJetpackProtectExtensionActivator->get_child_file(), $mainJetpackProtectExtensionActivator->get_child_key(), $siteid, 'jetpack_protect', $post_data );

			if ( is_array( $information ) && isset( $information['code'] ) && 'success' === $information['code'] ) {
				$update = array(
					'wpid'      => $siteid,
					'connected' => ! empty( $information['connected'] ) ? 1 : 0,
				);
				MainWP_Jetpack_Protect_DB::get_instance()->update_protect( $update );
			}
			return $information;
		}

		return false;
	}

	/**
	 * Method ajax_upgrade_item()
	 *
	 * Ajax upgrade plugin/theme/wp.
	 */
	public function ajax_upgrade_item() {
		do_action( 'mainwp_secure_request', 'mainwp_jetpack_protect_upgrade_plugintheme' );
		$type = isset( $_POST['type'] ) ? $_POST['type'] : '';

		if ( 'plugin' === $type || 'theme' === $type ) {
			do_action( 'mainwp_action_upgradeplugintheme' );
			wp_die( 'done' );
		}

		wp_die( 'Invalid request.' );
	}


	/**
	 * Method ajax_delete_item()
	 *
	 * Ajax delete plugin/theme.
	 */
	public function ajax_delete_item() {
		do_action( 'mainwp_secure_request', 'mainwp_jetpack_protect_delete_plugintheme' );
		$type = isset( $_POST['type'] ) ? $_POST['type'] : '';
		if ( 'plugin' === $type ) {
			do_action( 'mainwp_action_deleteplugin' );
			wp_die( 'done' );
		} elseif ( 'theme' === $type ) {
			do_action( 'mainwp_action_deletetheme' );
			wp_die( 'done' );
		}
		wp_die( 'Invalid request.' );
	}

	/**
	 * Hook get reports tokens value.
	 */
	public static function hook_get_reports_tokens_value( $input, $site_id, $lasttime_scan = false ) {

		if ( empty( $site_id ) ) {
			return $input;
		}

		if ( empty( $lasttime_scan ) ) {
			$lasttime_scan = time();
		}

		$input = array();

		$input['jetpack.protect.plugins.count'] = 'N/A';
		$input['jetpack.protect.themes.count']  = 'N/A';
		$input['jetpack.protect.wp.count']      = 'N/A';
		$input['jetpack.protect.plugins']       = 'N/A';
		$input['jetpack.protect.themes']        = 'N/A';
		$input['jetpack.protect.wp']            = 'N/A';

		$last_protect_status = MainWP_Jetpack_Protect_DB::get_instance()->get_protect_status_by( 'wpid', $site_id, 1, $lasttime_scan );

		if ( empty( $last_protect_status ) ) {
			return $input;
		}

		$status_data = ! empty( $last_protect_status->status_data ) ? json_decode( $last_protect_status->status_data, true ) : array();
		if ( ! is_array( $status_data ) ) {
			$status_data = array();
		}

		$num_core_vuln    = isset( $status_data['core'] ) && isset( $status_data['core']['threats'] ) && is_array( $status_data['core']['threats'] ) ? count( $status_data['core']['threats'] ) : 'N/A';
		$num_plugins_vuln = isset( $status_data['num_plugins_threats'] ) ? intval( $status_data['num_plugins_threats'] ) : 'N/A';
		$num_themes_vuln  = isset( $status_data['num_themes_threats'] ) ? intval( $status_data['num_themes_threats'] ) : 'N/A';

		$core_status    = '';
		$plugins_status = '';
		$themes_status  = '';
		$all_num_vuln   = 0;

		if ( ! empty( $status_data ) ) {
			$lists_details = array(
				'core'    => array(
					'num_vuln' => $num_core_vuln,
					'items'    => isset( $status_data['core'] ) ? $status_data['core'] : array(),
				),
				'plugins' => array(
					'title'    => __( 'Plugins', 'mainwp-jetpack-protect-extension' ),
					'num_vuln' => $num_plugins_vuln,
					'items'    => isset( $status_data['plugins'] ) ? $status_data['plugins'] : array(),
				),
				'themes'  => array(
					'title'    => __( 'Themes', 'mainwp-jetpack-protect-extension' ),
					'num_vuln' => $num_themes_vuln,
					'items'    => isset( $status_data['themes'] ) ? $status_data['themes'] : array(),
				),

			);
		}

		if ( ! empty( $status_data ) ) {
			?>
				<?php foreach ( $lists_details as $type => $detail ) : ?>
					<?php ob_start(); ?>
						<?php
						$items = $detail['items'];
						if ( ! is_array( $items ) ) {
							$items = array();
						}
						if ( empty( $items ) ) {
							continue;
						}
						foreach ( $items as $detail ) :
							$vuln_items = isset( $detail['threats'] ) && is_array( $detail['threats'] ) ? $detail['threats'] : array();
							if ( empty( $vuln_items ) ) {
								continue;
							}
							$all_num_vuln += count( $vuln_items );
							$name          = isset( $detail['name'] ) ? esc_html( $detail['name'] ) : '';
							$slug          = isset( $detail['slug'] ) ? esc_html( $detail['slug'] ) : '';
							$version       = isset( $detail['version'] ) ? esc_html( $detail['version'] ) : '';
							foreach ( $vuln_items as $vuln_item ) :
								$vuln_id     = isset( $vuln_item['id'] ) ? $vuln_item['id'] : '';
								$title       = isset( $vuln_item['title'] ) ? $vuln_item['title'] : '';
								$fixed_in    = isset( $vuln_item['fixed_in'] ) ? $vuln_item['fixed_in'] : '';
								$description = isset( $vuln_item['description'] ) ? $vuln_item['description'] : '';
								?>
								<strong><?php echo esc_html( $name . ' ' . $version ); ?></strong></br>
								<?php echo esc_html( $title ); ?></br>
								<strong><?php esc_html_e( 'What is the problem?', 'mainwp-jetpack-protect-extension' ); ?></strong></br>
								<?php echo esc_html( $description ); ?></br>
								<?php printf( esc_html__( '%1$sSee more technical details of this vulnerability%2$s', 'mainwp-jetpack-protect-extension' ), '<a href="https://jetpack.com/redirect/?source=jetpack-protect-vul-info&path=' . esc_url( $vuln_id ) . '" target="_blank">', '</a>' ); ?></br>
								<strong><?php esc_html_e( 'How to fix it?', 'mainwp-jetpack-protect-extension' ); ?></strong></br>
								<?php echo esc_html__( 'Update to', 'mainwp-jetpack-protect-extension' ) . ' ' . esc_html( $name ) . ' ' . esc_html( $fixed_in ); ?></br>
							<?php endforeach; // foreach $vuln_items ?>
					<?php endforeach; // foreach $items ?>
					<?php
					if ( 'core' === $type ) {
						$core_status = ob_get_clean();
					} elseif ( 'plugins' === $type ) {
						$plugins_status = ob_get_clean();
					} elseif ( 'themes' === $type ) {
						$themes_status = ob_get_clean();
					}
					?>
				<?php endforeach; // foreach $lists_details ?>
			<?php
		}

		$input['jetpack.protect.plugins.count'] = $num_plugins_vuln;
		$input['jetpack.protect.themes.count']  = $num_themes_vuln;
		$input['jetpack.protect.wp.count']      = $num_core_vuln;
		$input['jetpack.protect.plugins']       = $plugins_status;
		$input['jetpack.protect.themes']        = $themes_status;
		$input['jetpack.protect.wp']            = $core_status;

		return $input;
	}
}
