<?php

declare( strict_types=1 );

namespace StrykeWP\Modules\WipMode;

use StrykeWP\Core\OptionManager;

/**
 * WIP Mode Admin Settings UI.
 *
 * Handles the settings form for the WIP Mode module inside the STRYKE WP dashboard.
 * Migrated from stryke-wip v1.6 (stryke_wip_settings_page()).
 *
 * Options are stored in the master plugin option system:
 *  - stryke_wp_module_wip_mode_active        (bool)
 *  - stryke_wp_module_wip_mode_allowed_pages (int[])
 *
 * Legacy options (stryke_wip_active, stryke_wip_allowed_pages_ids) are read as
 * a one-time migration fallback by WipController and migrated on first save.
 *
 * @package StrykeWP\Modules\WipMode
 */
class WipAdmin {

	const NONCE_ACTION = 'stryke_wip_save_settings';
	const NONCE_FIELD  = 'stryke_wip_nonce';
	const MENU_SLUG    = 'stryke-wp-wip_mode';

	public function __construct(
		private readonly OptionManager  $options,
		private readonly WipController  $controller,
	) {}

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

	/**
	 * Registers admin_init for form submission handling.
	 * Called from WipModeModule::boot_module() 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 the WIP settings form submission before any output.
	 *
	 * @return void
	 */
	public function handle_form_submission(): void {

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

		$page = sanitize_key( $_GET['page'] ?? '' );
		if ( self::MENU_SLUG !== $page ) {
			return;
		}

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

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Zugriff verweigert.', 'stryke-wp' ), 403 );
		}

		// Save active status.
		$is_active = isset( $_POST['wip_active'] ) && '1' === $_POST['wip_active'];
		$this->options->module_set( 'wip_mode', 'active', $is_active );

		// Save allowed page IDs.
		$allowed_pages = array();
		if ( isset( $_POST['wip_allowed_pages'] ) && is_array( $_POST['wip_allowed_pages'] ) ) {
			$allowed_pages = array_map( 'absint', $_POST['wip_allowed_pages'] );
			$allowed_pages = array_filter( $allowed_pages );
		}
		$this->options->module_set( 'wip_mode', 'allowed_pages', array_values( $allowed_pages ) );

		// Migrate legacy options on first save (write to new keys, keep legacy intact).

		wp_safe_redirect(
			add_query_arg(
				array( 'page' => self::MENU_SLUG, 'stryke_msg' => 'saved' ),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

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

	/**
	 * Renders the WIP Mode settings content inside the STRYKE WP dashboard.
	 * Called by WipModeModule::render_settings().
	 *
	 * @return void
	 */
	public function render_settings(): void {

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$is_active   = $this->controller->is_wip_active();
		$allowed_ids = $this->controller->get_allowed_page_ids();
		$all_pages   = get_pages( array( 'sort_column' => 'menu_order,post_title', 'hierarchical' => false ) );
		$msg         = isset( $_GET['stryke_msg'] ) ? sanitize_key( $_GET['stryke_msg'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification

		if ( 'saved' === $msg ) :
			?>
			<div class="stryke-notice stryke-notice--success">
				<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
				<?php esc_html_e( 'Einstellungen gespeichert.', 'stryke-wp' ); ?>
			</div>
		<?php endif; ?>

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

			<form method="post" action="">
				<?php wp_nonce_field( self::NONCE_ACTION, self::NONCE_FIELD ); ?>

				<!-- === WIP Mode Toggle === -->
				<div class="stryke-card">
					<h2><?php esc_html_e( 'WIP Modus', 'stryke-wp' ); ?></h2>

					<div class="stryke-field-row">
						<label class="stryke-toggle stryke-toggle--lg" for="wip_active_toggle">
							<input
								type="checkbox"
								id="wip_active_toggle"
								name="wip_active"
								value="1"
								class="stryke-toggle__input"
								<?php checked( $is_active ); ?>
							>
							<span class="stryke-toggle__slider" aria-hidden="true"></span>
							<span class="stryke-toggle__label">
								<?php echo $is_active
									? esc_html__( 'Aktiv — Wartungsseite wird angezeigt', 'stryke-wp' )
									: esc_html__( 'Inaktiv — Website ist öffentlich', 'stryke-wp' );
								?>
							</span>
						</label>
					</div>

					<p class="stryke-text-muted">
						<?php esc_html_e( 'Wenn aktiv, sehen nicht eingeloggte Besucher ohne Administratorrechte die Wartungsseite (HTTP 503). Administratoren haben immer Zugriff.', 'stryke-wp' ); ?>
					</p>
				</div>

				<!-- === Page Whitelist === -->
				<div class="stryke-card">
					<h2><?php esc_html_e( 'Seiten-Whitelist', 'stryke-wp' ); ?></h2>
					<p class="stryke-text-muted" style="margin-bottom: 12px;">
						<?php esc_html_e( 'Seiten, die im WIP-Modus öffentlich bleiben sollen (z.B. Impressum, Datenschutz). Mit STRG/CMD mehrere Seiten auswählen.', 'stryke-wp' ); ?>
					</p>

					<?php if ( ! empty( $all_pages ) ) : ?>
						<select
							name="wip_allowed_pages[]"
							id="wip_allowed_pages"
							multiple
							size="<?php echo min( 10, count( $all_pages ) ); ?>"
							style="width: 100%; max-width: 500px; background: #1a1a1a; color: #f0f0f0; border: 1px solid #363636; border-radius: 4px; padding: 8px;"
						>
							<?php foreach ( $all_pages as $page ) : ?>
								<option
									value="<?php echo esc_attr( $page->ID ); ?>"
									<?php echo in_array( $page->ID, $allowed_ids, true ) ? 'selected' : ''; ?>
								>
									<?php echo esc_html( $page->post_title ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					<?php else : ?>
						<p class="stryke-text-muted"><?php esc_html_e( 'Keine Seiten gefunden.', 'stryke-wp' ); ?></p>
					<?php endif; ?>
				</div>

				<!-- === Submit === -->
				<div class="stryke-form-actions">
					<button type="submit" class="stryke-btn stryke-btn--primary">
						<span class="dashicons dashicons-saved" aria-hidden="true"></span>
						<?php esc_html_e( 'Einstellungen speichern', 'stryke-wp' ); ?>
					</button>
				</div>

			</form>

			<!-- === Preview === -->
			<?php if ( $is_active ) : ?>
				<div class="stryke-card" style="margin-top: 16px;">
					<h2><?php esc_html_e( 'Status', 'stryke-wp' ); ?></h2>
					<div class="stryke-notice stryke-notice--warning">
						<span class="dashicons dashicons-hammer" aria-hidden="true"></span>
						<?php esc_html_e( 'WIP Modus ist aktiv. Nicht-Admin-Besucher sehen die Wartungsseite.', 'stryke-wp' ); ?>
					</div>
				</div>
			<?php endif; ?>

		</div>
		<?php
	}
}
