<?php
defined( 'ABSPATH' ) or exit;   // show a blank page if try to access this file directly

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

/* class modified from plugin custom-list-table-example/list-table-example.php */

class Ewz_Item_List extends WP_List_Table
{

    /**
     * @var int            $default_ipp
     */
     private $default_ipp = 20;

    /**
     * @var array<string>  $ewz_rows
     */
    public $ewz_rows;           // array of data to be displayed

    /**
     * @var array<int>     $ewz_item_ids
     */
    public $ewz_item_ids;       // array of integers

    /**
     * @var bool           $display_for_edit
     */
    public $display_for_edit;   // if true, edit view is being asked for

    /**
     * @var bool           $is_read_only
     */
    public $is_read_only;

    /**
     * @var array<int, string>  $field_headers
     */
    private $field_headers;

/**
 * @param  array<int>    $in_item_ids           item_ids
 * @param  array<string>    $in_headers            strings
 * @param  array<string>    $in_rows               array of arrays of strings
 * @param  bool  $in_display_for_edit   true if preparing the items for editing
 * @param  bool  $is_read_only          not currently used
 *
 * @return void
 */
    public function __construct( $in_item_ids, $in_headers, $in_rows,  $in_display_for_edit, $is_read_only=false )
    {
        //Set parent defaults
        parent::__construct( array(
            'singular' => 'item',       //singular name of the listed records
            'plural' => 'items',        //plural name of the listed records
            'ajax' => false             //does this table support ajax?
        ) );
        $html_headers = array();
        foreach( $in_headers as $n=>$header ){
            $html_headers[$n] = "$header<br>($n)";
        }
        $this->field_headers = $html_headers;
        $this->ewz_rows = $in_rows;
        $this->ewz_item_ids = $in_item_ids;
        $this->is_read_only = $is_read_only;
        $this->display_for_edit = $in_display_for_edit;
        $this->prepare_items($in_display_for_edit);
    }

    /** ************************************************************************
     * Generally, it's recommended to include a "column_xxx" method for each column
     * "xxx"you want to render.  But we are passing that value in when we instantiate
     * the table, so don't need that
     *
     * For more detailed insight into how columns are handled, take a look at
     * WP_List_Table::single_row_columns()
     *
     * @param array $row A singular item (one full row's worth of data)
     * @param string $col_name The name/slug of the column to be processed
     * @return string Text or HTML to be placed inside the column <td>
     **************************************************************************/
/**
 *
 * @param array<string>  $row
 * @param string  $col_name
 *
 * @return string   value to display in cell
 */
    protected function column_default( $row, $col_name )
    {
        // just use the value in the input row, which is generated elsewhere
        if( isset( $row[$col_name] ) ){
            return $row[$col_name];
        } else {
            return '';
        }
    }

    /** ***********************************************************************
     * Here is the one special column we do need - the one containing the checkbox
     **************************************************************************/
/**
 *
 * @param array<string>  $row
 *
 * @return string   html to display the checkbox
 */
    protected function column_cb( $row )
    {
        if( $this->is_read_only ){
            return '';
        } else {
            // override column default, show a checkbox
            return sprintf(
                '<input type="checkbox" name="%1$s[]" id="ewz_check%2$s_" value="%2$s" />',
                /* $1%s */ 'ewz_check',
                /* $2%s */ $row[0]    //The value of the checkbox should be the record's id
            );
        }
    }

/**
 *
 * @return array<string>  of strings
 */
    public function get_columns()
    {
        $columns = array();
        $columns['cb'] = $this->is_read_only ? '' :  '<input type="checkbox" />';
        foreach ( $this->field_headers as $n => $header ) {
            if ( $n > 0 ) {
                $columns[$n] = $header;
            }
        }
        return $columns;
    }

/**
 * @return array< int, array<string|bool> >   indexes of columns that are sortable
 */
    protected function get_sortable_columns() {
        $sortable_columns = array();
        foreach ( $this->field_headers as $n => $header ) {
            if ( $n > 0 ) {
                // quotes around $n required for sorting to work properly
                $sortable_columns[$n] = array( "$n", true );
                ++$n;
            }
        }
        return $sortable_columns;
    }

    /**
     * Return the array of bulk actions to be shown in the drop-down
     * Also note that list tables are not automatically wrapped in <form> elements,
     * so you will need to create those manually in order for bulk actions to function.
     *
     * @return array<string,string> An  array containing all the bulk actions: 'slugs'=>'Visible Titles'
     */
    protected function get_bulk_actions()
    {
        if( $this->is_read_only ){
            $actions = array();
        } elseif( $this->display_for_edit ){
            $actions = array(
                'ewz_save_edits' => 'Save changes to the uploaded data.',
            );

        } else {
            $actions = array(
                // attach is done via ajax, since list page itself does not change
                'ewz_attach_imgs'  => 'Attach images to Selected Page',

                // delete does a submit
                'ewz_batch_delete_all' => 'Delete Selected Items ( and Image Files )',

                // delete does a submit
                'ewz_batch_delete_data' => 'Delete Selected Item Data Only',

                // select for edit does a submit, changes which items are visible
                'ewz_select_for_edit' => 'Edit the uploaded data for selected items',

            );
        }
        return $actions;
    }

    /**
     * Return those members of the input items list that match the $field_opts list of values.
     *
     * @param bool   $is_display_for_edit   true if we are preparing items for editing
     * @return void
     */
    public function prepare_items( $is_display_for_edit=false )
    {
        $user_id = get_current_user_id();
        if( $this->is_read_only){
            $per_page = 500;
        } else {
            $per_page = get_user_meta( $user_id, 'ewz_itemsperpage', true );

            if ( empty( $per_page ) || $per_page < 1 ) {
                // set and use the default value if none is set
                update_user_meta( $user_id,'ewz_itemsperpage', $this->default_ipp );
                $per_page = $this->default_ipp;
            }
        }
        // headers
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);

        $data = $this->ewz_rows;

        // pagination
        $current_page = ( $this->is_read_only || $is_display_for_edit ) ? 1 : $this->get_pagenum();
        $total_items = count( $data );
        $dataslice = array_slice( $data, (($current_page - 1) * $per_page ), $per_page );
        $this->set_pagination_args( array(
            'total_items' => $total_items,
            'per_page' => $per_page,
            'total_pages' => ceil( $total_items / $per_page )
        ) );

        $this->items = $dataslice;
    }

}
