<?php
/**
 * Buttons list table.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

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

/**
 * Rsmspark_Buttons_List_Table
 */
class Rsmspark_Buttons_List_Table extends WP_List_Table {

	/**
	 * @return void
	 */
	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'rsmspark_button',
				'plural'   => 'rsm_buttons',
				'ajax'     => false,
			)
		);
	}

	/**
	 * Hide duplicate bottom bulk actions row.
	 *
	 * @param string $which top|bottom.
	 * @return void
	 */
	protected function extra_tablenav( $which ) {
		unset( $which );
	}

	/**
	 * @return array<string, string>
	 */
	public function get_columns() {
		$columns = array(
			'cb'        => '<input type="checkbox" />',
			'title'     => __( 'Button Name', 'rsm-content-widgets' ),
			'shortcode' => __( 'Shortcode', 'rsm-content-widgets' ),
			'modified'  => __( 'Last Modified', 'rsm-content-widgets' ),
		);

		if ( class_exists( 'Rsmspark_Buttons_Settings', false ) && Rsmspark_Buttons_Settings::show_list_preview() ) {
			$columns = array_merge(
				array_slice( $columns, 0, 2, true ),
				array( 'preview' => __( 'Preview', 'rsm-content-widgets' ) ),
				array_slice( $columns, 2, null, true )
			);
		}

		return $columns;
	}

	/**
	 * @return array<string, array<string, string>>
	 */
	protected function get_bulk_actions() {
		return array(
			'delete'    => __( 'Delete', 'rsm-content-widgets' ),
			'duplicate' => __( 'Duplicate', 'rsm-content-widgets' ),
		);
	}

	/**
	 * @param object $item Post object.
	 * @return string
	 */
	protected function column_cb( $item ) {
		return sprintf( '<input type="checkbox" name="button_ids[]" value="%d" />', absint( $item->ID ) );
	}

	/**
	 * @param object $item Post.
	 * @return string
	 */
	protected function column_title( $item ) {
		$edit_url = Rsmspark_Buttons_Admin::edit_url( (int) $item->ID );
		$actions  = array(
			'edit'      => sprintf( '<a href="%s">%s</a>', esc_url( $edit_url ), esc_html__( 'Edit', 'rsm-content-widgets' ) ),
			'duplicate' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( wp_nonce_url( Rsmspark_Buttons_Admin::list_url( array( 'action' => 'duplicate', 'button_id' => (int) $item->ID ) ), 'rsmspark_buttons_duplicate_' . (int) $item->ID ) ),
				esc_html__( 'Duplicate', 'rsm-content-widgets' )
			),
			'trash'     => sprintf(
				'<a href="%s" class="submitdelete">%s</a>',
				esc_url( wp_nonce_url( Rsmspark_Buttons_Admin::list_url( array( 'action' => 'trash', 'button_id' => (int) $item->ID ) ), 'rsmspark_buttons_trash_' . (int) $item->ID ) ),
				esc_html__( 'Trash', 'rsm-content-widgets' )
			),
		);

		return sprintf(
			'<strong><a href="%1$s">%2$s</a></strong>%3$s',
			esc_url( $edit_url ),
			esc_html( $item->post_title ),
			$this->row_actions( $actions )
		);
	}

	/**
	 * @param object $item Post.
	 * @return string
	 */
	protected function column_preview( $item ) {
		return '<div class="rsm-buttons-list-preview">' . Rsmspark_Buttons_Render::render( Rsmspark_Buttons_Config::get( (int) $item->ID ), (int) $item->ID, true ) . '</div>';
	}

	/**
	 * @return void
	 */
	public function no_items() {
		esc_html_e( 'Create your first reusable button to use across your site with a simple shortcode.', 'rsm-content-widgets' );
	}

	/**
	 * @param object $item Post.
	 * @return string
	 */
	protected function column_shortcode( $item ) {
		$shortcode = '[rsm_button id="' . absint( $item->ID ) . '"]';
		return sprintf(
			'<code class="rsm-buttons-shortcode-text">%1$s</code> <button type="button" class="button button-small rsm-buttons-copy-shortcode" data-shortcode="%2$s">%3$s</button>',
			esc_html( $shortcode ),
			esc_attr( $shortcode ),
			esc_html__( 'Copy', 'rsm-content-widgets' )
		);
	}

	/**
	 * @param object $item Post.
	 * @return string
	 */
	protected function column_modified( $item ) {
		return esc_html( get_the_modified_date( '', $item ) );
	}

	/**
	 * @param string $column_name Column name.
	 * @param object $item        Post item.
	 * @return void
	 */
	public function column_default( $column_name, $item ) {
		unset( $column_name, $item );
		echo '';
	}

	/**
	 * @return void
	 */
	public function prepare_items() {
		$this->_column_headers = array(
			$this->get_columns(),
			array(),
			$this->get_sortable_columns(),
		);

		$per_page = 20;
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only list filtering parameters; no state change.
		$paged    = isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1;
		$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['s'] ) ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		$query = new WP_Query(
			array(
				'post_type'              => Rsmspark_Buttons_CPT::get_post_types(),
				'post_status'            => array( 'publish', 'draft', 'private' ),
				'posts_per_page'         => $per_page,
				'paged'                  => $paged,
				's'                      => $search,
				'orderby'                => 'modified',
				'order'                  => 'DESC',
				'update_post_meta_cache' => true,
				'no_found_rows'          => false,
			)
		);

		$this->items = $query->posts;
		$this->set_pagination_args(
			array(
				'total_items' => (int) $query->found_posts,
				'per_page'    => $per_page,
				'total_pages' => (int) $query->max_num_pages,
			)
		);
	}

	/**
	 * Render table without duplicate bottom bulk row.
	 *
	 * @return void
	 */
	public function display() {
		$singular = $this->_args['singular'];

		$this->display_tablenav( 'top' );

		$this->screen->render_screen_reader_content( 'heading_list' );
		?>
<table class="wp-list-table <?php echo esc_attr( implode( ' ', $this->get_table_classes() ) ); ?>">
	<thead>
	<tr>
		<?php $this->print_column_headers(); ?>
	</tr>
	</thead>
	<tbody id="the-list"
		<?php
		if ( $singular ) {
			echo ' data-wp-lists="list:' . esc_attr( $singular ) . '"';
		}
		?>
		>
		<?php $this->display_rows_or_placeholder(); ?>
	</tbody>
</table>
		<?php
	}
}
