<?php
defined('ABSPATH') || exit;

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

class CF7_Submissions_List_Table extends WP_List_Table {
    private $table_name;

    public function __construct() {
        global $wpdb;
        parent::__construct([
            'singular' => 'cf7_submission',
            'plural'   => 'cf7_submissions',
            'ajax'     => false,
        ]);
        $this->table_name = $wpdb->prefix . 'cf7_submissions';
    }

    public function get_columns() {
        return [
            'cb'          => '<input type="checkbox" />',
            'name'        => 'Name',
            'email'       => 'Email',
            'phone'       => 'Phone',
            'message'     => 'Message',
            'submitted_at'=> 'Submitted At',
        ];
    }

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

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

    public function get_bulk_actions() {
        return ['delete' => 'Delete'];
    }

    public function process_bulk_action() {
        global $wpdb;

        if ($this->current_action() === 'delete') {
            $ids = isset($_POST['submission']) ? array_map('intval', $_POST['submission']) : [];
            if ($ids) {
                $placeholders = implode(',', array_fill(0, count($ids), '%d'));
                $wpdb->query($wpdb->prepare("DELETE FROM {$this->table_name} WHERE id IN ($placeholders)", ...$ids));
            }
        }
    }

    public function prepare_items() {
        global $wpdb;

        $this->process_bulk_action();

        $per_page = 10;
        $current_page = $this->get_pagenum();
        $search = !empty($_REQUEST['s']) ? sanitize_text_field($_REQUEST['s']) : '';

        $where = '';
        if ($search) {
            $like = '%' . $wpdb->esc_like($search) . '%';
            $where = $wpdb->prepare("WHERE name LIKE %s OR email LIKE %s OR phone LIKE %s OR message LIKE %s", $like, $like, $like, $like);
        }

        $total_items = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} $where");

        $offset = ($current_page - 1) * $per_page;

        $this->items = $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM {$this->table_name} $where ORDER BY submitted_at DESC LIMIT %d OFFSET %d", $per_page, $offset)
        );

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

        $this->_column_headers = [$this->get_columns(), [], $this->get_sortable_columns()];
    }

    public function get_sortable_columns() {
        return [
            'name'        => ['name', false],
            'email'       => ['email', false],
            'submitted_at'=> ['submitted_at', true],
        ];
    }

    public function search_box($text, $input_id) {
        if (!$this->has_items() && empty($_REQUEST['s'])) return;

        $input_id = $input_id . '-search-input';
        ?>
        <form method="get">
            <input type="hidden" name="page" value="<?php echo esc_attr($_REQUEST['page']); ?>" />
            <p class="search-box">
                <label class="screen-reader-text" for="<?php echo $input_id; ?>"><?php echo esc_html($text); ?>:</label>
                <input type="search" id="<?php echo $input_id; ?>" name="s" value="<?php echo esc_attr($_REQUEST['s'] ?? ''); ?>" />
                <?php submit_button($text, '', '', false); ?>
            </p>
        </form>
        <?php
    }
}
