<?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', 'wp-powersuite' ),
			'target' => __( 'Target', 'wp-powersuite' ),
			'type'   => __( 'Type', 'wp-powersuite' ),
			'match'  => __( 'Match', 'wp-powersuite' ),
			'hits'   => __( 'Hits', 'wp-powersuite' ),
			'last'   => __( 'Last Hit', 'wp-powersuite' ),
			'status' => __( 'Status', 'wp-powersuite' ),
		];
	}

	/**
	 * 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', 'wp-powersuite' ),
			'disable' => __( 'Disable', 'wp-powersuite' ),
			'delete'  => __( 'Delete', 'wp-powersuite' ),
		];
	}

	/**
	 * 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', 'wp-powersuite' )
			),
			'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', 'wp-powersuite' )
			),
			'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?', 'wp-powersuite' ),
				__( 'Delete', 'wp-powersuite' )
			),
		];
		$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', 'wp-powersuite' ),
			'regex'    => __( 'Regex', 'wp-powersuite' ),
			'exact'    => __( 'Exact', 'wp-powersuite' ),
		];
		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' );
		}
		return $ts ? sprintf( __( '%s ago', 'wp-powersuite' ), 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', 'wp-powersuite' ) : __( 'Click to enable', 'wp-powersuite' ) ),
			$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.', 'wp-powersuite' );
		} else {
			echo esc_html__( 'No redirects match your search or filter.', 'wp-powersuite' );
			echo ' <a href="' . esc_url( admin_url( 'admin.php?page=powersuite-redirect-manager' ) ) . '" class="button">' . esc_html__( 'Clear filters', 'wp-powersuite' ) . '</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', 'wp-powersuite' ),
				$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', 'wp-powersuite' ),
				$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', 'wp-powersuite' ),
				$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', 'wp-powersuite' ); ?></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>';
	}
}
