<?php
/**
 * Magic Login activity list table.
 *
 * @package MagicLogin
 */

namespace MagicLogin;

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

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

/**
 * Standard WordPress list table for magic login activity rows.
 */
class Activity_List_Table extends \WP_List_Table {

	private LinkRepository $repo;

	private string $status_filter;

	private string $search_query;

	public function __construct( LinkRepository $repo, string $status = 'all', string $search = '' ) {
		$this->repo           = $repo;
		$this->status_filter  = $status;
		$this->search_query   = $search;
		parent::__construct(
			[
				'singular' => 'ml_activity',
				'plural'   => 'ml_activities',
				'ajax'     => false,
			]
		);
	}

	public function get_columns(): array {
		return [
			'cb'       => '<input type="checkbox" />',
			'user'     => __( 'User', 'wp-powersuite' ),
			'email'    => __( 'Email', 'wp-powersuite' ),
			'created'  => __( 'Created', 'wp-powersuite' ),
			'used'     => __( 'Used', 'wp-powersuite' ),
			'expires'  => __( 'Expires', 'wp-powersuite' ),
			'ip'       => __( 'IP address', 'wp-powersuite' ),
			'status'   => __( 'Status', 'wp-powersuite' ),
		];
	}

	protected function get_sortable_columns(): array {
		return [
			'user'    => [ 'user', false ],
			'email'   => [ 'email', false ],
			'created' => [ 'created', true ],
			'used'    => [ 'used', false ],
			'expires' => [ 'expires', false ],
			'ip'      => [ 'ip', false ],
			'status'  => [ 'status', false ],
		];
	}

	protected function get_bulk_actions(): array {
		return [
			'delete' => __( 'Delete', 'wp-powersuite' ),
			'revoke' => __( 'Revoke pending', 'wp-powersuite' ),
		];
	}

	public function prepare_items(): void {
		$per_page     = $this->get_items_per_page( 'wpps_ml_activity_per_page', 20 );
		$current_page = max( 1, $this->get_pagenum() );
		$orderby      = isset( $_REQUEST['orderby'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['orderby'] ) ) : 'created';
		$order        = ( isset( $_REQUEST['order'] ) && strtolower( wp_unslash( (string) $_REQUEST['order'] ) ) === 'asc' ) ? 'ASC' : 'DESC';

		$query_args = [
			'status'   => $this->status_filter,
			'search'   => $this->search_query,
			'orderby'  => $orderby,
			'order'    => $order,
			'per_page' => $per_page,
			'offset'   => ( $current_page - 1 ) * $per_page,
		];

		$total_items = $this->repo->countActivityItems( $query_args );
		$this->items = $this->repo->getActivityItems( $query_args );

		$this->set_pagination_args(
			[
				'total_items' => $total_items,
				'per_page'    => $per_page,
				'total_pages' => (int) ceil( $total_items / $per_page ),
			]
		);

		$this->_column_headers = [
			$this->get_columns(),
			[],
			$this->get_sortable_columns(),
			'user',
		];
	}

	protected function column_cb( $item ): string {
		return sprintf(
			'<input type="checkbox" name="ml_activity[]" value="%d" />',
			(int) ( $item->id ?? 0 )
		);
	}

	protected function column_default( $item, $column_name ): string {
		return '';
	}

	protected function column_user( $item ): string {
		$user_id      = isset( $item->user_id ) ? (int) $item->user_id : 0;
		$display_name = (string) ( $item->display_name ?? '' );
		$row_id       = (int) ( $item->id ?? 0 );
		$edit_link    = $user_id > 0 ? get_edit_user_link( $user_id ) : '';

		$title = $display_name !== '' ? $display_name : '—';
		if ( $edit_link && $display_name !== '' ) {
			$title_html = '<strong><a class="row-title" href="' . esc_url( $edit_link ) . '">' . esc_html( $display_name ) . '</a></strong>';
		} else {
			$title_html = '<strong>' . esc_html( $title ) . '</strong>';
		}

		$actions = [];
		if ( $edit_link ) {
			$actions['edit'] = '<a href="' . esc_url( $edit_link ) . '">' . esc_html__( 'Edit user', 'wp-powersuite' ) . '</a>';
		}
		if ( $row_id > 0 ) {
			$delete_url = wp_nonce_url(
				add_query_arg(
					[
						'page'              => 'powersuite-magic-login',
						'ml_activity_action' => 'delete',
						'ml_activity_id'    => $row_id,
						'activity_status'   => $this->status_filter,
						's'                 => $this->search_query,
					],
					admin_url( 'admin.php' )
				),
				'wpps_ml_delete_activity_' . $row_id
			);
			$actions['delete'] = '<a href="' . esc_url( $delete_url ) . '" class="submitdelete" onclick="return confirm(\'' . esc_attr__( 'Delete this activity row?', 'wp-powersuite' ) . '\');">' . esc_html__( 'Delete', 'wp-powersuite' ) . '</a>';
		}

		return $title_html . $this->row_actions( $actions );
	}

	protected function column_email( $item ): string {
		$user_email = (string) ( $item->user_email ?? '' );
		if ( $user_email === '' ) {
			return '—';
		}
		return '<a href="mailto:' . esc_attr( $user_email ) . '">' . esc_html( $user_email ) . '</a>';
	}

	protected function column_created( $item ): string {
		return $this->formatActivityDate( (string) ( $item->created_at ?? '' ) );
	}

	protected function column_used( $item ): string {
		return $this->formatActivityDate( (string) ( $item->used_at ?? '' ) );
	}

	protected function column_expires( $item ): string {
		return $this->formatActivityDate( (string) ( $item->expires_at ?? '' ) );
	}

	protected function column_ip( $item ): string {
		$ip = (string) ( $item->ip_address ?? '' );
		return $ip !== '' ? esc_html( $ip ) : '—';
	}

	protected function column_status( $item ): string {
		[ $label, $class ] = $this->repo->resolveActivityStatus( $item );
		return '<span class="wpps-ml-status wpps-ml-status--' . esc_attr( $class ) . '">' . esc_html( $label ) . '</span>';
	}

	public function no_items(): void {
		if ( $this->search_query !== '' || $this->status_filter !== 'all' ) {
			echo esc_html__( 'No activity matches your search or filter.', 'wp-powersuite' );
			echo ' <a href="' . esc_url( admin_url( 'admin.php?page=powersuite-magic-login' ) ) . '">' . esc_html__( 'Clear filters', 'wp-powersuite' ) . '</a>';
			return;
		}
		esc_html_e( 'No magic login activity yet.', 'wp-powersuite' );
	}

	protected function get_views(): array {
		$base_url = admin_url( 'admin.php?page=powersuite-magic-login' );
		$search   = $this->search_query !== '' ? '&s=' . rawurlencode( $this->search_query ) : '';
		$counts   = $this->repo->getActivityStatusCounts( $this->search_query );

		$views = [];
		foreach (
			[
				'all'     => __( 'All', 'wp-powersuite' ),
				'used'    => __( 'Used', 'wp-powersuite' ),
				'pending' => __( 'Pending', 'wp-powersuite' ),
				'expired' => __( 'Expired', 'wp-powersuite' ),
			] as $key => $label
		) {
			$url = add_query_arg( 'activity_status', $key, $base_url ) . $search;
			$views[ $key ] = sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( $url ),
				$this->status_filter === $key ? 'current' : '',
				esc_html( $label ),
				(int) ( $counts[ $key ] ?? 0 )
			);
		}

		return $views;
	}

	private function formatActivityDate( string $datetime ): string {
		if ( $datetime === '' ) {
			return '—';
		}
		$ts = strtotime( $datetime . ' UTC' );
		if ( ! $ts ) {
			return '—';
		}
		$format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
		return esc_html( wp_date( $format, $ts ) );
	}
}
