<?php

declare( strict_types=1 );

namespace StrykeWP\Modules\Connector;

/**
 * Admin Settings UI for the Hub Connector module.
 *
 * Ported from StrykeHub_Admin (stryke-connector v1.0.0).
 * Adapted to render as a settings section within the STRYKE WP dashboard
 * rather than a standalone top-level admin page.
 *
 * Form submissions are handled via admin_init (PRG pattern).
 * The render_settings() method outputs the page content.
 *
 * @package StrykeWP\Modules\Connector
 */
class ConnectorAdmin {

	const CAPABILITY   = 'manage_options';
	const MENU_SLUG    = 'stryke-wp-connector';
	const NONCE_ACTION = 'stryke_hub_admin_action';

	public function __construct(
		private readonly Auth $auth,
	) {}

	// -----------------------------------------------------------------------
	// Hook Registration
	// -----------------------------------------------------------------------

	/**
	 * Registers admin_init hook for form submission handling.
	 * Called from ConnectorModule::boot_module() only in admin context.
	 *
	 * @return void
	 */
	public function register_hooks(): void {
		add_action( 'admin_init', array( $this, 'handle_form_submission' ) );
	}

	// -----------------------------------------------------------------------
	// Form Handling (POST-Redirect-GET)
	// -----------------------------------------------------------------------

	/**
	 * Processes key management form submissions before any output.
	 *
	 * @return void
	 */
	public function handle_form_submission(): void {

		if ( 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
			return;
		}

		// Only process when we are on our own settings page.
		$page = sanitize_key( $_GET['page'] ?? '' );
		if ( self::MENU_SLUG !== $page ) {
			return;
		}

		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), self::NONCE_ACTION ) ) {
			return;
		}

		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to perform this action.', 'stryke-wp' ), 403 );
		}

		$action = sanitize_key( $_POST['stryke_action'] ?? '' );

		if ( 'generate_key' === $action ) {
			$this->auth->generate_and_store_key();
			wp_safe_redirect(
				add_query_arg(
					array( 'page' => self::MENU_SLUG, 'stryke_msg' => 'key_generated' ),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}

		if ( 'revoke_key' === $action ) {
			$this->auth->revoke_key();
			wp_safe_redirect(
				add_query_arg(
					array( 'page' => self::MENU_SLUG, 'stryke_msg' => 'key_revoked' ),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}
	}

	// -----------------------------------------------------------------------
	// Settings Page Rendering
	// -----------------------------------------------------------------------

	/**
	 * Renders the Hub Connector settings content.
	 * Called by ConnectorModule::render_settings().
	 *
	 * @return void
	 */
	public function render_settings(): void {

		if ( ! current_user_can( self::CAPABILITY ) ) {
			return;
		}

		$has_key      = $this->auth->has_key();
		$raw_key_once = $this->auth->get_raw_key_once();
		$api_base     = esc_url( get_site_url() . '/wp-json/stryke/v1/' );

		$this->render_notices();
		?>

		<div class="stryke-connector-settings">

			<!-- === Module Intro === -->
			<p class="stryke-module-intro">
				<?php esc_html_e( 'Sicherer REST-API-Endpunkt für das STRYKE Hub Dashboard — Remote-Monitoring, Plugin-Management und System-Health in Echtzeit.', 'stryke-wp' ); ?>
			</p>

			<!-- === Connection Status === -->
			<div class="stryke-connector-card <?php echo $has_key ? 'stryke-connector-card--connected' : ''; ?>">
				<div class="stryke-connector-status <?php echo $has_key ? 'stryke-connector-status--active' : 'stryke-connector-status--inactive'; ?>">
					<span class="stryke-connector-status__dot"></span>
					<span class="stryke-connector-status__text">
						<?php
						echo $has_key
							? esc_html__( 'Verbunden — API-Schlüssel aktiv', 'stryke-wp' )
							: esc_html__( 'Nicht verbunden — Kein API-Schlüssel konfiguriert', 'stryke-wp' );
						?>
					</span>
				</div>

				<table class="stryke-info-table">
					<tr>
						<th><?php esc_html_e( 'API-Basis-URL', 'stryke-wp' ); ?></th>
						<td><code><?php echo esc_html( $api_base ); ?></code></td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Auth-Header', 'stryke-wp' ); ?></th>
						<td><code>X-STRYKE-API-KEY: &lt;key&gt;</code></td>
					</tr>
					<tr>
						<th><?php esc_html_e( 'Schlüsselspeicherung', 'stryke-wp' ); ?></th>
						<td><?php esc_html_e( 'SHA-256-Hash in wp_options (Klartext nie gespeichert)', 'stryke-wp' ); ?></td>
					</tr>
				</table>
			</div>

			<!-- === API Key Management === -->
			<?php if ( $has_key ) : ?>
				<details class="stryke-connector-card stryke-connector-key-details" <?php echo $raw_key_once ? 'open' : ''; ?>>
					<summary class="stryke-connector-key-summary">
						<span class="stryke-connector-key-summary__arrow"></span>
						<span class="dashicons dashicons-admin-network" aria-hidden="true"></span>
						<span><?php esc_html_e( 'API-Schlüssel Verwaltung', 'stryke-wp' ); ?></span>
						<span class="stryke-connector-key-hint"><?php esc_html_e( 'Nur bei Bedarf öffnen', 'stryke-wp' ); ?></span>
					</summary>
					<div class="stryke-connector-key-content">

						<?php if ( $raw_key_once ) : ?>
							<div class="stryke-key-banner">
								<p class="stryke-key-banner__headline">
									<span class="dashicons dashicons-warning" aria-hidden="true"></span>
									<?php esc_html_e( 'SICHERHEITSHINWEIS — Schlüssel jetzt kopieren!', 'stryke-wp' ); ?>
								</p>
								<p>
									<?php
									esc_html_e(
										'Dies ist die einzige Anzeige des API-Schlüssels im Klartext. '
										. 'Er wird nicht in der Datenbank gespeichert. '
										. 'Kopieren Sie ihn und speichern Sie ihn sicher im STRYKE Hub.',
										'stryke-wp'
									);
									?>
								</p>
								<div class="stryke-key-display">
									<code id="stryke-raw-key"><?php echo esc_html( $raw_key_once ); ?></code>
									<button
										type="button"
										class="stryke-btn stryke-btn--sm stryke-copy-btn"
										data-target="stryke-raw-key"
										data-copied-label="<?php esc_attr_e( 'Kopiert!', 'stryke-wp' ); ?>"
									>
										<?php esc_html_e( 'Kopieren', 'stryke-wp' ); ?>
									</button>
								</div>
								<p class="stryke-key-ttl">
									<span class="dashicons dashicons-clock" aria-hidden="true"></span>
									<?php esc_html_e( 'Diese Anzeige verschwindet in ', 'stryke-wp' ); ?>
									<span id="stryke-key-countdown"><?php echo esc_html( (string) Auth::TRANSIENT_TTL ); ?></span>
									<?php esc_html_e( ' Sekunden.', 'stryke-wp' ); ?>
								</p>
							</div>
						<?php endif; ?>

						<form method="post" action="">
							<?php wp_nonce_field( self::NONCE_ACTION ); ?>
							<input type="hidden" name="stryke_action" value="generate_key">
							<p>
								<button
									type="submit"
									class="stryke-btn stryke-btn--primary"
									onclick="return confirm('<?php echo esc_js( __( 'Das Regenerieren ungültigte den aktuellen Schlüssel sofort. Alle verbundenen STRYKE Hub-Instanzen verlieren den Zugriff bis zum Update. Fortfahren?', 'stryke-wp' ) ); ?>')"
								>
									<?php esc_html_e( 'API-Schlüssel regenerieren', 'stryke-wp' ); ?>
								</button>
							</p>
						</form>

						<hr class="stryke-connector-divider">

						<form method="post" action="">
							<?php wp_nonce_field( self::NONCE_ACTION ); ?>
							<input type="hidden" name="stryke_action" value="revoke_key">
							<p>
								<button
									type="submit"
									class="stryke-btn stryke-btn--danger"
									onclick="return confirm('<?php echo esc_js( __( 'Der Schlüssel wird sofort widerrufen und der API-Zugriff deaktiviert. Der aktuelle Schlüssel kann nicht wiederhergestellt werden. Fortfahren?', 'stryke-wp' ) ); ?>')"
								>
									<?php esc_html_e( 'API-Schlüssel widerrufen', 'stryke-wp' ); ?>
								</button>
							</p>
							<p class="stryke-text-muted">
								<?php esc_html_e( 'Nur verwenden, wenn Sie vermuten, dass der Schlüssel kompromittiert wurde.', 'stryke-wp' ); ?>
							</p>
						</form>
					</div>
				</details>
			<?php else : ?>
				<div class="stryke-connector-card">
					<h3 class="stryke-connector-section-title">
						<span class="dashicons dashicons-admin-network" aria-hidden="true"></span>
						<?php esc_html_e( 'API-Schlüssel Verwaltung', 'stryke-wp' ); ?>
					</h3>

					<?php if ( $raw_key_once ) : ?>
						<div class="stryke-key-banner">
							<p class="stryke-key-banner__headline">
								<span class="dashicons dashicons-warning" aria-hidden="true"></span>
								<?php esc_html_e( 'SICHERHEITSHINWEIS — Schlüssel jetzt kopieren!', 'stryke-wp' ); ?>
							</p>
							<p>
								<?php
								esc_html_e(
									'Dies ist die einzige Anzeige des API-Schlüssels im Klartext. '
									. 'Er wird nicht in der Datenbank gespeichert. '
									. 'Kopieren Sie ihn und speichern Sie ihn sicher im STRYKE Hub.',
									'stryke-wp'
								);
								?>
							</p>
							<div class="stryke-key-display">
								<code id="stryke-raw-key"><?php echo esc_html( $raw_key_once ); ?></code>
								<button
									type="button"
									class="stryke-btn stryke-btn--sm stryke-copy-btn"
									data-target="stryke-raw-key"
									data-copied-label="<?php esc_attr_e( 'Kopiert!', 'stryke-wp' ); ?>"
								>
									<?php esc_html_e( 'Kopieren', 'stryke-wp' ); ?>
								</button>
							</div>
							<p class="stryke-key-ttl">
								<span class="dashicons dashicons-clock" aria-hidden="true"></span>
								<?php esc_html_e( 'Diese Anzeige verschwindet in ', 'stryke-wp' ); ?>
								<span id="stryke-key-countdown"><?php echo esc_html( (string) Auth::TRANSIENT_TTL ); ?></span>
								<?php esc_html_e( ' Sekunden.', 'stryke-wp' ); ?>
							</p>
						</div>
					<?php endif; ?>

					<p class="stryke-text-muted" style="margin-bottom: 16px;">
						<?php esc_html_e( 'Generieren Sie einen API-Schlüssel, um die Verbindung zum STRYKE Hub herzustellen.', 'stryke-wp' ); ?>
					</p>
					<form method="post" action="">
						<?php wp_nonce_field( self::NONCE_ACTION ); ?>
						<input type="hidden" name="stryke_action" value="generate_key">
						<p>
							<button type="submit" class="stryke-btn stryke-btn--primary">
								<?php esc_html_e( 'API-Schlüssel generieren', 'stryke-wp' ); ?>
							</button>
						</p>
					</form>
				</div>
			<?php endif; ?>

			<!-- === Endpoint Reference === -->
			<div class="stryke-connector-card">
				<h3 class="stryke-connector-section-title"><?php esc_html_e( 'Verfügbare Endpunkte', 'stryke-wp' ); ?></h3>
				<?php $this->render_endpoint_table( $api_base ); ?>
			</div>

		</div>

		<?php $this->render_connector_scripts(); ?>

		<?php
	}

	// -----------------------------------------------------------------------
	// Sub-renderers
	// -----------------------------------------------------------------------

	/**
	 * Outputs contextual notices based on query string message flags.
	 *
	 * @return void
	 */
	private function render_notices(): void {
		$msg = isset( $_GET['stryke_msg'] ) ? sanitize_key( $_GET['stryke_msg'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification

		if ( 'key_generated' === $msg ) {
			printf(
				'<div class="stryke-notice stryke-notice--success"><span class="dashicons dashicons-yes-alt" aria-hidden="true"></span> %s</div>',
				esc_html__( 'Neuer API-Schlüssel generiert. Kopieren Sie ihn unten — er wird nicht erneut angezeigt.', 'stryke-wp' )
			);
		}

		if ( 'key_revoked' === $msg ) {
			printf(
				'<div class="stryke-notice stryke-notice--warning"><span class="dashicons dashicons-warning" aria-hidden="true"></span> %s</div>',
				esc_html__( 'API-Schlüssel widerrufen. Der API-Zugriff ist bis zur Generierung eines neuen Schlüssels deaktiviert.', 'stryke-wp' )
			);
		}
	}

	/**
	 * Renders the endpoint reference table.
	 *
	 * @param string $api_base The base URL for REST endpoints.
	 * @return void
	 */
	private function render_endpoint_table( string $api_base ): void {
		$endpoints = array(
			// --- Infrastructure (9) ---
			array( 'GET',  '/status',              __( 'Site-Info, WP/PHP-Versionen, Update-Anzahl, Core-Integrität', 'stryke-wp' ) ),
			array( 'GET',  '/plugins',             __( 'Alle installierten Plugins mit Update-Status', 'stryke-wp' ) ),
			array( 'GET',  '/themes',              __( 'Alle installierten Themes mit Update-Status', 'stryke-wp' ) ),
			array( 'GET',  '/logs',                __( 'Audit-Trail der letzten API-Zugriffe', 'stryke-wp' ) ),
			array( 'POST', '/plugins/manage',      __( 'Fernverwaltung von Plugins: aktivieren, deaktivieren, updaten', 'stryke-wp' ) ),
			array( 'GET',  '/system/health',       __( 'Tiefer Server- und WP-Umgebungs-Diagnose-Scan', 'stryke-wp' ) ),
			array( 'POST', '/system/maintenance',  __( 'Wartungsaktionen: flush_cache, optimize_logs', 'stryke-wp' ) ),
			array( 'POST', '/backup/trigger',      __( 'Backup auslösen (asynchron via WP-Cron, lokaler Modus)', 'stryke-wp' ) ),
			array( 'GET',  '/backup/status',       __( 'Status und Details des letzten Backups', 'stryke-wp' ) ),
			// --- Posts & Pages (6) ---
			array( 'GET',    '/posts',                    __( 'Beiträge/Seiten auflisten mit Filter und Paginierung', 'stryke-wp' ) ),
			array( 'GET',    '/posts/{id}',               __( 'Einzelnen Beitrag/Seite abrufen', 'stryke-wp' ) ),
			array( 'POST',   '/posts',                    __( 'Neuen Beitrag oder Seite erstellen', 'stryke-wp' ) ),
			array( 'PUT',    '/posts/{id}',               __( 'Bestehenden Beitrag/Seite aktualisieren', 'stryke-wp' ) ),
			array( 'DELETE', '/posts/{id}',               __( 'Beitrag/Seite in Papierkorb verschieben oder löschen', 'stryke-wp' ) ),
			array( 'GET',    '/posts/{id}/revisions',     __( 'Revisionen eines Beitrags abrufen', 'stryke-wp' ) ),
			// --- Media (3) ---
			array( 'GET',    '/media',                    __( 'Medienbibliothek auflisten', 'stryke-wp' ) ),
			array( 'POST',   '/media',                    __( 'Datei hochladen (Base64)', 'stryke-wp' ) ),
			array( 'DELETE', '/media/{id}',               __( 'Medien-Anhang dauerhaft löschen', 'stryke-wp' ) ),
			// --- Terms / Taxonomies (4) ---
			array( 'GET',    '/terms',                    __( 'Kategorien, Tags oder andere Taxonomien auflisten', 'stryke-wp' ) ),
			array( 'POST',   '/terms',                    __( 'Neuen Term erstellen', 'stryke-wp' ) ),
			array( 'PUT',    '/terms/{id}',               __( 'Bestehenden Term aktualisieren', 'stryke-wp' ) ),
			array( 'DELETE', '/terms/{id}',               __( 'Term löschen', 'stryke-wp' ) ),
			// --- Comments (3) ---
			array( 'GET',    '/comments',                 __( 'Kommentare auflisten mit Filter und Paginierung', 'stryke-wp' ) ),
			array( 'POST',   '/comments/{id}/moderate',   __( 'Kommentar moderieren: genehmigen, Spam, Papierkorb', 'stryke-wp' ) ),
			array( 'DELETE', '/comments/{id}',            __( 'Kommentar löschen', 'stryke-wp' ) ),
			// --- Users (1, read-only) ---
			array( 'GET',    '/users',                    __( 'Benutzer auflisten (nur lesen)', 'stryke-wp' ) ),
			// --- Settings (2) ---
			array( 'GET',    '/settings',                 __( 'WordPress-Einstellungen abrufen (Whitelist)', 'stryke-wp' ) ),
			array( 'PUT',    '/settings',                 __( 'WordPress-Einstellungen aktualisieren (Whitelist)', 'stryke-wp' ) ),
		);
		?>
		<table class="stryke-endpoint-table">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Methode', 'stryke-wp' ); ?></th>
					<th><?php esc_html_e( 'Endpunkt', 'stryke-wp' ); ?></th>
					<th><?php esc_html_e( 'Beschreibung', 'stryke-wp' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $endpoints as [ $method, $path, $desc ] ) : ?>
					<tr>
						<td>
							<span class="stryke-method-badge stryke-method-badge--<?php echo esc_attr( strtolower( $method ) ); ?>">
								<?php echo esc_html( $method ); ?>
							</span>
						</td>
						<td><code><?php echo esc_html( $api_base . ltrim( $path, '/' ) ); ?></code></td>
						<td><?php echo esc_html( $desc ); ?></td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
	}

	/**
	 * Outputs the inline copy-to-clipboard script for the key display.
	 *
	 * @return void
	 */
	private function render_connector_scripts(): void {
		?>
		<script id="stryke-connector-js">
		(function () {
			'use strict';
			document.addEventListener( 'DOMContentLoaded', function () {
				// Copy button
				var btn = document.querySelector( '.stryke-copy-btn' );
				if ( btn ) {
					btn.addEventListener( 'click', function () {
						var targetId = btn.getAttribute( 'data-target' );
						var el = document.getElementById( targetId );
						if ( ! el ) return;
						navigator.clipboard.writeText( el.textContent.trim() ).then(
							function () {
								var original = btn.textContent;
								btn.textContent = btn.getAttribute( 'data-copied-label' ) || 'Kopiert!';
								btn.disabled = true;
								setTimeout( function () { btn.textContent = original; btn.disabled = false; }, 2500 );
							},
							function () {
								var range = document.createRange();
								range.selectNode( el );
								window.getSelection().removeAllRanges();
								window.getSelection().addRange( range );
							}
						);
					} );
				}

				// Countdown timer — auto-hides key banner when expired
				var countdownEl = document.getElementById( 'stryke-key-countdown' );
				var banner = document.querySelector( '.stryke-key-banner' );
				if ( countdownEl && banner ) {
					var remaining = parseInt( countdownEl.textContent, 10 ) || 60;
					var timer = setInterval( function () {
						remaining--;
						countdownEl.textContent = String( remaining );
						if ( remaining <= 0 ) {
							clearInterval( timer );
							banner.style.transition = 'opacity 0.4s ease';
							banner.style.opacity = '0';
							setTimeout( function () { banner.style.display = 'none'; }, 400 );
						}
					}, 1000 );
				}
			} );
		}());
		</script>
		<?php
	}
}
