<?php
/**
 * TutorHelper Bookings diagnostics page.
 *
 * @package TutorHelper_Bookings
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Provides production-safe diagnostics and log management.
 */
final class TutorHelper_Diagnostics {

	/**
	 * Diagnostics page slug.
	 *
	 * @var string
	 */
	const PAGE_SLUG = 'tutorhelper-bookings-diagnostics';

	/**
	 * Register diagnostics hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action(
			'admin_menu',
			array( __CLASS__, 'register_menu' )
		);

		add_action(
			'admin_post_tutorhelper_download_system_report',
			array( __CLASS__, 'download_system_report' )
		);

		add_action(
			'admin_post_tutorhelper_download_plugin_log',
			array( __CLASS__, 'download_plugin_log' )
		);

		add_action(
			'admin_post_tutorhelper_clear_plugin_log',
			array( __CLASS__, 'clear_plugin_log' )
		);

		add_action(
			'admin_enqueue_scripts',
			array(
				__CLASS__,
				'enqueue_assets',
			)
		);
	}


	/**
	 * Load TutorHelper diagnostics styling.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 *
	 * @return void
	 */
	public static function enqueue_assets(
		$hook_suffix
	) {
		$expected_hook =
			'tools_page_'
			. self::PAGE_SLUG;

		if (
			$expected_hook
			!== $hook_suffix
		) {
			return;
		}

		$css_path =
			TUTORHELPER_BOOKINGS_PATH
			. 'assets/css/diagnostics.css';

		wp_enqueue_style(
			'tutorhelper-diagnostics',
			TUTORHELPER_BOOKINGS_URL
				. 'assets/css/diagnostics.css',
			array(),
			file_exists( $css_path )
				? (string) filemtime(
					$css_path
				)
				: TUTORHELPER_BOOKINGS_VERSION
		);
	}

	/**
	 * Add the diagnostics page under Tools.
	 *
	 * @return void
	 */
	public static function register_menu() {
		add_management_page(
			__(
				'TutorHelper Diagnostics',
				'tutorhelper-bookings'
			),
			__(
				'TutorHelper Diagnostics',
				'tutorhelper-bookings'
			),
			'manage_options',
			self::PAGE_SLUG,
			array( __CLASS__, 'render_page' )
		);
	}

	/**
	 * Render the diagnostics page.
	 *
	 * @return void
	 */
	public static function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die(
				esc_html__(
					'You do not have permission to view TutorHelper diagnostics.',
					'tutorhelper-bookings'
				),
				esc_html__(
					'Permission denied',
					'tutorhelper-bookings'
				),
				array(
					'response' => 403,
				)
			);
		}

		$report =
			TutorHelper_System_Report::
				get_data();

		$readiness_checks =
			TutorHelper_System_Report::
				get_readiness_checks();

		$plain_text =
			TutorHelper_System_Report::
				get_plain_text();

		$log_entries =
			TutorHelper_Logger::
				get_recent_entries(
					100
				);

		?>
		<div
			class="
				wrap
				tutorhelper-diagnostics
			"
		>
			<h1>
				<?php
				echo esc_html__(
					'TutorHelper Diagnostics',
					'tutorhelper-bookings'
				);
				?>
			</h1>

			<p>
				<?php
				echo esc_html__(
					'Use this page to review TutorHelper Bookings system information and recent technical log entries.',
					'tutorhelper-bookings'
				);
				?>
			</p>

			<div class="notice notice-info inline">
				<p>
					<?php
					echo esc_html__(
						'Diagnostic information is not sent anywhere automatically. Review the report before sharing it with support.',
						'tutorhelper-bookings'
					);
					?>
				</p>
			</div>

			<?php self::render_notice(); ?>

			<?php
			self::render_readiness_summary(
				$readiness_checks
			);
			?>

			<details
				class="tutorhelper-diagnostics-details"
			>
				<summary
					class="tutorhelper-diagnostics-details__summary"
				>
					<span>
						<?php
						echo esc_html__(
							'Detailed system information',
							'tutorhelper-bookings'
						);
						?>
					</span>

					<small>
						<?php
						echo esc_html__(
							'Click to expand technical information for troubleshooting and support',
							'tutorhelper-bookings'
						);
						?>
					</small>
				</summary>

				<div
					class="tutorhelper-diagnostics-details__content"
				>
					<?php foreach ( $report as $section ) : ?>
						<?php
						self::render_report_section(
							$section
						);
						?>
					<?php endforeach; ?>
				</div>
			</details>

			<details
				class="tutorhelper-diagnostics-details"
			>
				<summary
					class="tutorhelper-diagnostics-details__summary"
				>
					<span>
						<?php
						echo esc_html__(
							'Support report and logs',
							'tutorhelper-bookings'
						);
						?>
					</span>

					<small>
						<?php
						echo esc_html__(
							'Click to expand information you may be asked to provide when troubleshooting TutorHelper',
							'tutorhelper-bookings'
						);
						?>
					</small>
				</summary>

				<div
					class="tutorhelper-diagnostics-details__content"
				>

					<h2>
						<?php
						echo esc_html__(
							'Copyable system report',
							'tutorhelper-bookings'
						);
						?>
					</h2>

					<p
						class="tutorhelper-diagnostics-help"
					>
						<?php
						echo esc_html__(
							'This report contains technical information about your TutorHelper installation. You can copy or download it if TutorHelper support asks you to provide a system report.',
							'tutorhelper-bookings'
						);
						?>
					</p>

					<textarea
						readonly
						rows="20"
						class="large-text code"
					><?php echo esc_textarea( $plain_text ); ?></textarea>
					

					<p>
						<a
							class="button"
							href="<?php echo esc_url( self::get_download_report_url() ); ?>"
						>
							<?php
							echo esc_html__(
								'Download system report',
								'tutorhelper-bookings'
							);
							?>
						</a>
					</p>

			

					<hr />

					<h2>
						<?php
						echo esc_html__(
							'Recent TutorHelper log entries',
							'tutorhelper-bookings'
						);
						?>
					</h2>

					<p
						class="tutorhelper-diagnostics-help"
					>
						<?php
						echo esc_html__(
							'TutorHelper records a limited technical log to help diagnose plugin problems. Review log contents before sharing them with support.',
							'tutorhelper-bookings'
						);
						?>
					</p>

					<?php self::render_log_entries( $log_entries ); ?>

					<p>
						<a
							class="button"
							href="<?php echo esc_url( self::get_download_log_url() ); ?>"
						>
							<?php
							echo esc_html__(
								'Download plugin log',
								'tutorhelper-bookings'
							);
							?>
						</a>
					</p>

					<form
						method="post"
						action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
					>
						<input
							type="hidden"
							name="action"
							value="tutorhelper_clear_plugin_log"
						/>

						<?php
						wp_nonce_field(
							'tutorhelper_clear_plugin_log'
						);
						?>

						<?php
						submit_button(
							__(
								'Clear plugin log',
								'tutorhelper-bookings'
							),
							'delete',
							'submit',
							false
						);
						?>
					</form>
				</div>
			</details>
		</div>
		<?php
	}


	/**
	 * Render the TutorHelper Core readiness summary.
	 *
	 * @param array $checks Readiness checks.
	 *
	 * @return void
	 */
	private static function render_readiness_summary(
		$checks
	) {
		$checks =
			is_array( $checks )
				? $checks
				: array();

		$problem_count =
			0;

		$attention_count =
			0;

		foreach ( $checks as $check ) {
			$status =
				isset(
					$check['status']
				)
					? sanitize_key(
						$check['status']
					)
					: 'attention';

			if ( 'problem' === $status ) {
				++$problem_count;
			} elseif (
				'attention' === $status
			) {
				++$attention_count;
			}
		}

		if ( $problem_count ) {
			$summary_status =
				'problem';

			$summary_heading =
				__(
					'TutorHelper needs attention',
					'tutorhelper-bookings'
				);

			$summary_message =
				sprintf(
					/* translators: %d: Number of readiness problems. */
					_n(
						'%d setup problem should be resolved before students use online booking.',
						'%d setup problems should be resolved before students use online booking.',
						$problem_count,
						'tutorhelper-bookings'
					),
					$problem_count
				);
		} elseif ( $attention_count ) {
			$summary_status =
				'attention';

			$summary_heading =
				__(
					'TutorHelper Core is ready',
					'tutorhelper-bookings'
				);

			$summary_message =
				__(
					'The essential booking setup is ready. A few optional recommendations are shown below.',
					'tutorhelper-bookings'
				);
		} else {
			$summary_status =
				'ready';

			$summary_heading =
				__(
					'TutorHelper Core is ready',
					'tutorhelper-bookings'
				);

			$summary_message =
				__(
					'The essential TutorHelper booking configuration passed all readiness checks.',
					'tutorhelper-bookings'
				);
		}

		?>
		<section
			class="
				tutorhelper-diagnostics-readiness
				tutorhelper-diagnostics-readiness--<?php
					echo esc_attr(
						$summary_status
					);
				?>
			"
		>
			<header
				class="tutorhelper-diagnostics-readiness__header"
			>
				<div
					class="tutorhelper-diagnostics-readiness__summary-icon"
					aria-hidden="true"
				>
					<?php
					if ( 'ready' === $summary_status ) {
						echo '✓';
					} elseif (
						'attention'
						=== $summary_status
					) {
						echo '!';
					} else {
						echo '×';
					}
					?>
				</div>

				<div>
					<h2>
						<?php
						echo esc_html(
							$summary_heading
						);
						?>
					</h2>

					<p>
						<?php
						echo esc_html(
							$summary_message
						);
						?>
					</p>
				</div>
			</header>

			<div
				class="tutorhelper-diagnostics-readiness__checks"
			>
				<?php foreach ( $checks as $check ) : ?>
					<?php
					$status =
						isset(
							$check['status']
						)
							? sanitize_key(
								$check['status']
							)
							: 'attention';

					$label =
						isset(
							$check['label']
						)
							? $check['label']
							: '';

					$message =
						isset(
							$check['message']
						)
							? $check['message']
							: '';

					$action_url =
						isset(
							$check[
								'action_url'
							]
						)
							? $check[
								'action_url'
							]
							: '';

					$action_label =
						isset(
							$check[
								'action_label'
							]
						)
							? $check[
								'action_label'
							]
							: '';
					?>

					<div
						class="
							tutorhelper-diagnostics-check
							tutorhelper-diagnostics-check--<?php
								echo esc_attr(
									$status
								);
							?>
						"
					>
						<span
							class="tutorhelper-diagnostics-check__icon"
							aria-hidden="true"
						>
							<?php
							if ( 'ready' === $status ) {
								echo '✓';
							} elseif (
								'attention'
								=== $status
							) {
								echo '!';
							} else {
								echo '×';
							}
							?>
						</span>

						<div
							class="tutorhelper-diagnostics-check__content"
						>
							<strong>
								<?php
								echo esc_html(
									$label
								);
								?>
							</strong>

							<p>
								<?php
								echo esc_html(
									$message
								);
								?>
							</p>
						</div>

						<?php
						if (
							'' !== $action_url
							&& ''
								!== $action_label
						) :
							?>
							<a
								class="
									button
									tutorhelper-hub-pill-button
								"
								href="<?php
									echo esc_url(
										$action_url
									);
								?>"
							>
								<?php
								echo esc_html(
									$action_label
								);
								?>
							</a>
						<?php endif; ?>
					</div>
				<?php endforeach; ?>
			</div>
		</section>
		<?php
	}



	/**
	 * Render one system report section.
	 *
	 * @param array $section Report section.
	 *
	 * @return void
	 */
	private static function render_report_section( $section ) {
		$label = isset( $section['label'] )
			? $section['label']
			: '';

		$items = isset( $section['items'] )
			&& is_array( $section['items'] )
			? $section['items']
			: array();

		?>
		<h3><?php echo esc_html( $label ); ?></h3>

		<table
			class="
				widefat
				striped
				tutorhelper-diagnostics-table
			"
		>
			<tbody>
				<?php foreach ( $items as $item_label => $value ) : ?>
					<tr>
						<th
							scope="row"
							class="tutorhelper-diagnostics-table__label"
						>
							<?php echo esc_html( $item_label ); ?>
						</th>
						<td>
							<?php echo esc_html( $value ); ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
	}

	/**
	 * Render recent plugin log entries.
	 *
	 * @param array $entries Log entries.
	 *
	 * @return void
	 */
	private static function render_log_entries( $entries ) {
		if ( empty( $entries ) ) {
			echo '<p>';
			echo esc_html__(
				'No TutorHelper log entries have been recorded.',
				'tutorhelper-bookings'
			);
			echo '</p>';

			return;
		}

		?>
		<table class="widefat striped">
			<thead>
				<tr>
					<th scope="col">
						<?php
						echo esc_html__(
							'UTC time',
							'tutorhelper-bookings'
						);
						?>
					</th>
					<th scope="col">
						<?php
						echo esc_html__(
							'Level',
							'tutorhelper-bookings'
						);
						?>
					</th>
					<th scope="col">
						<?php
						echo esc_html__(
							'Message',
							'tutorhelper-bookings'
						);
						?>
					</th>
					<th scope="col">
						<?php
						echo esc_html__(
							'Context',
							'tutorhelper-bookings'
						);
						?>
					</th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $entries as $entry ) : ?>
					<tr>
						<td>
							<?php
							echo esc_html(
								isset( $entry['timestamp'] )
									? $entry['timestamp']
									: ''
							);
							?>
						</td>
						<td>
							<?php
							echo esc_html(
								isset( $entry['level'] )
									? strtoupper(
										$entry['level']
									)
									: ''
							);
							?>
						</td>
						<td>
							<?php
							echo esc_html(
								isset( $entry['message'] )
									? $entry['message']
									: ''
							);
							?>
						</td>
						<td>
							<code>
								<?php
								echo esc_html(
									isset( $entry['context'] )
										? wp_json_encode(
											$entry['context']
										)
										: ''
								);
								?>
							</code>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
	}

	/**
	 * Download the system report.
	 *
	 * @return void
	 */
	public static function download_system_report() {
		self::verify_admin_request(
			'tutorhelper_download_system_report'
		);

		header( 'Content-Type: text/plain; charset=utf-8' );
		header(
			'Content-Disposition: attachment; filename="tutorhelper-system-report.txt"'
		);

		echo esc_html(
			TutorHelper_System_Report::get_plain_text()
		);
		
		exit;
	}

	/**
	 * Download the active plugin log.
	 *
	 * @return void
	 */
	public static function download_plugin_log() {
		self::verify_admin_request(
			'tutorhelper_download_plugin_log'
		);

		$contents =
			TutorHelper_Logger::get_log_contents();

		if ( '' === $contents ) {
			wp_die(
				esc_html__(
					'No readable TutorHelper log file was found.',
					'tutorhelper-bookings'
				)
			);
		}

		header(
			'Content-Type: text/plain; charset=utf-8'
		);

		header(
			'Content-Disposition: attachment; filename="tutorhelper-bookings.log"'
		);

		echo esc_html( $contents );
		exit;
	}

	/**
	 * Clear the active and rotated plugin logs.
	 *
	 * @return void
	 */
	public static function clear_plugin_log() {
		self::verify_admin_request(
			'tutorhelper_clear_plugin_log'
		);

		$cleared = TutorHelper_Logger::clear();

		self::redirect_with_notice(
			$cleared
				? 'log_cleared'
				: 'log_clear_failed'
		);
	}

	/**
	 * Verify an administrator action and nonce.
	 *
	 * @param string $nonce_action Nonce action.
	 *
	 * @return void
	 */
	private static function verify_admin_request( $nonce_action ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die(
				esc_html__(
					'You do not have permission to manage TutorHelper diagnostics.',
					'tutorhelper-bookings'
				),
				esc_html__(
					'Permission denied',
					'tutorhelper-bookings'
				),
				array(
					'response' => 403,
				)
			);
		}

		check_admin_referer( $nonce_action );
	}

	/**
	 * Return the system report download URL.
	 *
	 * @return string
	 */
	private static function get_download_report_url() {
		return wp_nonce_url(
			admin_url(
				'admin-post.php?action=tutorhelper_download_system_report'
			),
			'tutorhelper_download_system_report'
		);
	}

	/**
	 * Return the plugin log download URL.
	 *
	 * @return string
	 */
	private static function get_download_log_url() {
		return wp_nonce_url(
			admin_url(
				'admin-post.php?action=tutorhelper_download_plugin_log'
			),
			'tutorhelper_download_plugin_log'
		);
	}

	/**
	 * Redirect to the diagnostics page with a notice.
	 *
	 * @param string $notice Notice code.
	 *
	 * @return void
	 */
	private static function redirect_with_notice( $notice ) {
		wp_safe_redirect(
			add_query_arg(
				array(
					'page'               => self::PAGE_SLUG,
					'tutorhelper_notice' => sanitize_key(
						$notice
					),
				),
				admin_url( 'tools.php' )
			)
		);

		exit;
	}

	/**
	 * Render a diagnostics action notice.
	 *
	 * @return void
	 */
	private static function render_notice() {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only notice key used only to render feedback after a nonce-protected diagnostics action.
		if ( ! isset( $_GET['tutorhelper_notice'] ) ) {
			return;
		}

		$notice = sanitize_key(
			wp_unslash( $_GET['tutorhelper_notice'] )
		);
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		$notices = array(
			'log_cleared' => array(
				'class'   => 'notice notice-success inline',
				'message' => __(
					'The TutorHelper log was cleared.',
					'tutorhelper-bookings'
				),
			),
			'log_clear_failed' => array(
				'class'   => 'notice notice-error inline',
				'message' => __(
					'The TutorHelper log could not be cleared.',
					'tutorhelper-bookings'
				),
			),
		);

		if ( ! isset( $notices[ $notice ] ) ) {
			return;
		}

		echo '<div class="';
		echo esc_attr( $notices[ $notice ]['class'] );
		echo '"><p>';
		echo esc_html( $notices[ $notice ]['message'] );
		echo '</p></div>';
	}


	

}
