<?php
// File: forums-list.php

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

add_action('wp_ajax_bcforum_delete_forum', 'bcforum_delete_forum');
function bcforum_delete_forum() {
    global $wpdb;

    if (!check_ajax_referer('bc-forum-nonce', 'security', false)) {
        wp_send_json_error('Invalid security nonce');
    }

    $forum_id = isset($_POST['forum_id']) ? intval($_POST['forum_id']) : 0;

    if ($forum_id > 0) {
        $cache_key = 'forum_' . $forum_id;
        wp_cache_delete($cache_key, 'forums');

        $forums_table = $wpdb->prefix . 'bc_forums';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $deleted = $wpdb->delete($forums_table, ['id' => $forum_id], ['%d']);

        if ($deleted !== false) {
            wp_send_json_success("Forum deleted successfully.");
        } else {
            wp_send_json_error("Failed to delete the forum.");
        }
    } else {
        wp_send_json_error("Invalid forum ID.");
    }

    wp_die();
}

class BCForum_Forums_List extends WP_List_Table {

    private $table_name;

    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'bc_forums';

        parent::__construct(array(
            'singular' => 'bc-forum',
            'plural'   => 'bc-forums',
            'ajax'     => false,
        ));
    }

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


    public function process_bulk_action() {
        if ($this->current_action() === 'delete') {
            check_admin_referer('bulk-' . $this->_args['plural']);

            $forum_ids = isset($_REQUEST['forum_id']) ? array_map('intval', $_REQUEST['forum_id']) : [];

            if (!empty($forum_ids)) {
                global $wpdb;
                $forums_table = $wpdb->prefix . 'bc_forums';

                foreach ($forum_ids as $forum_id) {
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                    $wpdb->delete($forums_table, ['id' => $forum_id], ['%d']);
                    wp_cache_delete('forum_' . $forum_id, 'forums');
                }
            }
        }
    }

    public function get_columns() {
        return [
            'cb'        => '<input type="checkbox" />',
            // 'id'        => __('ID', 'bc-forum'),
            'title'     => __('Forum Name', 'bc-forum'),
            'page_name' => __('Page Name', 'bc-forum'),
        ];
    }

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

    protected function column_default($item, $column_name) {
        switch ($column_name) {
            case 'title':
     
                return sprintf(
                    '<strong style="color:#2271b1;">%s</strong><span class="row-actions">%s</span>',
                    esc_html($item->title),
                    $this->get_action_buttons($item->id)
                );
    
            case 'page_name':
                return get_the_title($item->page_id);
        
            default:
                return isset($item->$column_name) ? esc_html($item->$column_name) : '';
        }
    }
    

    private function get_action_buttons($forum_id) {
        $edit_link = add_query_arg(['page' => 'bcforum-edit-forum', 'forum-id' => $forum_id], admin_url('admin.php'));
        $view_link = add_query_arg(['page' => 'bcforum', 'forum-id' => $forum_id,'forum_nonce' => wp_create_nonce('view_forum_nonce_action')], admin_url('admin.php'));

        return sprintf(
            '<span class="row-actions">
                <a href="%s">Edit</a> |
                <span class="delete"><a href="#" class="delete-forum" data-forum-id="%d">Delete</a></span> |
                <a href="%s">View</a>
            </span>',
            esc_url($edit_link),
            $forum_id,
            esc_url($view_link)
        );
    }
    public function prepare_items() {
        global $wpdb;
    
        $this->process_bulk_action();
    
        $columns  = $this->get_columns();
        $hidden   = [];
        $sortable = [];

    
        $this->_column_headers = [$columns, $hidden, $sortable];
    
        // Get search term from default input
        $search = '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset($_REQUEST['s']) && is_string($_REQUEST['s']) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $search = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) );
        }
    
        $query = '';
        if ( ! empty( $search ) ) {
            if ( is_numeric( $search ) ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $items = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$wpdb->prefix}bc_forums WHERE id = %d",
                        $search
                    )
                );
            } else {
                $like = '%' . $wpdb->esc_like( $search ) . '%';
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $items = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$wpdb->prefix}bc_forums WHERE title LIKE %s",
                        $like
                    )
                );
            }
        } else {
            $cache_key   = 'forums_list_all';
            $cache_group = 'forums_list';
    
            $items = wp_cache_get( $cache_key, $cache_group );
    
            if ( false === $items ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $items = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}bc_forums" );
                wp_cache_set( $cache_key, $items, $cache_group, 3600 );
            }
        }
    
        $this->items = $items;
    }
    
    public function display() {
        $this->search_box('Search', 'bc-forum');
        parent::display();
    }

}