<?php
if (!defined('ABSPATH')) {
    exit;
}

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

class BotBlocker_Log_Table extends WP_List_Table {
    public function __construct() {
        parent::__construct(['singular' => 'bot-event', 'plural' => 'bot-events', 'ajax' => false]);
    }

    public function get_columns() {
        return [
            'cb'          => '<input type="checkbox" />',
            'occurred_at' => __('Time', 'sera-bot-blocker'),
            'bot_name'    => __('Bot', 'sera-bot-blocker'),
            'category'    => __('Category', 'sera-bot-blocker'),
            'action_taken'=> __('Action', 'sera-bot-blocker'),
            'country'     => __('Country', 'sera-bot-blocker'),
            'path'        => __('Path', 'sera-bot-blocker'),
        ];
    }

    protected function get_sortable_columns() {
        return [
            'occurred_at' => ['occurred_at', true],
            'bot_name'    => ['bot_name', false],
            'category'    => ['category', false],
            'action_taken'=> ['action_taken', false],
            'country'     => ['country', false],
        ];
    }

    protected function column_cb($item) {
        return '<input type="checkbox" name="log_ids[]" value="' . (int) $item['id'] . '" />';
    }

    public function column_default($item, $column_name) {
        return esc_html($item[$column_name] ?? '');
    }

    public function get_bulk_actions() {
        return [
            'delete_selected' => __('Delete selected', 'sera-bot-blocker'),
            'delete_filtered' => __('Delete filtered', 'sera-bot-blocker'),
            'delete_all'      => __('Delete all', 'sera-bot-blocker'),
        ];
    }

    public function prepare_items() {
        $per_page = 30;
        $args = [
            'paged'    => $this->get_pagenum(),
            'per_page' => $per_page,
            'orderby'  => isset($_GET['orderby']) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'occurred_at',
            'order'    => isset($_GET['order']) ? sanitize_text_field(wp_unslash($_GET['order'])) : 'DESC',
            's'        => isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '',
            'category' => isset($_GET['filter_category']) ? sanitize_text_field(wp_unslash($_GET['filter_category'])) : '',
            'action'   => isset($_GET['filter_action']) ? sanitize_text_field(wp_unslash($_GET['filter_action'])) : '',
        ];

        $result = BotBlocker_Storage::search_logs($args);
        $this->items = $result['items'];
        $this->_column_headers = [$this->get_columns(), [], $this->get_sortable_columns()];
        $this->set_pagination_args([
            'total_items' => $result['total'],
            'per_page'    => $per_page,
            'total_pages' => ceil($result['total'] / $per_page),
        ]);
    }
}
