<?php
/**
 * Registration Date Column Module
 *
 * @package RegistrationDateColumn
 * @since 1.0.0
 */

namespace RegistrationDateColumn;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'registration-date-column';
	private const MODULE_VERSION = '1.1.1';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Registration Date Column', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Adds a joined-on date to the Users list so you can spot new signups and sort accounts by when they arrived.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin' ];
	}

	protected function registerHooks(): void {
		if ( ! is_admin() ) {
			return;
		}

		add_filter( 'manage_users_columns', [ $this, 'addRegistrationDateColumn' ] );
		add_filter( 'manage_users_custom_column', [ $this, 'displayRegistrationDate' ], 10, 3 );
		add_filter( 'manage_users_sortable_columns', [ $this, 'makeRegistrationDateColumnSortable' ] );
		add_action( 'admin_print_styles-users.php', [ $this, 'addColumnStyle' ] );
	}

	public function addRegistrationDateColumn( array $columns ): array {
		$columns['wpps_registered'] = __( 'Registered', 'wp-powersuite' );
		return $columns;
	}

	public function displayRegistrationDate( string $output, string $column_name, int $user_id ): string {
		if ( 'wpps_registered' !== $column_name ) {
			return $output;
		}

		$user = get_userdata( $user_id );

		if ( ! $user || empty( $user->user_registered ) ) {
			return esc_html( '—' );
		}

		$user_registered_unix = strtotime( $user->user_registered );

		if ( false === $user_registered_unix || $user_registered_unix <= 0 ) {
			return esc_html( '—' );
		}

		$date_format = get_option( 'date_format', 'F j, Y' );
		$time_format = get_option( 'time_format', 'g:i a' );

		if ( function_exists( 'wp_date' ) ) {
			$output = wp_date( $date_format . ' ' . $time_format, $user_registered_unix );
		} else {
			$output = date_i18n( $date_format . ' ' . $time_format, $user_registered_unix );
		}

		return esc_html( $output );
	}

	public function makeRegistrationDateColumnSortable( array $sortable_columns ): array {
		$sortable_columns['wpps_registered'] = 'user_registered';
		return $sortable_columns;
	}

	public function addColumnStyle(): void {
		?>
		<style>
			.column-wpps_registered {
				min-width: 160px;
			}
		</style>
		<?php
	}
}
