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

class Ai2MediaDataTable extends WP_List_Table {

	const DB_NAME = "ai2media_data_table";
	const CHECKBOX_ACTION = "checkbox-select-action";
	const MAX_RECORDS_ON_PAGE = 10;

	private static $shared = null;

	static function getShared() {
		if ( self::$shared === null ) {
			self::$shared = new Ai2MediaDataTable();
		}
		return self::$shared;
	}

	function __construct() {
		parent::__construct( array(
			'singular' => 'custom_data',
			'plural'   => 'custom_datas',
			'ajax'     => false
		) );
	}

	function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'id':
			case 'title':
			case 'text':
			case 'summary':
			default:
				return $item[ $column_name ];
		}
	}

	function column_cb( $item ) {
		return sprintf( "<input type='checkbox' name='%s[]' value='%s' />",
			Ai2MediaDataTable::CHECKBOX_ACTION, $item['id'] );
	}

	function get_columns() {
		$columns = array(
			'cb'      => '<input type="checkbox" />',
			'title'   => 'Title',
			'text'    => 'Text',
			'summary' => 'Summary'
		);
		return $columns;
	}

	function prepare_items() {
		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );

		global $wpdb;
		$table_name = $wpdb->prefix . Ai2MediaDataTable::DB_NAME;

		$data = $wpdb->get_results( "SELECT * FROM $table_name", ARRAY_A );

		$per_page     = self::MAX_RECORDS_ON_PAGE;
		$current_page = $this->get_pagenum();
		$total_items  = count( $data );

		$this->set_pagination_args( array(
			'total_items' => $total_items,
			'per_page'    => $per_page
		) );

		$data = array_slice( $data, ( ( $current_page - 1 ) * $per_page ), $per_page );

		$this->items = $data;
	}
}
