<?php

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

class Backpack_History_List_Table extends WP_List_Table
{
    public function __construct()
    {
        parent::__construct([
            'singular' => 'log', // Singular name of the item
            'plural'   => 'logs', // Plural name of the items
            'ajax'     => false, // Set to true if using Ajax
        ]);
    }

    // Define columns
    public function get_columns()
    {
        return [
            'cb'         => '<input type="checkbox" />', // Checkbox for bulk actions
            'ID'         => 'ID',
            'message'    => 'Message',
            'type'       => 'Type',
            'created_at' => 'Created At',
        ];
    }

    // Default column rendering
    protected function column_default($item, $column_name)
    {
        global $backpack;

        switch ($column_name) {
            case 'ID':
            case 'message':
            case 'type':
                return $item[$column_name];

            case 'created_at':
                if ($item[$column_name] !== null) {
                    $date = Carbon\Carbon::createFromFormat("Y-m-d H:i:s", $item[$column_name], $backpack->getTimezone());
                    return $date->format('d/m/Y H:i');
                }

                return "N/A";
            default:
                return print_r($item, true); // Show the array for undefined columns
        }
    }

    // Render the checkbox column
    protected function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="bulk-select[]" value="%s" />',
            $item['ID']
        );
    }

    // Prepare the items to display in the table
    public function prepare_items()
    {
        $columns  = $this->get_columns();
        $hidden   = [];
        $sortable = $this->get_sortable_columns();

        $this->_column_headers = [$columns, $hidden, $sortable];

        // Get sort parameters
        $orderBy = (! empty($_GET['orderby'])) ? sanitize_text_field($_GET['orderby']) : 'id'; // Default sort column.
        $order   = (! empty($_GET['order'])) && 'asc' === strtolower($_GET['order']) ? 'ASC' : 'DESC'; // Default order.


        $data         = $this->get_data($orderBy, $order);
        $current_page = $this->get_pagenum();
        $per_page     = 50;

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

        $this->items = $data;

        $this->set_pagination_args([
            'total_items' => $total_items,
            'per_page'    => $per_page,
            'total_pages' => ceil($total_items / $per_page),
        ]);
    }

    private function get_data(string $orderBy = 'id', string $order = 'DESC')
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'backpack_log'; // Replace 'your_table_name' with the actual table name

        $query   = "SELECT id as ID, message, type, created_at FROM $table_name ORDER BY $orderBy $order"; // Match field names to your table schema
        $results = $wpdb->get_results($query, ARRAY_A);

        return $results ? $results : [];
    }

    // Define sortable columns
    protected function get_sortable_columns()
    {
        return [
            'ID'         => ['ID', true],
            'message'    => ['message', false],
            'type'       => ['type', false],
            'created_at' => ['created_at', false],
        ];
    }
}
