<?php
/**
 * AdminUI — Ghost Purge admin page.
 *
 * Under Users → Ghost Purge. Provides:
 *   - Role dropdown (administrator excluded)
 *   - Months input (default 12, range 1–120)
 *   - Reassign-to-user input (optional — preserves content)
 *   - Preview button (dry run, lists candidates)
 *   - Purge button (batched delete with progress bar)
 *
 * @package Platform\Helm\Modules\GhostPurge
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\GhostPurge;

use Platform\Helm\Core\Assets;
use Platform\Helm\Core\Ui;

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

final class AdminUI {

	public const PAGE_SLUG = 'platform-helm-ghost-purge';

	public function __construct( private Assets $assets ) {}

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

	public function register_menu(): void {
		if ( ! \Platform\Helm\Core\Authorization::is_master_admin() ) {
			return;
		}
		add_users_page(
			__( 'Ghost Purge', 'platform-helm' ),
			__( 'Ghost Purge', 'platform-helm' ),
			'delete_users',
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
	}

	public function maybe_enqueue( string $hook_suffix ): void {
		if ( false === strpos( $hook_suffix, self::PAGE_SLUG ) ) {
			return;
		}
		$this->assets->enqueue_ghost_purge( [
			'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
			'nonce'     => wp_create_nonce( AjaxController::NONCE_ACTION ),
			'batchSize' => GhostPurgeModule::BATCH_SIZE,
			'i18n'      => [
				'previewFirst'    => __( 'Run a preview first to confirm the user list.', 'platform-helm' ),
				'confirmPurge'    => __( 'This will permanently delete the listed users. Continue?', 'platform-helm' ),
				'starting'        => __( 'Starting…', 'platform-helm' ),
				'previewing'      => __( 'Loading preview…', 'platform-helm' ),
				'processing'      => __( 'Deleting users %1$d–%2$d of %3$d…', 'platform-helm' ),
				'doneTitle'       => __( 'Done', 'platform-helm' ),
				'doneSummary'     => __( 'Deleted %1$d users. %2$d failed.', 'platform-helm' ),
				'networkError'    => __( 'Network error. Please retry.', 'platform-helm' ),
				'noUsersFound'    => __( 'No users matched these criteria.', 'platform-helm' ),
				'previewCount'    => __( 'Found %d candidate user(s).', 'platform-helm' ),
				'previewCapNote'  => __( '(showing first 50; the rest will be processed too)', 'platform-helm' ),
			],
		] );
	}

	public function render(): void {
		\Platform\Helm\Core\Authorization::require_master_admin();
		$finder      = new UserFinder();
		$roles       = $finder->purgeable_roles();
		$current_uid = get_current_user_id();

		Ui::open_page(
			__( 'Ghost Purge', 'platform-helm' ),
			__( 'Bulk-delete users inactive for N months. Administrators are always excluded; reassign authorship first to preserve content.', 'platform-helm' )
		);

		Ui::notice(
			'<strong>' . esc_html__( 'Reminder:', 'platform-helm' ) . '</strong> ' . esc_html__( 'Always take a database backup before purging on production — user deletion is irreversible.', 'platform-helm' ),
			'warning'
		);

		Ui::card_open( __( 'Purge criteria', 'platform-helm' ), '', 'ti-user-x' );

		echo '<div style="display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px">';

		echo '<div class="field-group"><label class="field-label" for="platform-helm-gp-role">' . esc_html__( 'Role to purge', 'platform-helm' ) . '</label>';
		echo '<select id="platform-helm-gp-role" class="field-input">';
		foreach ( $roles as $slug => $name ) {
			echo '<option value="' . esc_attr( $slug ) . '">' . esc_html( translate_user_role( $name ) ) . '</option>';
		}
		echo '</select></div>';

		echo '<div class="field-group"><label class="field-label" for="platform-helm-gp-months">' . esc_html__( 'Inactive for at least (months)', 'platform-helm' ) . '</label>';
		echo '<input type="number" id="platform-helm-gp-months" class="field-input" min="1" max="120" value="' . esc_attr( (string) GhostPurgeModule::DEFAULT_MONTHS ) . '"></div>';

		echo '<div class="field-group"><label class="field-label" for="platform-helm-gp-reassign">' . esc_html__( 'Reassign content to (user ID)', 'platform-helm' ) . '</label>';
		echo '<input type="number" id="platform-helm-gp-reassign" class="field-input" min="0" value="' . esc_attr( (string) $current_uid ) . '"></div>';

		echo '</div>';

		echo '<p style="font-size:11px;color:var(--text-faint);margin-top:10px">' . esc_html__( 'Users whose last login (or registration, if they never logged in) is older than the threshold. Reassign defaults to you; set to 0 to delete their content too.', 'platform-helm' ) . '</p>';

		echo '<div style="display:flex;gap:10px;margin-top:16px">';
		echo '<button type="button" id="platform-helm-gp-preview-btn" class="btn btn-secondary"><i class="ti ti-eye" aria-hidden="true"></i> ' . esc_html__( '1. Preview candidates', 'platform-helm' ) . '</button>';
		echo '<button type="button" id="platform-helm-gp-purge-btn" class="btn btn-danger-ghost"><i class="ti ti-trash" aria-hidden="true"></i> ' . esc_html__( '2. Purge', 'platform-helm' ) . '</button>';
		echo '</div>';

		// Dynamic regions — IDs consumed by ghost-purge.js (do not rename).
		echo '<div id="platform-helm-gp-preview-results" style="margin-top:16px"></div>';
		echo '<div id="platform-helm-gp-progress-wrap" class="progress-card" style="display:none;margin-top:16px">';
		echo '<div class="progress-track"><div class="progress-fill" id="platform-helm-gp-progress-bar" style="width:0"></div></div>';
		echo '<p class="progress-meta" id="platform-helm-gp-progress-text"></p>';
		echo '</div>';
		echo '<div id="platform-helm-gp-purge-results" style="margin-top:16px"></div>';

		Ui::card_close();
		Ui::close_page();
	}
}
