<?php
 /**
 * CV Monitor
 *
 * @package   CV_Monitor_Admin
 * @author    Gabriel Mariani <gabriel@coursevector.com>
 * @license   GPL-2.0+
 * @link      http://coursevector.com
 * @copyright 2019 CourseVector
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) die;

//if ( ! current_user_can( 'view_site_health_checks' ) ) { // only exists in v5+
if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( __( 'Sorry, you are not allowed to access the debug data.' ), '', 403 );
}

global $wpdb;

$row_count = 0;
$table_totals = array(0, 0, 0, array() );
$alternate = '';
$tables = $wpdb->get_col( "SHOW TABLES", 0 );
$table_count = count($tables);

// Generate table
$body_html = '';
foreach ( $tables as $table ) {
	$row_count++;

	// Get table information
	foreach ( $wpdb->get_results( "SHOW TABLE STATUS LIKE '{$table}';" ) as $table_data ) {
		// Check table
		$check_data = $wpdb->get_results( "CHECK TABLE {$table}" );
		$check_data_row = $check_data[0];

		// Non-OK table messages
		if ( 'OK' !== $check_data_row->Msg_text ) {
			$table_totals[3][] = array( $table_data->Name, $check_data_row->Msg_text );
		}

		//$alternate = ( $alternate == 'alternate' ) ? '' : 'alternate';
		$body_html .= sprintf(
			'<tr valign="top" class="%s">
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
			</tr>',
			$alternate,
			$table_data->Name,
			number_format( $table_data->Rows ),
			$table_data->Engine,
			$table_data->Create_time,
			$table_data->Collation,
			$this->plugin->parse_file_size( $table_data->Data_length + $table_data->Index_length ),
			$this->plugin->parse_file_size( $table_data->Data_free )
		);
		$table_totals[0] += $table_data->Rows;
		$table_totals[1] += $table_data->Data_length + $table_data->Index_length;
		$table_totals[2] += $table_data->Data_free;
	}
}
?>

<div class="wrap">
	<?php

	global $wp_version;
	if ( version_compare( $wp_version, '3.8', '<' ) ) {
		screen_icon();
		echo '<h2>' . esc_html( get_admin_page_title() ) . '</h2>';
	} else {
		echo '<h1>' . esc_html( get_admin_page_title() ) . '</h1>';
	}
	?>
	<div class="wrap-body">
	<?php
	///////////////////
	// Notifications //
	///////////////////
	// Display notice at the top. Use updated for yellow box, error for red

	global $wpdb;

	// Check/Repair/Optimize database
	if ( isset( $_POST["db-action"] ) && wp_verify_nonce( $_POST['db-nonce'], 'db' ) ) {
		$action = preg_replace( "/[^a-zA-Z]+/", "", $_POST["db-action"] );
		$table = preg_replace( "/[^0-9a-zA-Z_\$\s]+/", "", $_POST["table-name"] );
		$result = null;
		switch ($action) {
			case 'check' :
				$result = $this->main->site->check_db( $table );
				break;
			case 'repair' :
				$result = $this->main->site->repair_db( $table );
				break;
			case 'convert' :
				$result = $this->main->site->convert_db( $table );
				break;
			case 'optimize' :
				$action = 'optimiz'; // so we don't have two e's when 'ed' is appended
				$result = $this->main->site->optimize_db( $table );
				if ( $result ) update_option( 'cv_monitor_last_optimized', time() );
				break;
		}

		if ( $result ) {
			$alternate = '';
			$error_html = '';

			// If there were any issues, display them
			foreach( $result as $result_row) {
				$msg_text = $result_row->Msg_text;
				if ( $msg_text != 'Table is already up to date' && $msg_text != 'OK' && $msg_text != 'Table does not support optimize, doing recreate + analyze instead') {
					$alternate = ($alternate == 'alternate') ? '' : 'alternate';
					$error_html .= "<tr class='{$alternate}'><td>" . $result_row->Table . '</td><td>' . $result_row->Op . '</td><td>' . $result_row->Msg_type . '</td><td>' . $msg_text . '</td></tr>';
				}
			}

			if ( '' !== $error_html ) {
				echo '<div class="notice is-dismissible error">';
					echo '<p>' . __( 'There was a problem ' . $action . 'ing tables:<br>', $this->main->plugin_name ) . $wpdb->last_error . '</p>';
					echo '<p><table class="widefat">';
						echo '<thead><tr><th>Table</th><th>Op</th><th>Message Type</th><th>Message</th></tr></thead>';
						echo '<tbody>';
							echo $error_html;
						echo '</tbody>';
					echo '</table></p>';
				echo '</div>';
			} else {
				echo '<div class="notice is-dismissible updated"><p>';

				if ( function_exists("SimpleLogger") ) {
					$current_user = wp_get_current_user();
					SimpleLogger()->info("User '{$current_user->user_login}' " . $action . 'ed the database successfully.');
				}

				if ( $table ) {
					echo __( 'The table "' . $table . '" has been ' . $action . 'ed successfully.', $this->main->plugin_name );
				} else {
					echo __( 'Database has been ' . $action . 'ed successfully.', $this->main->plugin_name );
				}
				echo '</p></div>';
			}
		} else {
			echo '<div class="notice is-dismissible error"><p>';

			if ( function_exists("SimpleLogger") ) {
					$current_user = wp_get_current_user();
					SimpleLogger()->info("User '{$current_user->user_login}' had a problem " . $action . 'ing the database.');
				}

			if ($table) {
				echo __( 'There was a problem ' . $action . 'ing tables:<br>', $this->main->plugin_name ) . $wpdb->last_error;
			} else {
				echo __( 'There was a problem ' . $action . 'ing database:<br>', $this->main->plugin_name ) . $wpdb->last_error;
			}
			echo '</p></div>';
		}
	}

	?>

	<form method="post" id="cv-monitor-db">
		<div class="tablenav top">
			<div class="alignleft actions bulkactions">
				<?php wp_nonce_field( 'db', 'db-nonce', false ); ?>
				<input type="hidden" id="db-action"name="db-action" value="" />
				<input type="hidden" id="table-name" name="table-name" value="" />
				<p>Your database holds <strong><?php echo $table_count . ' ' . _n( 'table', 'tables', $table_count, $this->main->plugin_name ); ?></strong> and <strong><?php echo $this->plugin->parse_file_size( $table_totals[1] ); ?></strong> of data. It can be reduced by <strong><?php echo $this->plugin->parse_file_size( $table_totals[2] ); ?></strong>. Last optimized <?php echo '<abbr title="' . date("m/d/Y h:i:s A", get_option( 'cv_monitor_last_optimized' ) ) . '">' . $this->plugin->parse_timestamp( get_option( 'cv_monitor_last_optimized' ) ) . '</abbr>'; ?> ago, next optimization in <?php echo '<abbr title="' . date("m/d/Y h:i:s A", wp_next_scheduled( 'cv_optimize_db' ) ) . '">' . $this->plugin->parse_timestamp( wp_next_scheduled( 'cv_optimize_db' ) ) . '</abbr>'; ?>.</p>
				<p><?php submit_button( 'Optimize tables', 'button', 'optimize', false ); ?> <?php submit_button( 'Convert tables to InnoDB', 'button', 'convert', false ); ?></p>
			</div>

			<?php
			// Non-OK table messages
			if ( count( $table_totals[3] ) > 0 ) {
			?>
				<div class="notice error">
					<p>The database has <strong><?php echo count( $table_totals[3] ); ?></strong> tables that need to be repaired. <?php submit_button( 'Repair', 'button', 'repair', false ); ?></p>
					<p><table class="widefat striped-alt">
						<thead><tr><th>Table</th><th>Message</th></tr></thead>
						<tbody>
							<?php
							$alternate = '';
							foreach( $table_totals[3] as $checked_table ) {
								//$alternate = ($alternate == 'alternate') ? '' : 'alternate';
								echo "<tr class='{$alternate}'><td>" . $checked_table[0] . '</td><td>' . $checked_table[1] . '</td></tr>';
							}
							?>
						</tbody>
					</table></p>
				</div>
			<?php }	?>
			<br class="clear">
		</div>
		<table class="widefat db-table-rows striped-alt tablesorter">
			<thead>
				<tr valign="top">
					<th class=""><a href="#"><span>Table</span><span class="sorting-indicator"></span></a></th>
					<th class=""><a href="#"><span>Rows</span><span class="sorting-indicator"></span></a></th>
					<th class=""><a href="#"><span>Engine</span><span class="sorting-indicator"></span></a></th>
					<th class=""><a href="#"><span>Create Time</span><span class="sorting-indicator"></span></a></th>
					<th class=""><a href="#"><span>Collation</span><span class="sorting-indicator"></span></a></th>
					<th class=""><a href="#"><span>Size</span><span class="sorting-indicator"></span></a></th>
					<th class=""><a href="#"><span>Overhead</span><span class="sorting-indicator"></span></a></th>
				</tr>
			</thead>
			<tbody>
				<?php echo $body_html; ?>
			</tbody>
			<tfoot>
				<tr valign="top">
					<th>Totals</th>
					<th><?php echo number_format( $table_totals[0] ); ?> Rows</th>
					<th></th>
					<th></th>
					<th></th>
					<th><?php echo $this->plugin->parse_file_size( $table_totals[1] ); ?></th>
					<th><?php echo $this->plugin->parse_file_size( $table_totals[2] ); ?></th>
				</tr>
			</tfoot>
		</table>
	</form>

	</div>
</div> <!-- End Wrap -->