<?php
/**
 * Redirect Manager List Table
 *
 * Uses WordPress WP_List_Table for default table styling, header, and row actions.
 *
 * @package RedirectManager
 * @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 Redirect_Manager_List_Table
 */
class Redirect_Manager_List_Table extends WP_List_Table {

	/**
	 * Module instance.
	 *
	 * @var \RedirectManager\Module
	 */
	private $module;

	/**
	 * Status filter: all, active, inactive.
	 *
	 * @var string
	 */
	private $status_filter;

	/**
	 * Search query.
	 *
	 * @var string
	 */
	private $search_query;

	/**
	 * Nonce for toggle.
	 *
	 * @var string
	 */
	private $nonce;

	/**
	 * Constructor.
	 *
	 * @param \RedirectManager\Module $module Module instance.
	 * @param string                  $status Status filter (all, active, inactive).
	 * @param string                  $search Search query.
	 * @param string                  $nonce  Nonce for toggle.
	 */
	public function __construct( $module, $status = 'all', $search = '', $nonce = '' ) {
		$this->module        = $module;
		$this->status_filter = $status;
		$this->search_query  = $search;
		$this->nonce         = $nonce;
		parent::__construct(
			[
				'singular' => 'redirect',
				'plural'   => 'redirects',
				'ajax'     => false,
			]
		);
	}

	/**
	 * Get table columns.
	 *
	 * @return array
	 */
	public function get_columns() {
		return [
			'cb'     => '<input type="checkbox" />',
			'source' => __( 'Source', 'wppowersuite-lite' ),
			'target' => __( 'Target', 'wppowersuite-lite' ),
			'type'   => __( 'Type', 'wppowersuite-lite' ),
			'match'  => __( 'Match', 'wppowersuite-lite' ),
			'hits'   => __( 'Hits', 'wppowersuite-lite' ),
			'last'   => __( 'Last Hit', 'wppowersuite-lite' ),
			'status' => __( 'Status', 'wppowersuite-lite' ),
		];
	}

	/**
	 * Get sortable columns.
	 *
	 * @return array
	 */
	protected function get_sortable_columns() {
		return [
			'source' => [ 'source', false ],
			'target' => [ 'target', false ],
			'type'   => [ 'type', false ],
			'hits'   => [ 'hits', false ],
		];
	}

	/**
	 * Get bulk actions.
	 *
	 * @return array
	 */
	protected function get_bulk_actions() {
		return [
			'enable'  => __( 'Enable', 'wppowersuite-lite' ),
			'disable' => __( 'Disable', 'wppowersuite-lite' ),
			'delete'  => __( 'Delete', 'wppowersuite-lite' ),
		];
	}

	/**
	 * Prepare items for display.
	 */
	public function prepare_items() {
		$redirects = $this->module->getAllRedirects();
		if ( $this->status_filter === 'active' ) {
			$redirects = array_filter( $redirects, fn( $r ) => ! empty( $r['active'] ) );
		} elseif ( $this->status_filter === 'inactive' ) {
			$redirects = array_filter( $redirects, fn( $r ) => empty( $r['active'] ) );
		}
		if ( $this->search_query !== '' ) {
			$search_lower = strtolower( $this->search_query );
			$redirects    = array_filter( $redirects, function ( $r ) use ( $search_lower ) {
				return stripos( $r['source'] ?? '', $search_lower ) !== false
					|| stripos( $r['target'] ?? '', $search_lower ) !== false
					|| stripos( $r['notes'] ?? '', $search_lower ) !== false;
			} );
		}
		$orderby = isset( $_REQUEST['orderby'] ) ? sanitize_key( wp_unslash( $_REQUEST['orderby'] ) ) : 'source';
		$order   = isset( $_REQUEST['order'] ) && strtolower( wp_unslash( $_REQUEST['order'] ) ) === 'asc' ? 'asc' : 'desc';
		usort( $redirects, function ( $a, $b ) use ( $orderby, $order ) {
			$va = $a[ $orderby ] ?? '';
			$vb = $b[ $orderby ] ?? '';
			if ( $orderby === 'hits' ) {
				$va = (int) $va;
				$vb = (int) $vb;
				$c  = $va <=> $vb;
			} else {
				$c = strcasecmp( (string) $va, (string) $vb );
			}
			return $order === 'asc' ? $c : -$c;
		} );
		$this->items         = array_values( $redirects );
		$this->_column_headers = [
			$this->get_columns(),
			[],
			$this->get_sortable_columns(),
			'source',
		];
	}

	/**
	 * Checkbox column.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="ids[]" value="%s" />',
			esc_attr( $item['id'] ?? '' )
		);
	}

	/**
	 * Source column with row actions (Edit | Copy | Delete).
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_source( $item ) {
		$edit_url = admin_url( 'admin.php?page=powersuite-redirect-manager&edit=' . rawurlencode( $item['id'] ?? '' ) );
		$source   = $item['source'] ?? '';
		$actions  = [
			'edit' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( $edit_url ),
				__( 'Edit', 'wppowersuite-lite' )
			),
			'copy' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=wpps_redirect_manager_duplicate&id=' . rawurlencode( $item['id'] ?? '' ) ), 'wpps_redirect_duplicate' ) ),
				__( 'Copy', 'wppowersuite-lite' )
			),
			'delete' => sprintf(
				'<a href="%s" class="submitdelete" onclick="return confirm(\'%s\');">%s</a>',
				esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=wpps_redirect_manager_delete&id=' . rawurlencode( $item['id'] ?? '' ) ), 'wpps_redirect_delete' ) ),
				esc_attr__( 'Delete this redirect?', 'wppowersuite-lite' ),
				__( 'Delete', 'wppowersuite-lite' )
			),
		];
		$row_actions = $this->row_actions( $actions );
		return '<strong><a href="' . esc_url( $edit_url ) . '" class="row-title">' . esc_html( $source ) . '</a></strong>' . $row_actions;
	}

	/**
	 * Target column.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_target( $item ) {
		$target = $item['target'] ?? '';
		return $target !== '' ? '<code>' . esc_html( $target ) . '</code>' : '—';
	}

	/**
	 * Type column with badge.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_type( $item ) {
		$type = $item['type'] ?? '301';
		$is_error = in_array( $type, [ '401', '402', '403', '404', '405', '410', '501', '502', '503' ], true );
		$class = $is_error ? 'rm-status--off' : 'rm-status--on';

		return sprintf(
			'<span class="rm-status %1$s">%2$s</span>',
			esc_attr( $class ),
			esc_html( $type )
		);
	}

	/**
	 * Match column.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_match( $item ) {
		$match = $item['match_type'] ?? 'exact';
		$labels = [
			'wildcard' => __( 'Wildcard', 'wppowersuite-lite' ),
			'regex'    => __( 'Regex', 'wppowersuite-lite' ),
			'exact'    => __( 'Exact', 'wppowersuite-lite' ),
		];
		return $labels[ $match ] ?? $match;
	}

	/**
	 * Hits column.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_hits( $item ) {
		return number_format_i18n( (int) ( $item['hits'] ?? 0 ) );
	}

	/**
	 * Last hit column.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_last( $item ) {
		$datetime = $item['last_hit'] ?? null;
		if ( empty( $datetime ) ) {
			return '—';
		}
		$ts = get_date_from_gmt( (string) $datetime, 'U' );
		if ( ! $ts ) {
			$ts = strtotime( (string) $datetime . ' UTC' );
		}
		/* translators: %s: string value. */
		return $ts ? sprintf( __( '%s ago', 'wppowersuite-lite' ), human_time_diff( (int) $ts ) ) : esc_html( (string) $datetime );
	}

	/**
	 * Status column with toggle.
	 *
	 * @param array $item Redirect item.
	 * @return string
	 */
	protected function column_status( $item ) {
		$active = ! empty( $item['active'] );
		$id     = $item['id'] ?? '';
		return sprintf(
			'<label class="wpps-rm-toggle" title="%s">
				<input type="checkbox" class="wpps-rm-toggle-input" %s data-id="%s" data-nonce="%s" />
				<span class="wpps-rm-toggle-slider"></span>
			</label>',
			esc_attr( $active ? __( 'Click to disable', 'wppowersuite-lite' ) : __( 'Click to enable', 'wppowersuite-lite' ) ),
			$active ? 'checked' : '',
			esc_attr( $id ),
			esc_attr( $this->nonce )
		);
	}

	/**
	 * Message when no items.
	 */
	public function no_items() {
		$all = $this->module->getAllRedirects();
		if ( empty( $all ) ) {
			esc_html_e( 'No redirects found.', 'wppowersuite-lite' );
		} else {
			echo esc_html__( 'No redirects match your search or filter.', 'wppowersuite-lite' );
			echo ' <a href="' . esc_url( admin_url( 'admin.php?page=powersuite-redirect-manager' ) ) . '" class="button">' . esc_html__( 'Clear filters', 'wppowersuite-lite' ) . '</a>';
		}
	}

	/**
	 * Get views for the list table (All, Active, Inactive).
	 *
	 * @return array
	 */
	protected function get_views() {
		$base_url     = admin_url( 'admin.php?page=powersuite-redirect-manager' );
		$search       = $this->search_query !== '' ? '&s=' . rawurlencode( $this->search_query ) : '';
		$all          = $this->module->getAllRedirects();
		$count_all  = count( $all );
		$count_active = count( array_filter( $all, fn( $r ) => ! empty( $r['active'] ) ) );
		$count_inactive = count( array_filter( $all, fn( $r ) => empty( $r['active'] ) ) );
		return [
			'all' => sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( add_query_arg( 'status', 'all', $base_url ) . $search ),
				$this->status_filter === 'all' ? 'current' : '',
				__( 'All', 'wppowersuite-lite' ),
				$count_all
			),
			'active' => sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( add_query_arg( 'status', 'active', $base_url ) . $search ),
				$this->status_filter === 'active' ? 'current' : '',
				__( 'Active', 'wppowersuite-lite' ),
				$count_active
			),
			'inactive' => sprintf(
				'<a href="%s" class="%s">%s <span class="count">(%d)</span></a>',
				esc_url( add_query_arg( 'status', 'inactive', $base_url ) . $search ),
				$this->status_filter === 'inactive' ? 'current' : '',
				__( 'Inactive', 'wppowersuite-lite' ),
				$count_inactive
			),
		];
	}

	/**
	 * Extra tablenav: Clear cache button.
	 *
	 * @param string $which Top or bottom.
	 */
	protected function extra_tablenav( $which ) {
		if ( $which !== 'top' ) {
			return;
		}
		?>
		<div class="alignright">
			<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=wpps_redirect_manager_clear_cache' ), 'wpps_redirect_clear_cache' ) ); ?>" class="button"><?php esc_html_e( 'Clear cache', 'wppowersuite-lite' ); ?></a>
		</div>
		<?php
	}

	/**
	 * Add inactive class to row when redirect is disabled.
	 *
	 * @param object|array $item The current item.
	 */
	public function single_row( $item ) {
		$active = ! empty( $item['active'] );
		echo '<tr' . ( $active ? '' : ' class="wpps-rm-inactive"' ) . '>';
		$this->single_row_columns( $item );
		echo '</tr>';
	}
}

