<?php
/**
 * Admin controller for the Audit Log page and the CSV-export endpoint.
 *
 * @package KaizenCoders\MagicLink\Admin\AuditLog
 */

namespace KaizenCoders\MagicLink\Admin\AuditLog;

use KaizenCoders\MagicLink\AuditLog\Events;
use KaizenCoders\MagicLink\AuditLog\HealthCheck;
use KaizenCoders\MagicLink\AuditLog\Logger;

class Controller {

	const CAPABILITY = 'manage_options';

	public function init() {
		add_action( 'admin_menu', array( $this, 'register_menu' ), 20 );
		add_action( 'admin_init', array( $this, 'maybe_export_csv' ) );
	}

	/**
	 * Register the Audit Log + Health menu items under the Magic Link parent.
	 *
	 * @return void
	 */
	public function register_menu() {
		add_submenu_page(
			'magic-link',
			__( 'Audit Log', 'magic-link' ),
			__( 'Audit Log', 'magic-link' ),
			self::CAPABILITY,
			'magic-link-audit-log',
			array( $this, 'render_audit_log_page' )
		);
		add_submenu_page(
			'magic-link',
			__( 'Health', 'magic-link' ),
			__( 'Health', 'magic-link' ),
			self::CAPABILITY,
			'magic-link-health',
			array( $this, 'render_health_page' )
		);
	}

	/**
	 * Render the audit-log list.
	 *
	 * @return void
	 */
	public function render_audit_log_page() {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have permission to view this page.', 'magic-link' ) );
		}

		$args     = $this->args_from_request();
		$rows     = Logger::query( $args );
		$total    = Logger::count( $args );
		$per_page = max( 1, (int) $args['per_page'] );
		$page     = max( 1, (int) $args['page'] );
		$pages    = max( 1, (int) ceil( $total / $per_page ) );

		$is_pro = function_exists( 'KC_ML' ) && KC_ML()->is_pro();
		if ( $is_pro ) {
			$export_url = wp_nonce_url(
				add_query_arg(
					array_merge( $args, array( 'kc_ml_export' => 'csv' ) ),
					admin_url( 'admin.php?page=magic-link-audit-log' )
				),
				'kc_ml_audit_export'
			);
		}
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Magic Link Audit Log', 'magic-link' ); ?></h1>
			<form method="get">
				<input type="hidden" name="page" value="magic-link-audit-log" />
				<p class="search-box">
					<label class="screen-reader-text" for="kc-ml-search"><?php esc_html_e( 'Search', 'magic-link' ); ?></label>
					<input type="search" id="kc-ml-search" name="search" value="<?php echo esc_attr( $args['search'] ); ?>" />
					<select name="event_type">
						<option value=""><?php esc_html_e( 'All events', 'magic-link' ); ?></option>
						<?php foreach ( Events::all() as $event ) : ?>
							<option value="<?php echo esc_attr( $event ); ?>" <?php selected( $args['event_type'], $event ); ?>>
								<?php echo esc_html( Events::label( $event ) ); ?>
							</option>
						<?php endforeach; ?>
					</select>
					<input type="submit" class="button" value="<?php esc_attr_e( 'Filter', 'magic-link' ); ?>" />
					<?php if ( $is_pro ) : ?>
					<a class="button" href="<?php echo esc_url( $export_url ); ?>"><?php esc_html_e( 'Export CSV', 'magic-link' ); ?></a>
					<?php endif; ?>
				</p>
			</form>
			<table class="wp-list-table widefat striped">
				<thead><tr>
					<th><?php esc_html_e( 'When (UTC)', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'Event', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'User', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'Email', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'IP', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'Meta', 'magic-link' ); ?></th>
				</tr></thead>
				<tbody>
				<?php if ( empty( $rows ) ) : ?>
					<tr><td colspan="6"><?php esc_html_e( 'No audit events recorded yet.', 'magic-link' ); ?></td></tr>
				<?php else : ?>
					<?php foreach ( $rows as $row ) : ?>
					<tr>
						<td><?php echo esc_html( $row['created_at'] ); ?></td>
						<td><?php echo esc_html( Events::label( $row['event_type'] ) ); ?></td>
						<td><?php echo esc_html( $row['user_id'] ); ?></td>
						<td><?php echo esc_html( $row['email'] ); ?></td>
						<td><?php echo esc_html( $row['ip_address'] ); ?></td>
						<td><code><?php echo esc_html( $row['meta_json'] ); ?></code></td>
					</tr>
					<?php endforeach; ?>
				<?php endif; ?>
				</tbody>
			</table>
			<p><?php
				printf(
					/* translators: 1: current page, 2: total pages, 3: total rows */
					esc_html__( 'Page %1$d of %2$d (%3$d events).', 'magic-link' ),
					(int) $page,
					(int) $pages,
					(int) $total
				);
			?></p>
		</div>
		<?php
	}

	/**
	 * Render the health page.
	 *
	 * @return void
	 */
	public function render_health_page() {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have permission to view this page.', 'magic-link' ) );
		}
		$results = HealthCheck::run();
		$rollup  = HealthCheck::rollup( $results );
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Magic Link Health', 'magic-link' ); ?></h1>
			<p><strong><?php esc_html_e( 'Overall status:', 'magic-link' ); ?></strong> <?php echo esc_html( strtoupper( $rollup ) ); ?></p>
			<table class="wp-list-table widefat striped">
				<thead><tr>
					<th><?php esc_html_e( 'Check', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'Status', 'magic-link' ); ?></th>
					<th><?php esc_html_e( 'Detail', 'magic-link' ); ?></th>
				</tr></thead>
				<tbody>
					<?php foreach ( $results as $r ) : ?>
					<tr>
						<td><?php echo esc_html( $r['id'] ); ?></td>
						<td><?php echo esc_html( strtoupper( $r['status'] ) ); ?></td>
						<td><?php echo esc_html( $r['message'] ); ?></td>
					</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Streams a CSV download when ?kc_ml_export=csv is set on the audit log page.
	 *
	 * @return void
	 */
	public function maybe_export_csv() {
		if ( ! isset( $_GET['page'] ) || 'magic-link-audit-log' !== $_GET['page'] ) {
			return;
		}
		if ( ! isset( $_GET['kc_ml_export'] ) || 'csv' !== $_GET['kc_ml_export'] ) {
			return;
		}
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'Permission denied.', 'magic-link' ) );
		}
		if ( ! function_exists( 'KC_ML' ) || ! KC_ML()->is_pro() ) {
			wp_die( esc_html__( 'CSV export is a PRO feature.', 'magic-link' ) );
		}
		check_admin_referer( 'kc_ml_audit_export' );

		$args             = $this->args_from_request();
		$args['per_page'] = 10000;
		$args['page']     = 1;
		$csv              = Logger::to_csv( Logger::query( $args ) );

		nocache_headers();
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="kc-ml-audit-' . gmdate( 'Y-m-d-His' ) . '.csv"' );
		echo $csv; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Map current request to query args.
	 *
	 * @return array
	 */
	private function args_from_request() {
		return array(
			'event_type' => isset( $_GET['event_type'] ) ? sanitize_key( wp_unslash( $_GET['event_type'] ) ) : '',
			'user_id'    => isset( $_GET['user_id'] ) ? (int) $_GET['user_id'] : 0,
			'since'      => isset( $_GET['since'] ) ? sanitize_text_field( wp_unslash( $_GET['since'] ) ) : '',
			'until'      => isset( $_GET['until'] ) ? sanitize_text_field( wp_unslash( $_GET['until'] ) ) : '',
			'search'     => isset( $_GET['search'] ) ? sanitize_text_field( wp_unslash( $_GET['search'] ) ) : '',
			'per_page'   => isset( $_GET['per_page'] ) ? (int) $_GET['per_page'] : 50,
			'page'       => isset( $_GET['paged'] ) ? (int) $_GET['paged'] : 1,
		);
	}
}
