<?php
/**
 * Table
 *
 * Main table file for the plugin.
 *
 * @category   Plugins
 * @package    WordPress
 * @author     Peachy Software LLC
 */

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

/**
 * PSDM_List_Table
 *
 * Class for the table.
 */
class PSDM_List_Table extends WP_List_Table {
	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct(
			array(
				'singular' => 'wp_list_psdm_download', // Singular label.
				'plural'   => 'wp_list_psdm_downloads', // plural label, also this well be one of the table css class.
				'ajax'     => false, // We won't support Ajax for this table.
			)
		);
	}
	/**
	 * Display the table
	 *
	 * @param string $item which item to format.
	 * @return string
	 */
	public function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="downloads[]" value="%s" />',
			$item->id
		);
	}

	/**
	 * Display the table
	 *
	 * @return array
	 */
	public function get_columns() {
		return array(
			'cb'            => '<input type="checkbox" />',
			'id'            => __( 'ID' ),
			'download_name' => __( 'Download' ),
			'name'          => __( 'Name' ),
			'email_address' => __( 'Email' ),
			'comments'      => __( 'Status' ),
			'time'          => __( 'Date' ),
			'ip_address'    => __( 'IP Address' ),
		);
	}

	/**
	 * Prepare the table with different parameters, pagination, columns and table elements
	 */
	public function prepare_items() {
		global $wpdb, $_wp_column_headers;
		$this->process_bulk_items();
		$query = "SELECT * FROM {$wpdb->prefix}psdm_downloads ORDER BY time DESC";
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$totalitems = $wpdb->query( $query );
		$perpage    = 10;
		$paged      = ! empty( $_GET['paged'] ) ? sanitize_text_field( wp_unslash( $_GET['paged'] ) ) : '’';
		if ( empty( $paged ) || ! is_numeric( $paged ) || $paged <= 0 ) {
			$paged = 1; }
		$totalpages = ceil( $totalitems / $perpage );
		if ( ! empty( $paged ) && ! empty( $perpage ) ) {
			$offset = ( $paged - 1 ) * $perpage;
			$query .= ' LIMIT ' . (int) $offset . ',' . (int) $perpage; }
		$this->set_pagination_args(
			array(
				'total_items' => $totalitems,
				'total_pages' => $totalpages,
				'per_page'    => $perpage,
			)
		);
		$columns               = $this->get_columns();
		$primary               = 'id';
		$hidden                = array();
		$sortable              = array();
		$this->_column_headers = array( $columns, $hidden, $sortable, $primary );
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$this->items = $wpdb->get_results( $query );
	}

	/**
	 * Process bulk actions
	 */
	public function process_bulk_items() {
		global $wpdb;
		if ( 'delete' === $this->current_action() ) {
			if ( isset( $_REQUEST['_wpnonce'] ) ) {
				if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) ), 'bulk-' . $this->_args['plural'] ) ) {
					$table = "{$wpdb->prefix}psdm_downloads";
					$psdm_post = filter_input_array( INPUT_POST, FILTER_SANITIZE_NUMBER_INT );
					foreach ( $psdm_post['downloads'] as $id ) {
						$wpdb->delete( $table, array( 'id' => $id ) );
					}
					echo '<div class="notice notice-success is-dismissible"><p>Download Information Deleted</p></div>';
				} else {
					echo '<div class="notice notice-error is-dismissible"><p>Security Error, Unable to Delete, refresh the page and try again.</p></div>';
				}
			}
		}
	}

	/**
	 * Format column heqder
	 *
	 * @param string $item which item to format.
	 * @param string $column_name which column to format.
	 * @return string
	 */
	public function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'id':
			case 'download_name':
			case 'name':
			case 'email_address':
			case 'ip_address':
			case 'comments':
			case 'time':
				return $item->$column_name;
			default:
				return '';
		}
	}

	/**
	 * Get bulk actions
	 *
	 * @return array
	 */
	public function get_bulk_actions() {
		$actions = array(
			'delete' => 'Delete',
		);
		return $actions;
	}


}
