<?php
/**
 * Activity Log Page.
 *
 * Read-only viewer under Helm → Activity Log: a paginated table of recent
 * events with an action filter and CSV export. Rendered in the Helm design
 * system. Gated by `manage_options`.
 *
 * @package Platform\Helm\Modules\Activity_Log
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Activity_Log;

use Platform\Helm\Core\Ui;

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

final class ActivityLogPage {

	public const PAGE_SLUG   = 'platform-helm-activity-log';
	public const PARENT_SLUG = 'platform-helm';
	private const CAPABILITY  = 'manage_options';
	private const PER_PAGE     = 50;

	public function __construct( private ActivityLogger $logger ) {}

	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_menu' ], 50 );
	}

	public function register_menu(): void {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			return;
		}
		add_submenu_page(
			self::PARENT_SLUG,
			__( 'Activity Log', 'platform-helm' ),
			__( 'Activity Log', 'platform-helm' ),
			self::CAPABILITY,
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
	}

	/**
	 * Per-action presentation: [ friendly label, badge tone, Tabler icon, area ].
	 * Derived from the stored action key — no synthetic data.
	 *
	 * @return array<string,array{0:string,1:string,2:string,3:string}>
	 */
	private function action_meta(): array {
		return [
			'login'              => [ __( 'Logged in', 'platform-helm' ),          'info',    'ti-login',      __( 'Auth', 'platform-helm' ) ],
			'logout'             => [ __( 'Logged out', 'platform-helm' ),         'neutral', 'ti-logout',     __( 'Auth', 'platform-helm' ) ],
			'post_published'     => [ __( 'Published', 'platform-helm' ),          'success', 'ti-file-check', __( 'Content', 'platform-helm' ) ],
			'post_updated'       => [ __( 'Updated', 'platform-helm' ),            'info',    'ti-edit',       __( 'Content', 'platform-helm' ) ],
			'post_trashed'       => [ __( 'Trashed', 'platform-helm' ),            'warning', 'ti-trash',      __( 'Content', 'platform-helm' ) ],
			'post_deleted'       => [ __( 'Deleted', 'platform-helm' ),            'danger',  'ti-trash-x',    __( 'Content', 'platform-helm' ) ],
			'role_changed'       => [ __( 'Role changed', 'platform-helm' ),       'warning', 'ti-shield',     __( 'Users', 'platform-helm' ) ],
			'user_registered'    => [ __( 'Registered', 'platform-helm' ),         'success', 'ti-user-plus',  __( 'Users', 'platform-helm' ) ],
			'link_inserted'      => [ __( 'Links applied', 'platform-helm' ),      'info',    'ti-link',       __( 'Link Architect', 'platform-helm' ) ],
			'link_restored'      => [ __( 'Links restored', 'platform-helm' ),     'info',    'ti-refresh',    __( 'Link Architect', 'platform-helm' ) ],
			'settings_changed'   => [ __( 'Settings saved', 'platform-helm' ),     'neutral', 'ti-settings',   __( 'Settings', 'platform-helm' ) ],
			'plugin_activated'   => [ __( 'Plugin activated', 'platform-helm' ),   'success', 'ti-plug',       __( 'Plugins', 'platform-helm' ) ],
			'plugin_deactivated' => [ __( 'Plugin deactivated', 'platform-helm' ), 'warning', 'ti-plug-off',   __( 'Plugins', 'platform-helm' ) ],
		];
	}

	public function render(): void {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'platform-helm' ) );
		}

		// phpcs:disable WordPress.Security.NonceVerification.Recommended
		$filter = isset( $_GET['action_filter'] ) ? sanitize_key( wp_unslash( (string) $_GET['action_filter'] ) ) : '';
		$paged  = isset( $_GET['paged'] ) ? max( 1, (int) $_GET['paged'] ) : 1;
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
		$offset = ( $paged - 1 ) * self::PER_PAGE;

		$rows  = $this->logger->recent( self::PER_PAGE, $offset, $filter );
		$total = $this->logger->count_all();
		$pages = (int) ceil( $total / self::PER_PAGE );
		$meta  = $this->action_meta();

		$actions = array_merge( [ '' ], array_keys( $meta ) );

		$retention = (int) ( get_option( 'platform_helm_settings', [] )['activity_retention_days'] ?? 0 );
		$subtitle  = __( 'A record of notable actions on your site — newest first.', 'platform-helm' );
		if ( $retention > 0 ) {
			/* translators: %d: number of days */
			$subtitle .= ' ' . sprintf( __( 'Auto-pruned after %d days.', 'platform-helm' ), $retention );
		}

		$export_action = '<a href="' . esc_url( ActivityMaintenance::export_url( $filter ) ) . '" class="btn btn-ghost"><i class="ti ti-download" aria-hidden="true"></i> ' . esc_html__( 'Export CSV', 'platform-helm' ) . '</a>';

		Ui::open_page( __( 'Activity Log', 'platform-helm' ), $subtitle, $export_action );

		echo '<div class="card">';

		// Filter bar — only the real, server-backed action filter.
		echo '<form method="get" class="filter-row">';
		echo '<input type="hidden" name="page" value="' . esc_attr( self::PAGE_SLUG ) . '">';
		echo '<select name="action_filter" onchange="this.form.submit()">';
		foreach ( $actions as $a ) {
			$label = '' === $a ? __( 'All actions', 'platform-helm' ) : ( $meta[ $a ][0] ?? $a );
			echo '<option value="' . esc_attr( $a ) . '" ' . selected( $filter, $a, false ) . '>' . esc_html( $label ) . '</option>';
		}
		echo '</select>';
		if ( '' !== $filter ) {
			echo '<a class="btn btn-ghost btn-sm" href="' . esc_url( admin_url( 'admin.php?page=' . self::PAGE_SLUG ) ) . '">' . esc_html__( 'Clear', 'platform-helm' ) . '</a>';
		}
		echo '<span class="filter-count">' . esc_html(
			sprintf( /* translators: %s: number of entries */ _n( '%s entry', '%s entries', $total, 'platform-helm' ), number_format_i18n( $total ) )
		) . '</span>';
		echo '</form>';

		// Table.
		echo '<div class="table-wrap"><table><thead><tr>';
		echo '<th>' . esc_html__( 'Date & Time', 'platform-helm' ) . '</th>';
		echo '<th>' . esc_html__( 'Action', 'platform-helm' ) . '</th>';
		echo '<th>' . esc_html__( 'Detail', 'platform-helm' ) . '</th>';
		echo '<th>' . esc_html__( 'User', 'platform-helm' ) . '</th>';
		echo '<th>' . esc_html__( 'Area', 'platform-helm' ) . '</th>';
		echo '</tr></thead><tbody>';

		if ( empty( $rows ) ) {
			echo '<tr><td colspan="5"><span class="text-faint">' . esc_html__( 'No activity recorded yet.', 'platform-helm' ) . '</span></td></tr>';
		} else {
			foreach ( $rows as $r ) {
				$ts   = strtotime( (string) $r['logged_at'] );
				$when = $ts
					? sprintf( /* translators: %s: time diff */ __( '%s ago', 'platform-helm' ), human_time_diff( $ts, time() ) )
					: (string) $r['logged_at'];
				$a  = (string) $r['action'];
				$m  = $meta[ $a ] ?? [ ucfirst( str_replace( '_', ' ', $a ) ), 'neutral', 'ti-point-filled', '' ];

				echo '<tr>';
				echo '<td style="white-space:nowrap;color:var(--text-muted);font-size:11px">' . esc_html( $when ) . '</td>';
				echo '<td><span class="badge badge-' . esc_attr( $m[1] ) . '"><i class="ti ' . esc_attr( $m[2] ) . '" aria-hidden="true"></i> ' . esc_html( $m[0] ) . '</span></td>';
				echo '<td>' . esc_html( (string) $r['description'] ) . '</td>';
				echo '<td style="font-size:11px;color:var(--text-secondary)">' . esc_html( (string) $r['user_name'] ) . '</td>';
				echo '<td>' . ( '' !== $m[3] ? '<span class="badge badge-neutral">' . esc_html( $m[3] ) . '</span>' : '—' ) . '</td>';
				echo '</tr>';
			}
		}
		echo '</tbody></table></div>';

		// Footer pagination.
		if ( $pages > 1 ) {
			$base = admin_url( 'admin.php' );
			$prev = $paged > 1 ? add_query_arg( [ 'page' => self::PAGE_SLUG, 'action_filter' => $filter, 'paged' => $paged - 1 ], $base ) : '';
			$next = $paged < $pages ? add_query_arg( [ 'page' => self::PAGE_SLUG, 'action_filter' => $filter, 'paged' => $paged + 1 ], $base ) : '';
			echo '<div style="padding:10px 16px;border-top:1px solid var(--border);display:flex;justify-content:space-between;align-items:center">';
			echo '<span class="text-faint">' . esc_html( sprintf( /* translators: 1: current page, 2: total pages */ __( 'Page %1$d of %2$d', 'platform-helm' ), $paged, $pages ) ) . '</span>';
			echo '<div style="display:flex;gap:8px">';
			if ( '' !== $prev ) {
				echo '<a class="btn btn-ghost btn-sm" href="' . esc_url( $prev ) . '">‹ ' . esc_html__( 'Prev', 'platform-helm' ) . '</a>';
			}
			if ( '' !== $next ) {
				echo '<a class="btn btn-ghost btn-sm" href="' . esc_url( $next ) . '">' . esc_html__( 'Next', 'platform-helm' ) . ' ›</a>';
			}
			echo '</div></div>';
		}

		echo '</div>';
		Ui::close_page();
	}
}
