<?php

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


	protected static $_instance = null;
	private static $order       = '';
	private static $orderby     = '';

	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public static function render_dashboard_tab( $websites ) {
        ?>
		<table class="ui unstackable single line table" id="mainwp-vulnerabilities-table" style="width:100%">
			<thead>
				<tr>
					<th class="no-sort collapsing check-column" scope=""><span class="ui checkbox"><input type="checkbox" id="cb-select-all-top"></span></th>
					<th scope=""><?php esc_html_e( 'Site', 'mainwp-vulnerability-checker-extension' ); ?></th>
					<th class="collapsing no-sort" scope=""><i class="sign in icon"></i></th>
					<th scope=""><?php esc_html_e( 'URL', 'mainwp-vulnerability-checker-extension' ); ?></th>
					<th scope=""><?php esc_html_e( 'Last check date', 'mainwp-vulnerability-checker-extension' ); ?></th>
					<th class="center aligned collapsing" scope=""><?php esc_html_e( 'WP Core', 'mainwp-vulnerability-checker-extension' ); ?></th>
					<th class="center aligned collapsing" scope=""><?php esc_html_e( 'Plugins', 'mainwp-vulnerability-checker-extension' ); ?></th>
					<th class="center aligned collapsing" scope=""><?php esc_html_e( 'Themes', 'mainwp-vulnerability-checker-extension' ); ?></th>
					<th class="collapsing no-sort right aligned" scope=""></th>
				</tr>
			</thead>
			<tbody id="mainwp-vulnerabilities-list">
				<?php
				if ( is_array( $websites ) && count( $websites ) > 0 ) {
					self::gen_data_table_row( $websites );
				} else {
					echo '<tr><td colspan="7">' . esc_html__( 'No reports generated yet.', 'mainwp-vulnerability-checker-extension' ) . '</td></tr>';
				}
				?>
			</tbody>
			<tfoot class="full-width">
				<th class="no-sort collapsing check-column" scope=""><span class="ui checkbox"><input type="checkbox" id="cb-select-all-bottom"></span></th>
				<th scope=""><?php esc_html_e( 'Site', 'mainwp-vulnerability-checker-extension' ); ?></th>
				<th class="collapsing no-sort"><i class="sign in icon"></i></th>
				<th scope=""><?php esc_html_e( 'URL', 'mainwp-vulnerability-checker-extension' ); ?></th>
				<th scope=""><?php esc_html_e( 'Last check date', 'mainwp-vulnerability-checker-extension' ); ?></th>
				<th scope=""><?php esc_html_e( 'WP Core', 'mainwp-vulnerability-checker-extension' ); ?></th>
				<th scope=""><?php esc_html_e( 'Plugins', 'mainwp-vulnerability-checker-extension' ); ?></th>
				<th scope=""><?php esc_html_e( 'Themes', 'mainwp-vulnerability-checker-extension' ); ?></th>
				<th class="collapsing no-sort" scope=""></th>
			</tfoot>
		</table>
		<script type="text/javascript">
			var responsive = true;
			if (jQuery(window).width() > 1140) {
				responsive = false;
			}

			jQuery(document).ready(function() {
				try {
					jQuery('#mainwp-vulnerabilities-table').DataTable({
						"stateSave": true,
						"stateDuration": 0, // forever
						"scrollX": false,
						"responsive": responsive,
						"colReorder": {
							columns: ":not(.check-column):not(:last-child)"
						},
						"lengthMenu": [
							[10, 25, 50, 100, -1],
							[10, 25, 50, 100, "All"]
						],
						"columnDefs": [{
							"targets": 'no-sort',
							"orderable": false
						}],
						"order": [
							[1, "asc"]
						],
						'select': {
							items: 'row',
							style: 'multi+shift',
							selector: 'tr>td:not(.not-selectable)'
						},
					}).on('select', function(e, dt, type, indexes) {
						if ('row' == type) {
							dt.rows(indexes)
								.nodes()
								.to$().find('td.check-column .ui.checkbox').checkbox('set checked');
						}
					}).on('deselect', function(e, dt, type, indexes) {
						if ('row' == type) {
							dt.rows(indexes)
								.nodes()
								.to$().find('td.check-column .ui.checkbox').checkbox('set unchecked');
						}
					}).on('columns-reordered', function(e, settings, details) {
						console.log('columns-reordered');
						setTimeout(() => {
							jQuery('#mainwp-vulnerabilities-table .ui.checkbox').checkbox();
							mainwp_datatable_fix_menu_overflow('#mainwp-vulnerabilities-table');
						}, 1000);
					});
				} catch (err) {
					// to fix js error.
				}
			});
		</script>
		<div class="ui modal" id="mainwp-vulnerability-checker-modal">
			<i class="close close-reload-modal icon"></i>
			<div class="header"><?php echo esc_html__( 'Vulnerability Checker', 'mainwp-vulnerabilities-checker-extension' ); ?></div>
			<div class="scrolling content"></div>
		</div>
		<?php
	}

	public static function gen_data_table_row( $websites ) {
		foreach ( $websites as $website ) {
			$website_id   = intval( $website['id'] );
			$recheck_link = '<a href="#" class="ui mini green button vulner_action_recheck" >' . __( 'Recheck', 'mainwp-vulnerability-checker-extension' ) . '</a>';
			$open_link    = '<a target="_blank" href="admin.php?page=SiteOpen&newWindow=yes&websiteid=' . $website_id . '&_opennonce=' . wp_create_nonce( 'mainwp-admin-nonce' ) . '" rel="noopener noreferrer">' . __( '<i class="sign in icon"></i>' ) . '</a>';

			$wp_count     = isset( $website['wp_vulner_count'] ) ? intval( $website['wp_vulner_count'] ) : 0;
			$plugin_count = isset( $website['plugin_vulner_count'] ) ? intval( $website['plugin_vulner_count'] ) : 0;
			$theme_count  = isset( $website['theme_vulner_count'] ) ? intval( $website['theme_vulner_count'] ) : 0;

			$last_date = $website['last_check'];

            ?>
			<tr class="child-site-vulnerabilities" website-id="<?php echo esc_attr( $website_id ); ?>">
				<td class="check-column"><span class="ui checkbox"><input type="checkbox" name="checked[]"></span></td>
				<td><a href="admin.php?page=managesites&dashboard=<?php echo esc_attr( $website_id ); ?>"><?php echo esc_html( stripslashes( $website['name'] ) ); ?></a></td>
				<td><?php echo $open_link; //phpcs:ignore -- NOSONAR ?></td>
				<td><a href="<?php echo esc_url( $website['url'] ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $website['url'] ); ?></a></td>
				<td>
					<?php
					if ( $last_date ) {
						echo esc_html( MainWP_Vulnerability_Utility::formatTimestamp( MainWP_Vulnerability_Utility::get_timestamp( $last_date ) ) );
					}
					?>
				</td>
				<td class="center aligned"><a href="admin.php?page=ManageSitesVulnerabilities&id=<?php echo esc_attr( $website_id ); ?>"><span class="ui <?php echo $wp_count > 0 ? 'red' : 'green'; ?> basic label"><?php echo $wp_count ; //phpcs:ignore -- NOSONAR ?></span></a></td>
				<td class="center aligned"><a href="admin.php?page=ManageSitesVulnerabilities&id=<?php echo esc_attr( $website_id ); ?>"><span class="ui <?php echo $plugin_count > 0 ? 'red' : 'green'; ?> basic label"><?php echo $plugin_count; //phpcs:ignore -- NOSONAR ?></span></a></td>
				<td class="center aligned"><a href="admin.php?page=ManageSitesVulnerabilities&id=<?php echo esc_attr( $website_id ); ?>"><span class="ui <?php echo $theme_count > 0 ? 'red' : 'green'; ?> basic label"><?php echo $theme_count;//phpcs:ignore -- NOSONAR  ?></span></a></td>
				<td class="right aligned not-selectable"><?php echo $recheck_link; //phpcs:ignore -- NOSONAR ?></td>
			</tr>
            <?php
		}
	}

	public function get_websites_result( $websites, $selected_group = 0 ) {
		$sites_results = array();

		if ( is_array( $websites ) && count( $websites ) ) {
			if ( empty( $selected_group ) ) {
				$sites_results = $websites;
			} else {
				global $mainwp_VulnerCheckerExtensionActivator;
				$group_websites = apply_filters( 'mainwp_getdbsites', $mainwp_VulnerCheckerExtensionActivator->get_child_file(), $mainwp_VulnerCheckerExtensionActivator->get_child_key(), array(), array( $selected_group ) );
				$site_ids       = array();

				foreach ( $group_websites as $site ) {
					$site_ids[] = $site->id;
				}

				foreach ( $websites as $site ) {
					if ( $site && in_array( $site['id'], $site_ids ) ) {
						$sites_results[] = $site;
					}
				}
			}
		}
		return $sites_results;
	}

	public static function gen_select_sites( $websites, $selected_group ) {

		global $mainwp_VulnerCheckerExtensionActivator;
		$groups = apply_filters( 'mainwp_getgroups', $mainwp_VulnerCheckerExtensionActivator->get_child_file(), $mainwp_VulnerCheckerExtensionActivator->get_child_key(), null );

		?>
		<div class="ui two columns grid">
			<div class="column ui mini form">
				<select id="vulner_results_action" class="ui dropdown">
					<option class="text"><?php _e( 'Select action', 'mainwp-vulnerability-checker-extension' ); ?></option>
					<option value="recheck"><?php _e( 'Recheck', 'mainwp-vulnerability-checker-extension' ); ?></option>
					<option value="force-recheck"><?php _e( 'Force recheck', 'mainwp-vulnerability-checker-extension' ); ?></option>
				</select>
				<input type="button" id="vulner_results_doaction_btn" name="" value="<?php _e( 'Apply' ); ?>" class="ui tiny basic button">
			</div>
			<div class="right aligned ui mini form column">
				<form method="post" action="admin.php?page=Extensions-Mainwp-Vulnerability-Checker-Extension" style="display:inline-block">
					<input type="hidden" name="mainwp_vulner_groups_select" value="<?php echo intval( $selected_group ); ?>" />
					<select name="mainwp_vulner_groups_select" id="mainwp_vulner_groups_select" class="ui dropdown">
						<option><?php _e( 'Select tag', 'mainwp-vulnerability-checker-extension' ); ?></option>
						<option data-value="0" value="0"><?php esc_html_e( 'All tags', 'mainwp-vulnerability-checker-extension' ); ?></option>
						<?php
						if ( is_array( $groups ) && count( $groups ) > 0 ) {
							foreach ( $groups as $group ) {
								$_select = '';
								if ( $selected_group == $group['id'] ) {
									$_select = 'selected ';
								}
								echo '<option value="' . $group['id'] . '" data-value="' . $group['id'] . '" ' . $_select . '>' . esc_html( $group['name'] ) . '</option>';
							}
						}
						?>
					</select>
					<input class="ui tiny basic button" type="button" name="vulner_btn_display" id="vulner_btn_display" value="<?php _e( 'Filter Sites', 'mainwp-vulnerability-checker-extension' ); ?>">
				</form>
				<input type="button" id="vulner_recheck_all_sites" class="ui green mini button" value="<?php esc_attr_e( 'Check All Sites', 'mainwp-vulnerability-checker-extension' ); ?>">
			</div>
		</div>
        <?php
		return;
	}
} // End of class
