<?php
// File: single-question-answers-list.php

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

add_action('wp_ajax_bcforum_approve_answer', 'bcforum_approve_answer');

function bcforum_approve_answer() {
    if ( ! check_ajax_referer( 'bc-forum-nonce', 'security', false ) ) {
        wp_send_json_error('Invalid security token.');
        wp_die();
    }

    global $wpdb;
    $answer_id = isset($_POST['answer_id']) ? intval($_POST['answer_id']) : 0;

    if (!$answer_id) {
        wp_send_json_error('Invalid answer ID.');
        wp_die();
    }

    $answers_table = $wpdb->prefix . 'answers';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $updated = $wpdb->update(
        $answers_table,
        array('approved' => 1),
        array('id' => $answer_id),
        array('%d'),
        array('%d')
    );

    if ($updated !== false) {
        wp_cache_delete('answer_' . $answer_id, 'my_plugin_answers');
        wp_send_json_success('Answer approved successfully.');
    } else {
        wp_send_json_error('Failed to approve the answer.');
    }
    wp_die();
}

add_action('wp_ajax_bcforum_delete_answer', 'bcforum_delete_answer');

function bcforum_delete_answer() {
    if ( ! check_ajax_referer( 'bc-forum-nonce', 'security', false ) ) {
        wp_send_json_error('Invalid security token.');
        wp_die();
    }

    global $wpdb;
    $answer_id = isset($_POST['answer_id']) ? intval($_POST['answer_id']) : 0;

    if (!$answer_id) {
        wp_send_json_error('Invalid answer ID.');
        wp_die();
    }

    $answers_table = $wpdb->prefix . 'answers';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $deleted_answer = $wpdb->delete(
        $answers_table,
        array('id' => $answer_id),
        array('%d')
    );

    if ($deleted_answer !== false) {
        wp_cache_delete('answer_' . $answer_id, 'my_plugin_answers');
        wp_send_json_success('Answer deleted successfully.');
    } else {
        wp_send_json_error('Failed to delete the answer.');
    }
    wp_die();
}


class BCForum_Single_Question_Answers_List extends WP_List_Table {
    private $question_id;

    public function __construct($question_id) {
        $this->question_id = $question_id;
        parent::__construct(array(
            'singular' => 'answer',
            'plural'   => 'answers',
            'ajax'     => false,
        ));
    }
    public function display() {
        $this->search_box('Search', 'bc-forum');
        parent::display();
    }    
    
    public function get_bulk_actions() {
        $actions = array(
            'approve' => "Approve",
            'delete' => 'Delete',
        );
        return $actions;
    }
    public function process_bulk_action() {
        if (
            ! isset($_REQUEST['_wpnonce']) ||
            ! wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'bulk-' . $this->_args['plural'])
        ) {
            return;
        }
    
        $action = $this->current_action();
    
        if ( ! in_array($action, ['delete', 'approve'], true) ) {
            return;
        }
    
        $answer_entry_ids = isset($_REQUEST['answer']) && is_array($_REQUEST['answer'])
            ? array_map('intval', wp_unslash($_REQUEST['answer']))
            : [];
    
        if (empty($answer_entry_ids)) {
            return;
        }
    
        global $wpdb;
        $answers_table = $wpdb->prefix . 'answers';
    
        foreach ($answer_entry_ids as $entry_id) {
            if ($action === 'delete') {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $deleted = $wpdb->delete($answers_table, ['id' => $entry_id], ['%d']);
                if ($deleted !== false) {
                    wp_cache_delete('answer_' . $entry_id, 'my_plugin_answers');
                }
            }
    
            if ($action === 'approve') {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $approved = $wpdb->update($answers_table, ['approved' => 1], ['id' => $entry_id], ['%d'], ['%d']);
                if ($approved !== false) {
                    wp_cache_delete('answer_' . $entry_id, 'my_plugin_answers');
                }
            }
        }
    }
    


public function prepare_items() {
    global $wpdb;

    $this->process_bulk_action();

    $per_page = 10;
    $current_page = $this->get_pagenum();

    // ✅ Get search term
    $search_term = '';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset($_REQUEST['s']) && is_string($_REQUEST['s']) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $search_term = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) );
        }

    // ✅ Get total items count
    $total_items = $this->get_total_answers_count($search_term);

    // ✅ Set pagination
    $this->set_pagination_args(array(
        'total_items' => $total_items,
        'per_page'    => $per_page,
    ));

    $this->_column_headers = array($this->get_columns(), array(), $this->get_sortable_columns());

    // ✅ Fetch and assign items
    $this->items = $this->get_answers($per_page, $current_page, $search_term);
}

private function get_total_answers_count($search_term = '') {
    global $wpdb;

    $cache_key = 'my_plugin_answers_count_' . md5(serialize([
        'question_id' => $this->question_id,
        'search_term' => $search_term,
    ]));

    $cache_group = 'my_plugin_answers';

    $count = wp_cache_get($cache_key, $cache_group);

    if (false === $count) {
        if (!empty($search_term)) {
            if (is_numeric($search_term)) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $count = $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(*) FROM {$wpdb->prefix}answers 
                         WHERE question_id = %d AND (id = %d OR answer LIKE %s)",
                        $this->question_id,
                        intval($search_term),
                        '%' . $wpdb->esc_like($search_term) . '%'
                    )
                );
            } else {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $count = $wpdb->get_var(
                    $wpdb->prepare(
                        "SELECT COUNT(*) FROM {$wpdb->prefix}answers 
                         WHERE question_id = %d AND answer LIKE %s",
                        $this->question_id,
                        '%' . $wpdb->esc_like($search_term) . '%'
                    )
                );
            }
        } else {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $count = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}answers 
                     WHERE question_id = %d",
                    $this->question_id
                )
            );
        }

        wp_cache_set($cache_key, $count, $cache_group, 300);
    }

    return $count;
}


private function get_answers($per_page, $current_page, $search_term = '') {
    global $wpdb;

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

    $cache_key = 'my_plugin_answers_' . md5(serialize([
        'question_id' => $this->question_id,
        'search_term' => $search_term,
        'per_page'    => $per_page,
        'current_page'=> $current_page,
    ]));

    $cache_group = 'my_plugin_answers';

    $results = wp_cache_get($cache_key, $cache_group);

    if (false === $results) {
        if (!empty($search_term)) {
            if (is_numeric($search_term)) {
                // Search by ID or answer match
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $results = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$wpdb->prefix}answers 
                         WHERE question_id = %d AND (id = %d OR answer LIKE %s) 
                         ORDER BY id DESC LIMIT %d OFFSET %d",
                        $this->question_id,
                        intval($search_term),
                        '%' . $wpdb->esc_like($search_term) . '%',
                        $per_page,
                        $offset
                    ),
                    ARRAY_A
                );
            } else {
                // Search by answer content
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $results = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$wpdb->prefix}answers 
                         WHERE question_id = %d AND answer LIKE %s 
                         ORDER BY id DESC LIMIT %d OFFSET %d",
                        $this->question_id,
                        '%' . $wpdb->esc_like($search_term) . '%',
                        $per_page,
                        $offset
                    ),
                    ARRAY_A
                );
            }
        } else {
            // No search term — fetch all
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}answers 
                     WHERE question_id = %d 
                     ORDER BY id DESC LIMIT %d OFFSET %d",
                    $this->question_id,
                    $per_page,
                    $offset
                ),
                ARRAY_A
            );
        }

        wp_cache_set($cache_key, $results, $cache_group, 300); // cache for 5 min
    }

    return $results;
}

    public function get_columns() {
        $columns = array(
            'cb'         => '<input type="checkbox" />',
            // 'id'         => 'ID',
            'answer'     => 'Answer',
            'status'  => 'Status',            
        );
        return $columns;
    }

    public function get_sortable_columns() {
        $sortable_columns = array(
            // 'id'     => array('id', false),
        );
        return $sortable_columns;
    }

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

 
public function column_default($item, $column_name) {
    switch ($column_name) {
        case 'answer':
            $answer_text = esc_html($item['answer']);
            $answer_id = intval($item['id']);

            $buttons = sprintf(
                '<span class="row-actions">
                    <a href="#" class="approve-answer" data-answer-id="%d">Approve</a> |
                    <span class="delete"><a href="#" class="delete-answer" data-answer-id="%d">Delete</a></span>
                </span>',
                $answer_id,
                $answer_id
            );

            return "<strong style='color:#2271b1;font-size:16px'>$answer_text</strong><br>$buttons";

        case 'status':
            return $item['approved'] == 1
                ? '<span style="color: green;">Approved</span>'
                : '<span style="color: red;">Pending</span>';

        default:
            return esc_html($item[$column_name]);
    }
}


}