<?php
/**
 * Basic Forms - Forms List Table
 *
 * @package BasicForms
 * @since 1.0.0
 */

namespace BasicForms;

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

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

/**
 * Forms List Table for Basic Forms admin.
 */
class FormsListTable extends \WP_List_Table {

	private string $table_name;

	public function __construct() {
		global $wpdb;
		$this->table_name = $wpdb->prefix . 'wpps_form_entries';

		parent::__construct( [
			'singular' => 'form',
			'plural'   => 'forms',
			'ajax'     => false,
		] );
	}

	/** @return array<string, string> */
	public function get_columns(): array {
		return [
			'cb'        => '<input type="checkbox" />',
			'id'        => 'ID',
			'title'     => __( 'Form Name', 'wp-powersuite' ),
			'entries'   => __( 'Entries', 'wp-powersuite' ),
			'date'      => __( 'Date Created', 'wp-powersuite' ),
			'shortcode' => __( 'Shortcode', 'wp-powersuite' ),
		];
	}

	/** @return array<string, string> */
	protected function get_bulk_actions(): array {
		return [
			'delete' => __( 'Delete', 'wp-powersuite' ),
		];
	}

	/** @param \WP_Post $item */
	protected function column_cb( $item ): string {
		return sprintf( '<input type="checkbox" name="form[]" value="%d" />', (int) $item->ID );
	}

	/** @return array<string, array> */
	public function get_sortable_columns(): array {
		return [
			'id'    => [ 'ID', false ],
			'title' => [ 'post_title', false ],
			'date'  => [ 'post_date', true ],
		];
	}

	/** @param \WP_Post $item */
	public function column_default( $item, $column_name ) {
		global $wpdb;

		switch ( $column_name ) {
			case 'id':
				return (string) $item->ID;
			case 'entries':
				$count = (int) $wpdb->get_var( $wpdb->prepare(
					"SELECT COUNT(*) FROM {$this->table_name} WHERE form_id = %d",
					$item->ID
				) );
				if ( $count > 0 ) {
					return '<a href="' . esc_url( admin_url( 'admin.php?page=powersuite-basic-forms&view=entries&form_filter=' . $item->ID ) ) . '">' . esc_html( (string) $count ) . ' ' . esc_html__( 'entries', 'wp-powersuite' ) . '</a>';
				}
				return '<span style="color:#94a3b8;">0 ' . esc_html__( 'entries', 'wp-powersuite' ) . '</span>';
			case 'date':
				return esc_html( gmdate( 'M j, Y', strtotime( $item->post_date ) ) );
			case 'shortcode':
				return '<input type="text" readonly value=\'[basic_form id="' . esc_attr( (string) $item->ID ) . '"]\' class="wpps-bf-shortcode-input" onclick="wppsBfCopyShortcode(this)" title="' . esc_attr__( 'Click to copy', 'wp-powersuite' ) . '"><span class="wpps-bf-shortcode-copied">' . esc_html__( 'Copied!', 'wp-powersuite' ) . '</span>';
			default:
				return '';
		}
	}

	/** @param \WP_Post $item */
	public function column_title( $item ): string {
		$actions = [
			'edit'    => '<a href="' . esc_url( admin_url( 'admin.php?page=powersuite-basic-forms&action=edit&form_id=' . $item->ID ) ) . '">' . esc_html__( 'Edit', 'wp-powersuite' ) . '</a>',
			'entries' => '<a href="' . esc_url( admin_url( 'admin.php?page=powersuite-basic-forms&view=entries&form_filter=' . $item->ID ) ) . '">' . esc_html__( 'Entries', 'wp-powersuite' ) . '</a>',
			'delete'  => '<a href="' . esc_url( wp_nonce_url( admin_url( 'admin.php?page=powersuite-basic-forms&action=delete&form_id=' . $item->ID ), 'delete_form_' . $item->ID ) ) . '" onclick="return confirm(\'' . esc_js( __( 'Delete this form and all its entries?', 'wp-powersuite' ) ) . '\')">' . esc_html__( 'Delete', 'wp-powersuite' ) . '</a>',
		];

		return sprintf(
			'<strong><a href="%s">%s</a></strong>%s',
			esc_url( admin_url( 'admin.php?page=powersuite-basic-forms&action=edit&form_id=' . $item->ID ) ),
			esc_html( $item->post_title ),
			$this->row_actions( $actions )
		);
	}

	public function prepare_items(): void {
		$columns = $this->get_columns();
		$hidden = [];
		$sortable = $this->get_sortable_columns();
		$this->_column_headers = [ $columns, $hidden, $sortable ];

		$per_page = 20;
		$current_page = $this->get_pagenum();
		$orderby = isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : 'post_date';
		$order = isset( $_GET['order'] ) ? sanitize_text_field( wp_unslash( $_GET['order'] ) ) : 'DESC';

		$args = [
			'post_type'      => 'wpps_form',
			'posts_per_page' => $per_page,
			'paged'          => $current_page,
			'orderby'        => $orderby,
			'order'          => $order,
			'post_status'    => 'any',
		];

		$search = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
		if ( $search !== '' ) {
			$args['s'] = $search;
		}

		$query = new \WP_Query( $args );
		$this->items = $query->posts;

		$this->set_pagination_args( [
			'total_items' => $query->found_posts,
			'per_page'    => $per_page,
			'total_pages' => $query->max_num_pages,
		] );
	}

	public function no_items(): void {
		echo esc_html__( 'No forms found.', 'wp-powersuite' );
	}
}
