<?php
/**
 * Temporary Login List Table
 *
 * Standard WordPress list table for temporary logins (like Posts/Pages).
 *
 * @package TemporaryLogin
 * @since 1.0.0
 */

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

if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

/**
 * Class Temporary_Login_List_Table
 */
class Temporary_Login_List_Table extends WP_List_Table {

	/**
	 * Module instance.
	 *
	 * @var object
	 */
	private $module;

	/**
	 * Current status filter.
	 *
	 * @var string
	 */
	private $status_filter;

	/**
	 * Constructor.
	 *
	 * @param object $module Temporary Login module instance.
	 * @param string $status Current status filter (all, active, expired, revoked).
	 */
	public function __construct( $module, $status = 'all' ) {
		$this->module        = $module;
		$this->status_filter = $status;
		parent::__construct(
			[
				'singular' => 'login',
				'plural'   => 'logins',
				'ajax'     => false,
			]
		);
	}

	/**
	 * Get table columns.
	 *
	 * @return array
	 */
	public function get_columns() {
		return [
			'cb'       => '<input type="checkbox" />',
			'user'     => __( 'User', 'wp-powersuite' ),
			'role'     => __( 'Role', 'wp-powersuite' ),
			'expires'  => __( 'Expires', 'wp-powersuite' ),
			'uses'     => __( 'Uses', 'wp-powersuite' ),
			'status'   => __( 'Status', 'wp-powersuite' ),
			'actions'  => __( 'Actions', 'wp-powersuite' ),
		];
	}

	/**
	 * Get sortable columns.
	 *
	 * @return array
	 */
	protected function get_sortable_columns() {
		return [
			'user'    => [ 'user_id', false ],
			'expires' => [ 'expires_at', false ],
			'status'  => [ 'is_revoked', false ],
		];
	}

	/**
	 * Get bulk actions.
	 *
	 * @return array
	 */
	protected function get_bulk_actions() {
		return [
			'delete'  => __( 'Delete', 'wp-powersuite' ),
			'revoke'  => __( 'Revoke', 'wp-powersuite' ),
			'enable'  => __( 'Enable', 'wp-powersuite' ),
			'expire'  => __( 'Expire now', 'wp-powersuite' ),
		];
	}

	/**
	 * Prepare items for display.
	 */
	public function prepare_items() {
		$status = $this->status_filter;
		$args   = [ 'status' => ( $status !== 'all' ? $status : null ) ];
		$logins = $this->module->getAllLogins( $args );
		$this->items = $logins;
		$this->_column_headers = [
			$this->get_columns(),
			[],
			$this->get_sortable_columns(),
		];
	}

	/**
	 * Default column output.
	 *
	 * @param object $item        Login object.
	 * @param string $column_name Column name.
	 * @return string
	 */
	protected function column_default( $item, $column_name ) {
		return '';
	}

	/**
	 * Checkbox column.
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="login[]" value="%d" />',
			(int) $item->id
		);
	}

	/**
	 * User column.
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_user( $item ) {
		$user = get_userdata( $item->user_id );
		$name = $user ? ( $user->display_name ?: $user->user_login ) : __( 'Unknown', 'wp-powersuite' );
		$email = $user && $user->user_email ? $user->user_email : __( 'No email', 'wp-powersuite' );
		return '<strong>' . esc_html( $name ) . '</strong><br><small>' . esc_html( $email ) . '</small>';
	}

	/**
	 * Role column.
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_role( $item ) {
		$wp_roles = wp_roles();
		$names    = $wp_roles->get_names();
		$role     = $item->role ?? 'subscriber';
		return esc_html( $names[ $role ] ?? $role );
	}

	/**
	 * Expires column.
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_expires( $item ) {
		$expires_at = isset( $item->expires_at ) ? (string) $item->expires_at : '';
		$is_expired = $expires_at !== '' && \TemporaryLogin\Module::isLoginExpired( $expires_at );
		$is_revoked = ! empty( $item->is_revoked );
		$out        = '';
		if ( $expires_at !== '' ) {
			$expires_ts = \TemporaryLogin\Module::expiresAtToTimestamp( $expires_at );
			$out       .= esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $expires_ts ) );
			if ( ! $is_expired && ! $is_revoked ) {
				$time_left = human_time_diff( current_time( 'timestamp' ), $expires_ts );
				$out      .= '<br><small>' . esc_html( sprintf( __( '%s left', 'wp-powersuite' ), $time_left ) ) . '</small>';
			}
		}
		return $out;
	}

	/**
	 * Uses column.
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_uses( $item ) {
		$used = $item->used_count ?? 0;
		$out  = (string) $used;
		if ( isset( $item->max_uses ) && $item->max_uses > 0 ) {
			$out .= ' / ' . (int) $item->max_uses;
		}
		if ( ! empty( $item->single_use ) ) {
			$out .= '<br><small>' . esc_html__( '(Single use)', 'wp-powersuite' ) . '</small>';
		}
		return $out;
	}

	/**
	 * Status column.
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_status( $item ) {
		$expires_at   = isset( $item->expires_at ) ? (string) $item->expires_at : '';
		$is_expired   = $expires_at !== '' && \TemporaryLogin\Module::isLoginExpired( $expires_at );
		$is_revoked   = ! empty( $item->is_revoked );
		$status_class = $is_revoked ? 'revoked' : ( $is_expired ? 'expired' : 'active' );
		$status_text  = $is_revoked ? __( 'Revoked', 'wp-powersuite' ) : ( $is_expired ? __( 'Expired', 'wp-powersuite' ) : __( 'Active', 'wp-powersuite' ) );
		$styles       = $status_class === 'active' ? 'background-color: #00a32a; color: #fff;' : ( $status_class === 'expired' ? 'background-color: #d63638; color: #fff;' : 'background-color: #646970; color: #fff;' );
		return '<span class="tl-status-badge tl-status-' . esc_attr( $status_class ) . '" style="display: inline-block; padding: 4px 8px; border-radius: 3px; font-size: 12px; font-weight: 600; ' . esc_attr( $styles ) . '">' . esc_html( $status_text ) . '</span>';
	}

	/**
	 * Actions column (row actions + buttons).
	 *
	 * @param object $item Login object.
	 * @return string
	 */
	protected function column_actions( $item ) {
		$expires_at = isset( $item->expires_at ) ? (string) $item->expires_at : '';
		$is_expired = $expires_at !== '' && \TemporaryLogin\Module::isLoginExpired( $expires_at );
		$is_revoked = ! empty( $item->is_revoked );
		$id = (int) $item->id;

		// Icon-only buttons: shared class .tl-action-icon + color modifier (styles in admin.css)
		$buttons = [];
		if ( ! $is_revoked && ! $is_expired ) {
			$buttons[] = '<button type="button" class="button button-small tl-copy-link" data-login-id="' . $id . '" title="' . esc_attr__( 'Copy login link (generates a new URL)', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'Copy login link', 'wp-powersuite' ) . '"><span class="dashicons dashicons-admin-links tl-action-icon tl-action-icon--blue"></span></button>';
			$buttons[] = '<button type="button" class="button button-small tl-edit-login" data-login-id="' . $id . '" title="' . esc_attr__( 'Edit', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'Edit', 'wp-powersuite' ) . '"><span class="dashicons dashicons-edit tl-action-icon tl-action-icon--blue"></span></button>';
			$buttons[] = '<button type="button" class="button button-small tl-revoke-login" data-login-id="' . $id . '" title="' . esc_attr__( 'Revoke', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'Revoke', 'wp-powersuite' ) . '"><span class="dashicons dashicons-lock tl-action-icon tl-action-icon--amber"></span></button>';
		} elseif ( $is_revoked ) {
			$buttons[] = '<button type="button" class="button button-small tl-enable-login" data-login-id="' . $id . '" title="' . esc_attr__( 'Enable', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'Enable', 'wp-powersuite' ) . '"><span class="dashicons dashicons-unlock tl-action-icon tl-action-icon--green"></span></button>';
			$buttons[] = '<button type="button" class="button button-small tl-edit-login" data-login-id="' . $id . '" title="' . esc_attr__( 'Edit', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'Edit', 'wp-powersuite' ) . '"><span class="dashicons dashicons-edit tl-action-icon tl-action-icon--blue"></span></button>';
		}
		$buttons[] = '<button type="button" class="button button-small tl-view-logs" data-login-id="' . $id . '" title="' . esc_attr__( 'View Logs', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'View Logs', 'wp-powersuite' ) . '"><span class="dashicons dashicons-list-view tl-action-icon tl-action-icon--gray"></span></button>';
		$buttons[] = '<button type="button" class="button button-small tl-delete-login" data-login-id="' . $id . '" title="' . esc_attr__( 'Delete', 'wp-powersuite' ) . '" aria-label="' . esc_attr__( 'Delete', 'wp-powersuite' ) . '"><span class="dashicons dashicons-trash tl-action-icon tl-action-icon--red"></span></button>';

		return '<div class="tl-actions">' . implode( '', $buttons ) . '</div>';
	}

	/**
	 * Message when no items.
	 */
	public function no_items() {
		esc_html_e( 'No temporary logins found.', 'wp-powersuite' );
	}

	/**
	 * Extra table nav (e.g. bulk actions) above the table.
	 *
	 * @param string $which 'top' or 'bottom'.
	 */
	protected function extra_tablenav( $which ) {
		// Optional: add filters above/below table.
	}
}
