<?php

class MainWP_Vulnerability_Checker { // phpcs:ignore -- NOSONAR - multi methods.

	protected static $_instance    = null;
	protected $settings            = null;
	public static $enabled_service = null;

	// Constructor.
	public function __construct() {
		add_action( 'init', array( &$this, 'init_cron' ) );
		add_action( 'mainwp_cron_vulner_recheck', array( self::class, 'cron_vulner_recheck' ) );
		add_action( 'mainwp_cron_jobs_list', array( $this, 'cron_job_info' ) );
		// phpcs:ignore -- required for scheduled jobs.
		add_filter('cron_schedules', array($this, 'get_cron_schedules'));
	}

	public static function instance() {

		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public function admin_init() {
		add_action( 'wp_ajax_mainwp_vulner_result_recheck', array( $this, 'ajax_vulner_result_recheck' ) );
		add_action( 'wp_ajax_mainwp_vulner_upgrade_plugintheme', array( $this, 'ajax_upgrade_plugintheme' ) );
		add_action( 'wp_ajax_mainwp_vulner_delete_plugin', array( $this, 'ajax_delete_plugin' ) );
		add_action( 'wp_ajax_mainwp_vulner_delete_theme', array( $this, 'ajax_delete_theme' ) );
		add_action( 'wp_ajax_mainwp_vulner_load_sites', array( $this, 'ajax_load_sites' ) );
		$this->handle_post_settings();
	}

	public function init_cron() {

		$settings = self::instance()->get_current_service_settings();
		$schedule = is_array( $settings ) && isset( $settings['schedule'] ) ? $settings['schedule'] : '';
		$stop_job = false;

		if ( in_array( $schedule, array( 'daily', 'weekly', 'monthly' ) ) ) {
			$last_cron_recheck = get_option( 'mainwp_vulner_cron_recheck_last', 0 );
			$local_timestamp   = MainWP_Vulnerability_Utility::get_timestamp();
			$threshold         = MainWP_Vulnerability_Utility::get_time_threshold( $schedule );
			$time_run          = ( ( $local_timestamp - $last_cron_recheck ) < $threshold ) ? false : true;

			$recheck_finished = get_option( 'mainwp_vulner_cron_recheck_finished', false );
			if ( $time_run && $recheck_finished ) {
				update_option( 'mainwp_vulner_cron_recheck_finished', false );
				$recheck_finished = false;
				MainWP_Vulnerability_Utility::log_debug( 'start job' );
			}

			if ( $time_run && ! $recheck_finished ) {
				// check to schedule job.
				$useWPCron = ( get_option( 'mainwp_wp_cron' ) === false ) || ( get_option( 'mainwp_wp_cron' ) == 1 );
				if ( ( $sched = wp_next_scheduled( 'mainwp_cron_vulner_recheck' ) ) == false ) {
					if ( $useWPCron ) {
						wp_schedule_event( time(), '10minutely', 'mainwp_cron_vulner_recheck' );
					}
				} elseif ( ! $useWPCron ) {
					wp_unschedule_event( $sched, 'mainwp_cron_vulner_recheck' );
				}
			}

			if ( ! $time_run && $recheck_finished ) {
				$stop_job = true;
			}
		} else {
			$stop_job = true;
		}

		if ( $stop_job ) {
			if ( $sched = wp_next_scheduled( 'mainwp_cron_vulner_recheck' ) ) {
				wp_unschedule_event( $sched, 'mainwp_cron_vulner_recheck' );
				MainWP_Vulnerability_Utility::log_debug( 'stop job' );
			}
		}
	}


	/**
	 * Method get_cron_schedules()
	 *
	 * Get current Cron Schedual.
	 *
	 * @param array $schedules Array of currently set scheduals.
	 *
	 * @return array $scheduales.
	 */
	public function get_cron_schedules( $schedules ) {
		$schedules['10minutely'] = array(
			'interval' => 10 * 60,
			'display'  => __( 'Once every 10 minutes', 'mainwp' ),
		);
		return $schedules;
	}

	public function cron_job_info() {

		$settings = self::instance()->get_current_service_settings();

		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		$schedule = isset( $settings['schedule'] ) ? $settings['schedule'] : '';

		$lastAutomaticCheck = '';
		$nextAutomaticCheck = '';

		if ( $schedule != '' ) {
			$lastAutomaticCheck = get_option( 'mainwp_vulner_cron_recheck_last', 0 );
			if ( $lastAutomaticCheck == 0 ) {
				$lastAutomaticCheck = __( 'Never' );
			} else {
				$lastAutomaticCheck = MainWP_Vulnerability_Utility::formatTimestamp( MainWP_Vulnerability_Utility::get_timestamp( $lastAutomaticCheck ) );
			}
		}

		$nextAutomaticCheck = MainWP_Vulnerability_Utility::formatTimestamp( MainWP_Vulnerability_Utility::get_timestamp( wp_next_scheduled( 'mainwp_cron_vulner_recheck' ) ) );
		?>
		<tr>
			<td><?php esc_html_e( 'Check for vulnerabilities', 'mainwp-vulnerabilities-checker-extension' ); ?></td>
			<td><?php echo 'mainwp_cron_vulner_recheck'; ?></td>
			<td><?php esc_html_e( 'Once hourly', 'mainwp-vulnerabilities-checker-extension' ); ?></td>
			<td><?php echo esc_html( $lastAutomaticCheck ); ?></td>
			<td><?php echo esc_html( $nextAutomaticCheck ); ?></td>
		</tr>
		<?php
	}

	public static function cron_vulner_recheck() {

		MainWP_Vulnerability_Utility::log_debug( 'checker running' );
		$settings = self::instance()->get_current_service_settings();
		if ( ! is_array( $settings ) || ! isset( $settings['schedule'] ) || empty( $settings['schedule'] ) ) {
			return;
		}
		$schedule = $settings['schedule'];

		if ( $schedule != 'daily' && $schedule != 'weekly' && $schedule != 'monthly' ) {
			return;
		}

		$threshold = MainWP_Vulnerability_Utility::get_time_threshold( $schedule );

		if ( empty( $threshold ) ) {
			return;
		}

		$sent_email = get_option( 'mainwp_vulner_cron_recheck_sent_email' );

		$local_timestamp = MainWP_Vulnerability_Utility::get_timestamp();
		$sites           = MainWP_Vulnerability_DB::instance()->get_sites_to_recheck( $schedule, $threshold, $local_timestamp );
		MainWP_Vulnerability_Utility::log_debug( 'checker get sites :: count :: ' . ( $sites ? count( $sites ) : 0 ) );
		$finished = false;

		if ( is_array( $sites ) ) {
			if ( count( $sites ) == 0 ) {
				$finished = true;
			} else {
				if ( $sent_email ) {
					update_option( 'mainwp_vulner_cron_recheck_sent_email', false );
					$sent_email = false;
				}
				foreach ( $sites as $site ) {
					self::instance()->do_vulner_result_recheck( $site['site_id'], true );
					$update = array(
						'site_id'    => $site['site_id'],
						'last_check' => $local_timestamp,
					);
					MainWP_Vulnerability_DB::instance()->update_vulner_result( $update );
				}
			}
		} else {
			$finished = true;
		}

		if ( $finished ) {

			update_option( 'mainwp_vulner_cron_recheck_finished', true );
			update_option( 'mainwp_vulner_cron_recheck_last', $local_timestamp );

			if ( isset( $settings['noti'] ) && $settings['noti'] ) {
				global $mainwp_VulnerCheckerExtensionActivator;

				$all_sites = apply_filters( 'mainwp_getsites', $mainwp_VulnerCheckerExtensionActivator->get_child_file(), $mainwp_VulnerCheckerExtensionActivator->get_child_key(), null );

				if ( ! is_array( $all_sites ) ) {
					$all_sites = array();
				}

				$send_noti_sites = array();

				foreach ( $all_sites as $website ) {
					$send_noti_sites[ $website['id'] ] = $website;
				}

				unset( $all_sites );

				$body = '';

				$results = MainWP_Vulnerability_DB::instance()->get_all_results( false );

				if ( is_array( $results ) && count( $results ) > 0 ) {
					foreach ( $results as $result ) {
						if ( ! isset( $send_noti_sites[ $result['site_id'] ] ) ) {
							continue;
						}

						$total   = $result['wp_vulner_count'] + $result['plugin_vulner_count'] + $result['theme_vulner_count'];
						$website = $send_noti_sites[ $result['site_id'] ];
						$body   .= '<li>' . $website['name'] . ' - [ ' . $website['url'] . ' ] - [ ' . $total . ' ]</li>';
					}
				}

				$email = @apply_filters( 'mainwp_getnotificationemail', false );

				if ( false == $sent_email && ! empty( $email ) && $body != '' ) {
					$body = '<div>MainWP - Vulnerability check result details:</div>
					<div></div>
					<ul>' . $body . '</ul>
					<div></div>
					<div>Please visit your MainWP Dashboard to see details. (<a href="' . site_url() . '">' . site_url() . '</a>)</div>';

					MainWP_Vulnerability_Utility::log_debug( 'vulnerability check :: sending mail to ' . $email );

					wp_mail( $email, $title = 'MainWP - Vulnerability check', apply_filters( 'mainwp_getformatemail', $body, $email, $title ), array( 'From: "' . get_option( 'admin_email' ) . '" <' . get_option( 'admin_email' ) . '>', 'content-type: text/html' ) );
					update_option( 'mainwp_vulner_cron_recheck_sent_email', true );
				}
			}
		}
	}


	public static function get_enabled_service() {
		if ( null !== self::$enabled_service ) {
			return self::$enabled_service;
		}
		$service               = get_option( 'mainwp_vuln_checker_enabled_service', 'wpvulndb' );
		self::$enabled_service = $service;
		return $service;
	}

	public static function verify_nonce() {
		if ( ! isset( $_REQUEST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ), '_wpnonce_vulner' ) ) {
			die( wp_json_encode( array( 'error' => 'Invalid request' ) ) );
		}
	}

	public static function get_all_total_vulner( $service ) {
		$total = array();
		if ( 'nvd_nist' === $service ) {
			$total = MainWP_Vulnerability_Nvd_Checker::instance()->get_all_total_unignored_vulner();
		} else {
			$result = MainWP_Vulnerability_DB::instance()->get_total_vulner();
			if ( is_array( $result ) ) {
				$total = current( $result );
			}
		}
		return $total;
	}

	public function ajax_upgrade_plugintheme() {
		self::verify_nonce();
		do_action( 'mainwp_upgradePluginTheme' );
		die();
	}

	public function ajax_delete_plugin() {
		self::verify_nonce();
		do_action( 'mainwp_deletePlugin' );
		die();
	}

	public function ajax_delete_theme() {
		self::verify_nonce();
		do_action( 'mainwp_deleteTheme' );
		die();
	}

	public function ajax_vulner_result_recheck() {
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		self::verify_nonce();
		$siteid      = isset( $_POST['websiteId'] ) ? intval( $_POST['websiteId'] ) : null;
		$force       = isset( $_POST['force'] ) && ! empty( $_POST['force'] ) ? 1 : 0;
		$information = $this->do_vulner_result_recheck( $siteid, $force );
		// phpcs:enable WordPress.Security.NonceVerification.Missing
		die( wp_json_encode( $information ) );
	}

	public function do_vulner_result_recheck( $siteid, $force ) {
		if ( ! empty( $siteid ) ) {
			global $mainwp_VulnerCheckerExtensionActivator;

			$service = self::get_enabled_service();

			$post_data = array(
				'mwp_action' => 'vulner_recheck',
				'force'      => $force,
				'service'    => $service,
			);

			if ( 'wpvulndb' == $service ) {
				$post_data['wpvulndb_tk'] = MainWP_Vulnerability_Utility::instance()->get_compatible_access_token();
			}

			$local_timestamp = MainWP_Vulnerability_Utility::get_timestamp();
			$information     = apply_filters( 'mainwp_fetchurlauthed', $mainwp_VulnerCheckerExtensionActivator->get_child_file(), $mainwp_VulnerCheckerExtensionActivator->get_child_key(), $siteid, 'vulner_checker', $post_data );
			$information     = apply_filters( 'mainwp_vulner_before_save_result', $information, $siteid );

			if ( is_array( $information ) ) {
				MainWP_Vulnerability_Utility::log_debug( 'vulner check :: site id :: ' . $siteid . ' :: result :: ' . print_r( $information, true ) );
			}

			if ( is_array( $information ) && isset( $information['result'] ) ) {
				$current = MainWP_Vulnerability_DB::instance()->get_result_by( 'site_id', $siteid );

				if ( ! is_array( $current ) ) {
					$current = array();
				}

				$current_result = array();

				if ( $current && ! empty( $current['result'] ) ) {
					$current_result = json_decode( $current['result'], true ); // get to update later
					if ( ! is_array( $current_result ) ) {
						$current_result = array();
					}
				}

				$update = array(
					'site_id' => $siteid,
				);

				if ( isset( $information['result']['plugin'] ) && is_array( $information['result']['plugin'] ) ) {
					$plugin_count = 0;
					foreach ( $information['result']['plugin'] as $result ) {
						$result = json_decode( $result, true );
						if ( is_array( $result ) ) {
							$result = current( $result );
						}
						if ( is_array( $result ) && isset( $result['vulnerabilities'] ) && is_array( $result['vulnerabilities'] ) ) {
							if ( 'nvd_nist' == $service ) {
								$plugin_count += MainWP_Vulnerability_Nvd_Checker::get_vuln_count_issues( $result['vulnerabilities'], $siteid, 'plugin' );
							} else {
								$plugin_count += count( $result['vulnerabilities'] );
							}
						}
					}

					$update['plugin_vulner_count'] = $plugin_count;
					$current_result['plugin']      = $information['result']['plugin'];
				}

				if ( isset( $information['result']['theme'] ) && is_array( $information['result']['theme'] ) ) {
					$theme_count = 0;
					foreach ( $information['result']['theme'] as $result ) {
						$result = isset( $result['vulner_data'] ) ? $result['vulner_data'] : '';
						$result = json_decode( $result, true );
						if ( is_array( $result ) ) {
							$result = current( $result );
						}
						if ( is_array( $result ) && isset( $result['vulnerabilities'] ) && is_array( $result['vulnerabilities'] ) ) {
							if ( 'nvd_nist' == $service ) {
								$theme_count += MainWP_Vulnerability_Nvd_Checker::get_vuln_count_issues( $result['vulnerabilities'], $siteid, 'theme' );
							} else {
								$theme_count += count( $result['vulnerabilities'] );
							}
						}
					}

					$update['theme_vulner_count'] = $theme_count;
					$current_result['theme']      = $information['result']['theme'];
				}

				if ( isset( $information['result']['wp'] ) ) {
					$wp_count = 0;
					$result   = $information['result']['wp'];
					$result   = json_decode( $result, true );

					if ( is_array( $result ) ) {
						$result = current( $result );
						if ( is_array( $result ) && isset( $result['vulnerabilities'] ) && is_array( $result['vulnerabilities'] ) ) {
							if ( 'nvd_nist' == $service ) {
								$wp_count += MainWP_Vulnerability_Nvd_Checker::get_vuln_count_issues( $result['vulnerabilities'], $siteid, 'wp' );
							} else {
								$wp_count += count( $result['vulnerabilities'] );
							}
						}
						$update['wp_vulner_count'] = $wp_count;
						$current_result['wp']      = $information['result']['wp'];
					}
				}

				$update['result']     = wp_json_encode( $current_result );
				$update['last_check'] = $local_timestamp;

				MainWP_Vulnerability_DB::instance()->update_vulner_result( $update );

				$information['wp_count']     = isset( $update['wp_vulner_count'] ) ? $update['wp_vulner_count'] : ( isset( $current['wp_vulner_count'] ) ? $current['wp_vulner_count'] : 0 );
				$information['plugin_count'] = isset( $update['plugin_vulner_count'] ) ? $update['plugin_vulner_count'] : ( isset( $current['plugin_vulner_count'] ) ? $current['plugin_vulner_count'] : 0 );
				$information['theme_count']  = isset( $update['theme_vulner_count'] ) ? $update['theme_vulner_count'] : ( isset( $current['theme_vulner_count'] ) ? $current['theme_vulner_count'] : 0 );

				unset( $information['result'] );
			}
			return $information;
		}
		return false;
	}

	public static function ajax_load_sites() {
		self::verify_nonce();

		global $mainwp_VulnerCheckerExtensionActivator;

		$all_sites = apply_filters( 'mainwp_getsites', $mainwp_VulnerCheckerExtensionActivator->get_child_file(), $mainwp_VulnerCheckerExtensionActivator->get_child_key(), null );

		$error = '';

		if ( count( $all_sites ) == 0 ) {
			$error = __( 'No websites were found.' );
		}
		$html = '';

		if ( empty( $error ) ) {
			ob_start();
			?>

			<div class="ui relaxed divided list">
				<?php foreach ( $all_sites as $website ) : ?>
					<div class="item" action="" website-id="<?php echo esc_attr( $website['id'] ); ?>" status="queue">
						<div class="ui grid">
							<div class="two column row">
								<div class="column"><?php echo esc_html( $website['name'] ); ?></div>
								<div class="right aligned column status"><?php echo '<span data-tooltip="' . __( 'Queued', 'mainwp-vulnerability-checker-extension' ) . '" data-inverted="" data-position="left center"><i class="clock outline icon"></i></span>'; ?></div>
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<?php
			$html = ob_get_clean();
		}
		if ( ! empty( $error ) ) {
			die( wp_json_encode( array( 'error' => $error ) ) );
		}

		die( wp_json_encode( array( 'result' => $html ) ) );
	}

	public static function render_detail() {
		do_action( 'mainwp_pageheader_sites', 'Vulnerabilities' );
		$service = self::get_enabled_service();

		if ( 'wpvulndb' == $service ) {
			self::render_wpvulndb_detail_tabs();
		} else {
			MainWP_Vulnerability_Nvd_Checker::render_nvd_nist_detail_tabs();
		}
		do_action( 'mainwp_pagefooter_sites', 'Vulnerabilities' );
	}

	public static function render_wpvulndb_detail_tabs() {

		$site_id = 0;

		if ( isset( $_GET['id'] ) && ! empty( $_GET['id'] ) ) {
			$site_id = intval( $_GET['id'] );
		}

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

		$vulner_result = array();

		$result = MainWP_Vulnerability_DB::instance()->get_result_by( 'site_id', $site_id );

		if ( $result && ! empty( $result['result'] ) ) {
			$vulner_result = json_decode( $result['result'], true );
			if ( ! is_array( $vulner_result ) ) {
				$vulner_result = array();
			}
		}
		?>
		<div class="ui segment" id="mainwp-<?php echo esc_attr( $site_id ); ?>-vulnerabilities">
			<div id="mainwp-message-zone" class="ui message" style="display:none"></div>
			<h3 class="ui dividing header"><?php esc_html_e( 'WordPress', 'mainwp-vulnerability-checker-extension' ); ?></h3>
			<div class="ui segment">
				<?php

				$wp_results = array();
				if ( is_array( $vulner_result ) && isset( $vulner_result['wp'] ) ) {
					$wp_results = @json_decode( $vulner_result['wp'], true );
					if ( ! is_array( $wp_results ) ) {
						$wp_results = array();
					}
				}

				?>
				<table class="ui compact selectable table stackable">
					<thead>
						<tr>
							<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'affected-version' ) ); ?></th>
							<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'type' ) ); ?></th>
							<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'fixed-in-version' ) ); ?></th>
							<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'references' ) ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $wp_results as $wp_vuln_data ) : ?>
							<?php
							if ( ! empty( $wp_vuln_data['vulnerabilities'] ) ) {
								self::vulnche_list( $wp_vuln_data['vulnerabilities'] );
							} else {
								echo '<tr><td>' . esc_html__( 'No WordPress vulnerabilities detected.', 'mainwp-vulnerabilities-checker-extension' ) . '</tr></td>';
							}
							?>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
			<h3 class="ui dividing header"><?php esc_html_e( 'Plugins', 'mainwp-vulnerability-checker-extension' ); ?></h3>
			<div class="ui segment">
				<?php
				$plug_results = is_array( $vulner_result ) && isset( $vulner_result['plugin'] ) ? $vulner_result['plugin'] : array();

				if ( empty( $plug_results ) ) {
					?>
					<table class="ui selectable table stackable">
						<thead>
							<tr>
								<th><?php echo esc_html__( 'Plugin: ', 'mainwp-vulnerabilities-checker-extension' ); ?></th>
								<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'detected-version' ) ); ?></th>
								<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'latest-version' ) ); ?></th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td colspan="4"><?php echo esc_html__( 'No vulnerable plugins detected.', 'mainwp-vulnerabilities-checker-extension' ); ?></td>
							</tr>
						<tbody>
					</table>
					<?php
				} else {
					foreach ( $plug_results as $plug_slug => $plug_vuln ) :
						if ( ! empty( $plug_vuln ) ) :
							$show_actions = false;
							$plug_vuln    = json_decode( $plug_vuln, true );
							$plugin_name  = '';

							foreach ( $plug_vuln as $pl_name => $pl_vuln_data ) {
								$plugin_name = esc_html( $pl_name );
								if ( isset( $pl_vuln_data['detected_version'] ) ) {
									$pl_latest_version   = isset( $pl_vuln_data['latest_version'] ) ? $pl_vuln_data['latest_version'] : '';
									$pl_detected_version = isset( $pl_vuln_data['detected_version'] ) ? $pl_vuln_data['detected_version'] : '';
								} else {
									$pl_latest_version   = isset( $pl_vuln_data['latest_version'] ) ? $pl_vuln_data['latest_version'] : '';
									$pl_detected_version = isset( $pl_vuln_data['last_updated'] ) ? $pl_vuln_data['last_updated'] : '';
								}
								?>
								<table class="ui selectable table stackable">
									<thead>
										<tr>
											<th id="plugin"><?php echo esc_html__( 'Plugin: ', 'mainwp-vulnerabilities-checker-extension' ) . esc_html( $plugin_name ); ?></th>
											<th id="detected-version"><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'detected-version' ) ) . esc_html( $pl_detected_version ); ?></th>
											<th id="latest-version"><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'latest-version' ) ) . esc_html( $pl_latest_version ); ?></th>
											<th id="action"></th>
										</tr>
									</thead>
									<tbody>
										<tr class="active">
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'affected-version' ) ); ?></td>
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'type' ) ); ?></td>
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'fixed-in-version' ) ); ?></td>
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'references' ) ); ?></td>
										</tr>
										<?php
										if ( ! empty( $pl_vuln_data['vulnerabilities'] ) ) :
											$show_fix     = self::vulnche_list( $pl_vuln_data['vulnerabilities'] );
											$show_actions = true;
										endif;
										?>
									<tbody>
										<?php if ( $show_actions ) : ?>
									<tfoot class="full-width">
										<tr class="vulner-detail-actions" action-type="plugin" slug="<?php echo esc_html( $plug_slug ); ?>" website-id="<?php echo intval( $site_id ); ?>">
											<th colspan="4" scope="">
												<?php if ( $show_fix ) : ?>
													<a href="#" what="update" class="ui green right floated button vulner-detail-action-btn">
														<?php printf( esc_html__( 'Update %', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $plugin_name ) ); ?>
													</a>
												<?php endif; ?>
												<a href="#" what="delete" class="ui green basic button vulner-detail-action-btn">
													<?php printf( esc_html__( 'Delete %', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $plugin_name ) ); ?>
												</a>
											</th>
										</tr>
									</tfoot>
								<?php endif; ?>
								</table>
							<?php } ?>
						<?php else : ?>
							<div><?php echo esc_html( $plug_slug ); ?> <?php echo esc_html__( ' is not in the database.', 'mainwp-vulnerabilities-checker-extension' ); ?></div>
						<?php endif; ?>
						<?php
					endforeach;
				}
				?>
			</div>
			<h3 class="ui dividing header"><?php esc_html_e( 'Themes', 'mainwp-vulnerability-checker-extension' ); ?></h3>
			<div class="ui segment">
				<?php
				$th_results = is_array( $vulner_result ) && isset( $vulner_result['theme'] ) ? $vulner_result['theme'] : array();

				if ( empty( $th_results ) ) {
					?>
					<table class="ui selectable table stackable">
						<thead>
							<tr>
								<th><?php echo esc_html__( 'Theme: ', 'mainwp-vulnerabilities-checker-extension' ); ?></th>
								<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'detected-version' ) ); ?></th>
								<th><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'latest-version' ) ); ?></th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td colspan="4"><?php echo esc_html__( 'No vulnerable themes detected.', 'mainwp-vulnerabilities-checker-extension' ); ?></td>
							</tr>
						<tbody>
					</table>
					<?php
				} else {
					foreach ( $th_results as $th_slug => $data ) :
						$th_slug      = esc_html( $th_slug );
						$show_actions = false;
						$theme_vuln   = $data['vulner_data'];
						$theme_vuln   = json_decode( $theme_vuln, true );
						$theme_name   = '';
						if ( empty( $theme_vuln['parent'] ) ) :
							foreach ( $theme_vuln as $th_name => $th_vuln_data ) {
								$theme_name = esc_html( $th_name );

								if ( isset( $th_vuln_data['detected_version'] ) ) {
									$th_latest_version   = isset( $th_vuln_data['latest_version'] ) ? $th_vuln_data['latest_version'] : '';
									$th_detected_version = isset( $th_vuln_data['detected_version'] ) ? $th_vuln_data['detected_version'] : '';
								} else {
									$th_latest_version   = isset( $th_vuln_data['latest_version'] ) ? $th_vuln_data['latest_version'] : '';
									$th_detected_version = isset( $th_vuln_data['last_updated'] ) ? $th_vuln_data['last_updated'] : '';
								}

								?>
								<table class="ui selectable table stackable">
									<thead>
										<tr>
											<th id="theme">
												<?php printf( esc_html__( 'Theme: %s', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $theme_name ) ); ?>
											<th id="detected-version">
												<?php printf( esc_html__( 'Detected version: %s', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $th_detected_version ) ); ?>

											<th id="latest-version">
												<?php printf( esc_html__( 'Latest version: %s', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $th_latest_version ) ); ?>
											<th id="action"></th>
										</tr>
									</thead>
									<tbody>
										<tr class="active">
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'affected-version' ) ); ?></td>
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'type' ) ); ?></td>
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'fixed-in-version' ) ); ?></td>
											<td><?php echo esc_html( MainWP_Vulnerability_Utility::get_common_word( 'references' ) ); ?></td>
										</tr>
										<?php
										if ( ! empty( $th_vuln_data['vulnerabilities'] ) ) :
											$show_fix     = self::vulnche_list( $th_vuln_data['vulnerabilities'] );
											$show_actions = true;
										endif;
										?>
									<tbody>
										<?php if ( $show_actions ) : ?>
									<tfoot class="full-width">
										<tr class="vulner-detail-actions" action-type="theme" slug="<?php echo esc_attr( $th_slug ); ?>" theme-name="<?php echo esc_html( $data['name'] ); ?>" website-id="<?php echo intval( $site_id ); ?>">
											<th colspan="4" scope="">
												<?php if ( $show_fix ) : ?>
													<a href="#" what="update" class="ui green right floated button vulner-detail-action-btn">
														<?php printf( esc_html__( 'Update %', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $theme_name ) ); ?>
													</a>
												<?php endif; ?>
												<a href="#" what="delete" class="ui green basic button vulner-detail-action-btn">
													<?php printf( esc_html__( 'Delete %', 'mainwp-vulnerabilities-checker-extension' ), esc_html( $theme_name ) ); ?>
												</a>
											</th>
										</tr>
									</tfoot>
								<?php endif; ?>
								</table>
							<?php } ?>
						<?php else : ?>
							<div><?php echo esc_attr( $th_slug ); ?> <?php echo esc_html__( ' is not in the database.', 'mainwp-vulnerabilities-checker-extension' ); ?></div>
						<?php endif; ?>
						<?php
					endforeach;
				}
				?>
			</div>
		</div>
		<?php
	}

	public static function vulnche_list( $vulnerabilities ) {
		$show_fix = false;

		foreach ( $vulnerabilities as $vulnerability ) {
			if ( ! is_array( $vulnerability ) || ! isset( $vulnerability['title'] ) ) {
				continue;
			}
			echo '<tr>';
			if ( isset( $vulnerability['fixed_in'] ) && ! empty( $vulnerability['fixed_in'] ) ) {
				$show_fix = true;
			}
			echo '<td>' . esc_html( $vulnerability['title'] ) . '</td>'; // NOSONAR - tr break.
			echo '<td>' . esc_html( $vulnerability['vuln_type'] ) . '</td>'; // NOSONAR - tr break.
			echo '<td>' . esc_html( $vulnerability['fixed_in'] ) . '</td>'; // NOSONAR - tr break.
			echo '<td>';
			if ( isset( $vulnerability['references']['url'] ) ) {
				foreach ( $vulnerability['references']['url'] as $ref ) {
					echo '<a target="_blank" href="' . esc_url( $ref ) . '" rel="noopener noreferrer">' . esc_html( $ref ) . '</a><br />';
				}
			} else {
				echo 'None';
			}
			echo '</td>';
			echo '</tr>'; // NOSONAR - tr break.
		}

		return $show_fix;
	}

	public static function render() {
		self::render_tabs();
	}

	public static function render_tabs() {

		global $mainwp_VulnerCheckerExtensionActivator;

		$results      = MainWP_Vulnerability_DB::instance()->get_all_results();
		$list_ids     = array();
		$list_results = array();

		$selected_service = self::get_enabled_service();

		if ( 'nvd_nist' === $selected_service && is_array( $results ) ) {
			$new_results = array();
			foreach ( $results as $result ) {
				$result        = MainWP_Vulnerability_Nvd_Checker::instance()->recalculate_unignored_counting_numbers( $result );
				$new_results[] = $result;
			}
			$results = $new_results;
		}

		if ( is_array( $results ) ) {
			foreach ( $results as $result ) {
				$list_ids[]                         = $result['site_id'];
				$list_results[ $result['site_id'] ] = $result;
			}
		}

		$dbwebsites = apply_filters( 'mainwp_getdbsites', $mainwp_VulnerCheckerExtensionActivator->get_child_file(), $mainwp_VulnerCheckerExtensionActivator->get_child_key(), $list_ids, array() );

		$sites_results = array();

		$checking_existed_site_ids = array();

		foreach ( $dbwebsites as $website ) {
			if ( empty( $website ) ) {
				continue;
			}
			$checking_existed_site_ids[] = $website->id;
			$item                        = MainWP_Vulnerability_Utility::map_site( $website, array( 'id', 'name', 'url' ) );
			if ( isset( $list_results[ $item['id'] ] ) ) {
				$item['wp_vulner_count']     = $list_results[ $item['id'] ]['wp_vulner_count'];
				$item['plugin_vulner_count'] = $list_results[ $item['id'] ]['plugin_vulner_count'];
				$item['theme_vulner_count']  = $list_results[ $item['id'] ]['theme_vulner_count'];
				$item['last_check']          = $list_results[ $item['id'] ]['last_check'];
			} else {
				$item['wp_vulner_count']     = 0;
				$item['plugin_vulner_count'] = 0;
				$item['theme_vulner_count']  = 0;
				$item['last_check']          = 0;
			}
			$sites_results[] = $item;
		}
		unset( $dbwebsites );

		foreach ( $list_ids as $sid ) {
			if ( ! in_array( $sid, $checking_existed_site_ids ) ) {
				MainWP_Vulnerability_DB::instance()->delete_result_by( 'site_id', $sid );
			}
		}

		$selected_group = 0;

		if ( isset( $_POST['mainwp_vulner_groups_select'] ) ) {
			$selected_group = intval( $_POST['mainwp_vulner_groups_select'] );
		}

		$dbwebsites_result = MainWP_Vulnerability_List::instance()->get_websites_result( $sites_results, $selected_group );

		$save_to_sites = false;
		$current_tab   = '';

		if ( isset( $_POST['submit_vulner'] ) ) {
			if ( isset( $_POST['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), '_wpnonce_mainwp_vulner' ) ) {
				$save_to_sites = true;
			}
			$current_tab = 'settings';
		}

		if ( '' == $current_tab && isset( $_GET['tab'] ) ) {
			$current_tab = sanitize_text_field( wp_unslash( $_GET['tab'] ) );
		}

		?>
		<div class="ui labeled icon inverted menu mainwp-sub-submenu" id="mainwp-vulnerability-checker-menu">
			<a href="#" class="item <?php echo '' == $current_tab ? 'active' : ''; ?>" data-tab="mainwp-vulnerabilities-overview"><i class="dashboard icon"></i><?php echo esc_html__( 'Overview', 'mainwp-vulnerability-checker-extension' ); ?></a>
			<?php if ( 'nvd_nist' === $selected_service ) { ?>
				<a href="#" class="item <?php echo 'ignored' == $current_tab ? 'active' : ''; ?>" data-tab="mainwp-vulnerabilities-ignored"><i class="ban icon"></i><?php echo esc_html__( 'Ignored', 'mainwp-vulnerability-checker-extension' ); ?></a>
			<?php } ?>
			<a href="#" class="item <?php echo 'settings' == $current_tab ? 'active' : ''; ?>" data-tab="mainwp-vulnerabilities-settings"><i class="cog icon"></i><?php echo esc_html__( 'Settings', 'mainwp-vulnerability-checker-extension' ); ?></a>
		</div>
		<div class="ui tab <?php echo '' == $current_tab ? 'active' : ''; ?>" data-tab="mainwp-vulnerabilities-overview">
			<div class="mainwp-actions-bar">
				<?php MainWP_Vulnerability_List::gen_select_sites( $dbwebsites_result, $selected_group ); ?>
			</div>
			<div class="ui segment">
				<div id="mainwp-message-zone" class="ui message" style="display:none"></div>
				<?php MainWP_Vulnerability_List::render_dashboard_tab( $dbwebsites_result ); ?>
			</div>
		</div>
		<div class="ui tab <?php echo 'settings' == $current_tab ? 'active' : ''; ?>" data-tab="mainwp-vulnerabilities-settings">
			<div class="ui segment">
				<div id="mainwp-vulnerability-checker-settings">
					<?php if ( $save_to_sites ) : ?>
						<div class="ui green message"><i class="close icon"></i> <?php esc_html_e( 'Settings saved successfully.', 'mainwp-vulnerability-checker-extension' ); ?></div>
					<?php endif; ?>

					<?php self::render_settings_tab(); ?>
				</div>
				<div class="ui clearing hidden divider"></div>
			</div>
		</div>
		<?php if ( 'nvd_nist' === $selected_service ) { ?>
			<div class="ui tab <?php echo 'ignored' == $current_tab ? 'active' : ''; ?>" data-tab="mainwp-vulnerabilities-ignored">
				<div class="ui alt segment">
					<div id="mainwp-vulnerability-checker-settings">
						<?php MainWP_Vulnerability_Nvd_Checker::render_ignored_tab(); ?>
					</div>
					<div class="ui clearing hidden divider"></div>
				</div>
			</div>
			<?php
		}
	}

	public static function render_settings_tab() {

		$is_premium        = MainWP_Vulnerability_Checker_Extension::is_premium_account();
		$selected_service  = self::get_enabled_service();
		$settings_wpvulndb = MainWP_Vulnerability_Wpvulndb_Settings::instance()->get_options();
		$settings_nvd      = MainWP_Vulnerability_Nvd_Settings::instance()->get_options();
		$schedule_wpvulndb = isset( $settings_wpvulndb['schedule'] ) ? $settings_wpvulndb['schedule'] : '';
		$schedule_nvd      = isset( $settings_nvd['schedule'] ) ? $settings_nvd['schedule'] : '';
		$checked           = 'checked="true"';
		$schedule          = '';

		if ( 'wpvulndb' == $selected_service ) {
			$schedule = $schedule_wpvulndb;
		} else {
			$schedule = $schedule_nvd;
		}

		$local_timestamp = MainWP_Vulnerability_Utility::get_timestamp();

		$lastAutomaticCheck = '';
		$nextAutomaticCheck = '';

		if ( '' != $schedule ) {
			$lastAutomaticCheck = get_option( 'mainwp_vulner_cron_recheck_last', 0 );
			if ( $lastAutomaticCheck == 0 ) {
				$lastAutomaticCheck = _( 'Never' );
				$nextAutomaticCheck = _( 'Today' );
			} else {
				$nextAutomaticCheck = $lastAutomaticCheck + MainWP_Vulnerability_Utility::get_time_threshold( $schedule );
				$lastAutomaticCheck = MainWP_Vulnerability_Utility::formatTimestamp( MainWP_Vulnerability_Utility::get_timestamp( $lastAutomaticCheck ) );
				if ( $nextAutomaticCheck > $local_timestamp ) {
					$nextAutomaticCheck = MainWP_Vulnerability_Utility::formatTimestamp( MainWP_Vulnerability_Utility::get_timestamp( $nextAutomaticCheck ) );
				} else {
					$nextAutomaticCheck = '';
				}
			}
		}

		$supported_services = array(
			'wpvulndb' => __( 'WPScan API', 'mainwp-vulnerability-checker-extension' ),
		);

		if ( $is_premium ) {
			$supported_services['nvd_nist'] = __( 'MainWP NVD API', 'mainwp-vulnerability-checker-extension' );
		}
		?>
		<?php if ( 'nvd_nist' === $selected_service ) : ?>
			<div class="ui info message">
				<p><?php esc_html_e( 'MainWP NVD API brings you information about vulnerable plugins and themes on your Child Sites so you can act accordingly.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<p><?php esc_html_e( 'NVD Nist API Database can not be searched by plugin/theme slug (which would be unique for each item) and assure better accuracy, it can be searched by keyword only. This means that the API can return some false-positive results. For some vulnerabilities, the NVD Nist API lacks the "Fixed in version" info which can lead to extension showing vulnerabilities that already have been resolved. In order to remove false positives and get accurate results, you can use the "Ignore" function for the detected vulnerabilities if you recognize them as false-positive.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<p><?php esc_html_e( 'The NVD is the U.S. government repository of standards based vulnerability management data represented using the Security Content Automation Protocol (SCAP).', 'mainwp-vulnerability-checker-extension' ); ?> <a href="https://nvd.nist.gov/general" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Read more about NVD Nist API', 'mainwp-vulnerability-checker-extension' ); ?></a>.</p>
			</div>
		<?php endif; ?>
		<?php if ( 'wpvulndb' === $selected_service ) : ?>
			<div class="ui info message">
				<p><?php esc_html_e( 'WPScan Vulnerability Database API brings you information about vulnerable plugins and themes on your Child Sites so you can act accordingly.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<p><?php esc_html_e( 'WPScan API can be used free of charge, with an API request limit of 25 per day. To increase this limit, WPScan offers paid API usage that increases the daily request limit.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<p><?php esc_html_e( 'Please note that reaching the daily API request limit is very easy. If you have 5 sites with 3 plugins and a theme, you will hit the free 25 right away.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<ul>
					<li><?php esc_html_e( '5 WordPress Checks (1*5)', 'mainwp-vulnerability-checker-extension' ); ?></li>
					<li><?php esc_html_e( '5 Plugins checks (3*5)', 'mainwp-vulnerability-checker-extension' ); ?></li>
					<li><?php esc_html_e( '5 Theme checker (1*5)', 'mainwp-vulnerability-checker-extension' ); ?></li>
				</ul>
				<p><?php esc_html_e( 'Once the daily API Request limit is reached, the extension stops reporting, which can lead to misleading results.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<p><?php esc_html_e( 'If you need to make more than 250 API requests per day, you need to contact the WPScan team for pricing.', 'mainwp-vulnerability-checker-extension' ); ?></p>
				<p><?php esc_html_e( 'The WPScan Vulnerability Database is an online browsable version of WPScan’s data files which are used to detect known WordPress core, plugin and theme vulnerabilities. This database has been compiled by the WPScan Team and various other contributors since WPScan’s release. The development of the WPScan Vulnerability Database was funded by BruCON‘s 5by5 project.', 'mainwp-vulnerability-checker-extension' ); ?></p>
			</div>
		<?php endif; ?>
		<h3 class="ui dividing header">
			<?php esc_html_e( 'Vulnerability Checker Settings', 'mainwp-vulnerability-checker-extension' ); ?>
		</h3>
		<div class="ui form">
			<form method="post" action="">
				<?php
				if ( $is_premium ) {
					?>
					<div class="ui grid field">
						<label class="six wide column middle aligned" for=""><?php esc_html_e( 'Select service', 'mainwp-vulnerability-checker-extension' ); ?></label>
						<div class="ten wide column">
							<select name="vulner-select-service" id="vulner-select-service" class="ui dropdown">
								<?php foreach ( $supported_services as $key => $val ) : ?>
									<?php echo '<option class="' . ( $selected_service == $key ? 'active' : '' ) . '" value="' . esc_attr( $key ) . '" data-tab="' . esc_attr( $key ) . '"' . ( $selected_service == $key ? 'selected="selected"' : '' ) . '>' . esc_html( $val ) . '</option>'; ?>
								<?php endforeach; ?>
							</select>
						</div>
					</div>
				<?php } ?>
				<div id="mainwp-vulner-settings-tabs">
					<?php
					$wpvulndb_token = MainWP_Vulnerability_Utility::instance()->get_compatible_access_token();
					?>
					<div class="ui tab <?php echo 'wpvulndb' == $selected_service ? 'active' : ''; ?>" data-tab="wpvulndb">
						<div class="ui grid field">
							<label class="six wide column middle aligned" for=""><?php esc_html_e( 'WPScan API token', 'mainwp-vulnerability-checker-extension' ); ?></label>
							<div class="ten wide column">
								<input type="password" name="mainwp_vulnchecker_settings[wpvulndb][access_token]" id="mainwp_vulnchecker_settings[wpvulndb][access_token]" value="<?php echo esc_attr( $wpvulndb_token ); ?>">
								<br />
								<em><?php printf( esc_html__( 'To use the Vulnerability Checker you need to register account with %s WPScan %s and use the API token from your profile page.', 'mainwp-vulnerability-checker-extension' ), '<a href="https://wpscan.com/" target="_blank" rel="noopener noreferrer">', '</a>' ); ?></em>

							</div>
						</div>
						<div class="ui grid field">
							<label class="six wide column middle aligned" for=""><?php esc_html_e( 'Schedule automatic checks', 'mainwp-vulnerability-checker-extension' ); ?></label>
							<div class="ten wide column">
								<select name="mainwp_vulnchecker_settings[wpvulndb][schedule]" id="mainwp_vulnchecker_settings[wpvulndb][schedule]" class="ui dropdown">
									<option value="daily" <?php echo $schedule_wpvulndb == 'daily' ? 'selected' : ''; ?>><?php esc_html_e( 'Daily', 'mainwp-vulnerability-checker-extension' ); ?></option>
									<option value="weekly" <?php echo $schedule_wpvulndb == 'weekly' ? 'selected' : ''; ?>><?php esc_html_e( 'Weekly', 'mainwp-vulnerability-checker-extension' ); ?></option>
									<option value="monthly" <?php echo $schedule_wpvulndb == 'monthly' ? 'selected' : ''; ?>><?php esc_html_e( 'Monthly', 'mainwp-vulnerability-checker-extension' ); ?></option>
									<option value="disabled" <?php echo $schedule_wpvulndb == 'disabled' ? 'selected' : ''; ?>><?php esc_html_e( 'Disabled', 'mainwp-vulnerability-checker-extension' ); ?></option>
								</select>
								<div class="ui hidden divider"></div>
								<?php if ( $schedule_wpvulndb != '' ) { ?>
									<div class="ui label">
										<?php printf( esc_html__( 'Last run: %s', 'mainwp-vulnerability-checker-extension' ), esc_html( $lastAutomaticCheck ) ); ?>
									</div>
									<?php if ( $nextAutomaticCheck != '' ) { ?>
										<div class="ui label">
											<?php printf( esc_html__( 'Next run: %s', 'mainwp-vulnerability-checker-extension' ), esc_html( $nextAutomaticCheck ) ); ?>
										</div>
									<?php } ?>
								<?php } ?>
							</div>
						</div>
						<div class="ui grid field">
							<label class="six wide column middle aligned" for=""><?php esc_html_e( 'Send email notifications', 'mainwp-vulnerability-checker-extension' ); ?></label>
							<div class="ten wide column ui toggle checkbox">
								<input type="checkbox" name="mainwp_vulnchecker_settings[wpvulndb][noti_email]" value="1" <?php echo ( isset( $settings_wpvulndb['noti'] ) && ! empty( $settings_wpvulndb['noti'] ) ) ? esc_attr( $checked ) : ''; ?>>
							</div>
						</div>
						<div class="ui grid field">
							<label class="six wide column middle aligned" for=""><?php esc_html_e( 'Check sites when syncing', 'mainwp-vulnerability-checker-extension' ); ?></label>
							<div class="ten wide column ui toggle checkbox">
								<input type="checkbox" name="mainwp_vulnchecker_settings[wpvulndb][scan_sync]" <?php echo ( isset( $settings_wpvulndb['scan_sync'] ) && ! empty( $settings_wpvulndb['scan_sync'] ) ) ? esc_attr( $checked ) : ''; ?>>
							</div>
						</div>
					</div>

					<div class="ui tab <?php echo 'nvd_nist' == $selected_service ? 'active' : ''; ?>" data-tab="nvd_nist">
						<div class="ui grid field">
							<label class="six wide column middle aligned" for=""><?php esc_html_e( 'Schedule automatic checks', 'mainwp-vulnerability-checker-extension' ); ?></label>
							<div class="ten wide column">
								<select name="mainwp_vulnchecker_settings[nvd_nist][schedule]" id="mainwp_vulnchecker_settings[nvd_nist][schedule]" class="ui dropdown">
									<option value="daily" <?php echo $schedule_nvd == 'daily' ? 'selected' : ''; ?>><?php esc_html_e( 'Daily', 'mainwp-vulnerability-checker-extension' ); ?></option>
									<option value="weekly" <?php echo $schedule_nvd == 'weekly' ? 'selected' : ''; ?>><?php esc_html_e( 'Weekly', 'mainwp-vulnerability-checker-extension' ); ?></option>
									<option value="monthly" <?php echo $schedule_nvd == 'monthly' ? 'selected' : ''; ?>><?php esc_html_e( 'Monthly', 'mainwp-vulnerability-checker-extension' ); ?></option>
									<option value="disabled" <?php echo $schedule_nvd == 'disabled' ? 'selected' : ''; ?>><?php esc_html_e( 'Disabled', 'mainwp-vulnerability-checker-extension' ); ?></option>
								</select>
								<div class="ui hidden divider"></div>
								<?php if ( $schedule_nvd != '' ) { ?>
									<div class="ui label">
										<?php esc_html_e( 'Last run: ', 'mainwp-vulnerability-checker-extension' ); ?> <?php echo esc_html( $lastAutomaticCheck ); ?>
									</div>
									<?php if ( $nextAutomaticCheck != '' ) { ?>
										<div class="ui label"><?php esc_html_e( 'Next run: ', 'mainwp-vulnerability-checker-extension' ); ?>
											<?php echo esc_html( $nextAutomaticCheck ); ?>
										</div>
									<?php } ?>
								<?php } ?>
							</div>
						</div>
						<div class="ui grid field">
							<label class="six wide column middle aligned" for="">
								<?php esc_html_e( 'Send email notifications', 'mainwp-vulnerability-checker-extension' ); ?>
							</label>
							<div class="ten wide column ui toggle checkbox">
								<input type="checkbox" name="mainwp_vulnchecker_settings[nvd_nist][noti_email]" value="1" <?php echo ( isset( $settings_nvd['noti'] ) && ! empty( $settings_nvd['noti'] ) ) ? esc_attr( $checked ) : ''; ?>>
							</div>
						</div>
						<div class="ui grid field">
							<label class="six wide column middle aligned" for="">
								<?php esc_html_e( 'Check sites when syncing', 'mainwp-vulnerability-checker-extension' ); ?>
							</label>
							<div class="ten wide column ui toggle checkbox">
								<input type="checkbox" name="mainwp_vulnchecker_settings[nvd_nist][scan_sync]" <?php echo isset( $settings_nvd['scan_sync'] ) && ! empty( $settings_nvd['scan_sync'] ) ? esc_attr( $checked ) : ''; ?>>
							</div>
						</div>
					</div>
				</div>
				<div class="ui divider"></div>
				<input type="submit" class="ui green big button" name="submit_vulner" value="<?php esc_attr_e( 'Save Settings', 'mainwp-vulnerability-checker-extension' ); ?>" />
				<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( '_wpnonce_mainwp_vulner' ) ); ?>" />
			</form>
		</div>
		<script type="text/javascript">
			jQuery(function($) {
				$(document).on('change', '#vulner-select-service', function() {
					var tab = jQuery('#vulner-select-service').dropdown('get value');
					jQuery('#mainwp-vulner-settings-tabs .tab').tab('change tab', tab);
				})
			});
		</script>
		<?php
	}

	public function handle_post_settings() {

		if ( isset( $_POST['submit_vulner'] ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), '_wpnonce_mainwp_vulner' ) ) {

			$settings         = self::instance()->get_current_service_settings();
			$current_schedule = is_array( $settings ) && isset( $settings['schedule'] ) ? $settings['schedule'] : '';

			$enable_service = 'wpvulndb';
			if ( isset( $_POST['vulner-select-service'] ) ) {
				$enable_service = isset( $_POST['vulner-select-service'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['vulner-select-service'] ) ) ) : 'wpvulndb';
				update_option( 'mainwp_vuln_checker_enabled_service', $enable_service );
			}

			$options = array();
			if ( 'wpvulndb' == $enable_service ) {

				$file_key  = '';
				$encrypted = MainWP_Vulnerability_Wpvulndb_Settings::instance()->get_option( 'encrypted_data' );
				if ( ! empty( $encrypted ) && is_array( $encrypted ) && ! empty( $encrypted['file_key'] ) ) { // encrypted data.
					$file_key = $encrypted['file_key'];
				}

				$options['schedule']  = isset( $_POST['mainwp_vulnchecker_settings']['wpvulndb']['schedule'] ) ? sanitize_text_field( wp_unslash( $_POST['mainwp_vulnchecker_settings']['wpvulndb']['schedule'] ) ) : '';
				$options['noti']      = isset( $_POST['mainwp_vulnchecker_settings']['wpvulndb']['noti_email'] ) ? 1 : 0;
				$options['scan_sync'] = isset( $_POST['mainwp_vulnchecker_settings']['wpvulndb']['scan_sync'] ) ? 1 : 0;

				$encrypted_token = '';
				$access_token    = isset( $_POST['mainwp_vulnchecker_settings']['wpvulndb']['access_token'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['mainwp_vulnchecker_settings']['wpvulndb']['access_token'] ) ) ) : '';
				if ( empty( $access_token ) ) {
					if ( ! empty( $file_key ) ) {   // delete key file.
						do_action( 'mainwp_delete_key_file', $file_key );
					}
				} else {
					$encrypted_token = MainWP_Vulnerability_Utility::instance()->encrypt_api_keys( $access_token, false, $file_key );
				}

				$options['encrypted_data'] = ! empty( $encrypted_token ) ? $encrypted_token : '';

				MainWP_Vulnerability_Wpvulndb_Settings::instance()->update_options( $options );
			} elseif ( 'nvd_nist' == $enable_service ) {
				$options['schedule']  = isset( $_POST['mainwp_vulnchecker_settings']['nvd_nist']['schedule'] ) ? sanitize_text_field( wp_unslash( $_POST['mainwp_vulnchecker_settings']['nvd_nist']['schedule'] ) ) : '';
				$options['noti']      = isset( $_POST['mainwp_vulnchecker_settings']['nvd_nist']['noti_email'] ) ? 1 : 0;
				$options['scan_sync'] = isset( $_POST['mainwp_vulnchecker_settings']['nvd_nist']['scan_sync'] ) ? 1 : 0;
				MainWP_Vulnerability_Nvd_Settings::instance()->update_options( $options );
			}
			$new_schedule = isset( $options['schedule'] ) ? $options['schedule'] : '';
			if ( $new_schedule != $current_schedule ) {
				MainWP_Vulnerability_Utility::log_debug( 'updated schedule :: ' . $new_schedule );
				$sched = wp_next_scheduled( 'mainwp_cron_vulner_recheck' );
				if ( $sched ) {
					wp_unschedule_event( $sched, 'mainwp_cron_vulner_recheck' ); // will re-init.
				}
			}

			wp_safe_redirect( admin_url( 'admin.php?page=Extensions-Mainwp-Vulnerability-Checker-Extension&tab=settings&message=1' ) );
			exit();
		}
	}

	public static function get_current_service_settings() {
		$selected_service = self::get_enabled_service();
		if ( 'nvd_nist' === $selected_service ) {
			$settings = MainWP_Vulnerability_Nvd_Settings::instance()->get_options();
		} else {
			$settings = MainWP_Vulnerability_Wpvulndb_Settings::instance()->get_options();
		}
		return $settings;
	}
} // End of class
