<?php
/*
Plugin Name: BC Forum
Description: A BC Forum plugin for WordPress.
Author: Balaji Balagam
Version: 1.0.2
Text Domain: bc-forum
* License: GPL-2.0+
* Requires at least: 6.7
* Requires PHP: 7.4
*/

if (!defined('ABSPATH')) {
    // echo 'What are you trying to do?';
    exit;
}


require_once(plugin_dir_path(__FILE__) . 'includes/admin.php');
require_once(plugin_dir_path(__FILE__) . 'includes/frontend.php');

// Include the Questions-List class
require_once plugin_dir_path(__FILE__) . 'admin-questions-list.php';
require_once plugin_dir_path(__FILE__) . 'single-question-answers-list.php';
require_once plugin_dir_path(__FILE__) . 'forums-list.php';

$orange='#ff4101';
$yellow='#ffb611';
$green='#29870c';
$blue='#086c93';
$purple='#dfaada';


add_action('admin_enqueue_scripts', 'bcforum_enqueue_assets');

function bcforum_enqueue_assets($hook_suffix) {
    // Get the current screen object
    $current_screen = get_current_screen();    
    // Define the slugs of the admin pages where the assets should be loaded
    $plugin_pages = array(
        'question-data',
        'add-new-question',       
        'bcforum-edit-question',
       
    );    
    wp_enqueue_style(
        'bcforum-block-styles',
        plugin_dir_url(__FILE__) . 'bc-forum-block.css',
        array(),
        filemtime(plugin_dir_path(__FILE__) . 'bc-forum-block.css')
    );           

    // Check if the current screen base matches any of the defined plugin pages
    foreach ($plugin_pages as $page_slug) {
        if (strpos($current_screen->base, $page_slug) !== false) {            
          wp_enqueue_style(
                'bcforum-backend-styles',
                plugin_dir_url(__FILE__) . 'bc-forum-backend.css',
                array(),
                filemtime(plugin_dir_path(__FILE__) . 'bc-forum-backend.css')
            );
            return; 
        }
    }
}

add_action('init', 'bcforum_register_block');
// Register block
function bcforum_register_block() {
    register_block_type('bc-forum/block', array(
        'render_callback' => 'bcforum_render_shortcode',
    ));
}

// Render the shortcode
function bcforum_render_shortcode($attributes) {
    return do_shortcode('[bcforum_question_answers]');
}

add_action('wp_insert_post','bcforum_save_post', 10, 3);
// Save the block attributes
function bcforum_save_post($post_id, $post, $update) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if ($post->post_status != 'publish') {
        return;
    }
    global $wpdb;
    $blocks = parse_blocks($post->post_content);

    foreach ($blocks as $block) {
        if ($block['blockName'] === 'bc-forum/block') {
            $selected_forum = $block['attrs']['selectedForum'];

            // Update the page_id in bc_forums table
            $table_name = $wpdb->prefix . 'bc_forums';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->update(
                $table_name,
                array('page_id' => $post_id),
                array('id' => $selected_forum),
                array('%d'),  // Data format
                array('%d')   // Where format
            );
              // After update, clear related cache
            wp_cache_delete('forum_' . $selected_forum, 'my_plugin_forums');
            // error_log('Page ID: ' . $post_id . ' - Selected Forum ID: ' . $selected_forum);
        }
    }
}

class BCForum {

    protected $allowed_tags;

    public function __construct() {

        $this->allowed_tags = array(
            'form' => array(
                'action' => true,
                'method' => true,
                'class' => true,
                'id' => true,
            ),
            'input' => array(
                'type' => true,
                'name' => true,
                'value' => true,
                'id' => true,
                'class' => true,
                'placeholder' => true,
                'required' => true,
                'checked' => true,
            ),
            'textarea' => array(
                'name' => true,
                'rows' => true,
                'cols' => true,
                'placeholder' => true,
                'required' => true,
                'class' => true,
                'id' => true,
            ),
            'button' => array(
                'type' => true,
                'class' => true,
                'id' => true,
                'data-question-id' => true,
                'data-page'=>true,
                'data-logged-in'=>true,
                'data-login-url'=>true
            ),
            'img' => array(
                'src' => true,
                'alt' => true,
                'width' => true,
                'height' => true,
                'class' => true,
            ),
            'div' => array(
                'class' => true,
                'id' => true,
                'style' => true,
                'user_id'=>true,
            ),
            'p' => array('class' => true),
            'span' => array('class' => true, 'style' => true),
            'ul' => array('class' => true),
            'li' => array('class' => true),
            'abbr' => array('title' => true, 'class' => true),
            'h5' =>array(
                'class'=>true,
            ),
        );
        
        add_action('wp_enqueue_scripts', array($this, 'bcforum_load_assets'));
        add_action('admin_enqueue_scripts', array($this, 'bcforum_load_assets_backend'));        
        add_shortcode('bcforum_question_answers', array($this,'bcforum_question_archive_list'));

        add_action('admin_init', array($this, 'bcforum_handle_form_submission'));
        add_action('admin_init', array($this, 'bcforum_questions_table'));
        add_action('admin_init', array($this, 'bcforum_answers_table'));
        add_action('admin_init', array($this, 'bcforum_create_table'));
        // add_action('admin_init', array($this, 'create_taxanomies'));

        add_action('wp_ajax_bcforum_submit_comment', array($this, 'bcforum_submit_comment')); 
        add_action('wp_ajax_nopriv_bcforum_submit_comment', array($this, 'bcforum_submit_comment')); 

        add_action('wp_ajax_bcforum_loadmore_answers', array($this,'bcforum_loadmore_answers'));
        add_action('wp_ajax_nopriv_bcforum_loadmore_answers', array($this,'bcforum_loadmore_answers'));

        add_action('wp_ajax_bcforum_save_question', array($this,'bcforum_save_question'));
        add_action('wp_ajax_nopriv_bcforum_save_question', array($this,'bcforum_save_question'));

        add_action('wp_ajax_bcforum_get_questions', array($this,'bcforum_get_questions'));
        add_action('wp_ajax_nopriv_bcforum_get_questions', array($this,'bcforum_get_questions'));

        add_action('admin_menu', array($this, 'add_admin_menu'));

        add_action('wp_ajax_bcforum_toggle_like', array($this,'bcforum_toggle_like'));
        add_action('wp_ajax_nopriv_bcforum_toggle_like', array($this,'bcforum_toggle_like'));

        add_action('admin_init', array($this, 'create_settings_section'));

        add_action( 'wp_ajax_bcforum_get_titles',  array($this,'bcforum_block_get_titles' ));
        add_action( 'wp_ajax_nopriv_bcforum_get_titles',  array($this,'bcforum_block_get_titles') );       
        
    }
    
    function bcforum_block_get_titles() {
    global $wpdb;

    $cache_key = 'bc_forums_all';
    $cache_group = 'my_plugin_forums';
    // Try to get cached forums
    $bcforums = wp_cache_get($cache_key, $cache_group);

    if (false === $bcforums) {
        // Cache miss, query the database
        $bcforums_table = $wpdb->prefix . 'bc_forums';
    
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $bcforums = $wpdb->get_results($wpdb->prepare(
            "SELECT id, title FROM %i ORDER BY id DESC",$bcforums_table            
        ));

        // Save the result to cache for 5 minutes
        wp_cache_set($cache_key, $bcforums, $cache_group, 300);
    }

    // Send response
    wp_send_json_success($bcforums);
}
    function bcforum_toggle_like() {
        check_ajax_referer('bc-forum-nonce', 'security');
        global $wpdb;
        $question_id = isset($_POST['question_id']) ? intval($_POST['question_id']) : 0;
        $user_id     = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;

        if (!$question_id || !$user_id) {
        wp_send_json_error('Invalid request.');
        }

        $cache_key = 'question_likes_' . $question_id;
        $cache_group = 'my_plugin_questions';

        // Try to get likes from cache
        $likes = wp_cache_get($cache_key, $cache_group);

        if (false === $likes) {
        // Cache miss, query the database
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $question = $wpdb->get_row($wpdb->prepare(
            "SELECT likes FROM {$wpdb->prefix}questions WHERE id = %d",
            $question_id
        ));

        if ($question && $question->likes) {
            $likes = explode(',', $question->likes);
        } else {
            $likes = [];
        }

        // Clean up empty values
        $likes = array_filter($likes, function($value) {
            return !is_null($value) && $value !== '';
        });

        // Cache it for future
        wp_cache_set($cache_key, $likes, $cache_group, 300); // cache for 5 minutes
         }

        if (in_array($user_id, $likes)) {
            // User already liked, so unlike
            $likes = array_diff($likes, array($user_id));
            $liked = false;
        } else {
            // User hasn't liked yet, so like
            array_push($likes, $user_id);
            $liked = true;
        }

        // Convert the array back to a comma-separated string
        $likes_string = implode(',', $likes);

        // Update the database
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->update(
            "{$wpdb->prefix}questions",
            array('likes' => $likes_string),
            array('id' => $question_id),
            array('%s'),
            array('%d')
        );

          // Clear the cache because likes changed
        wp_cache_delete($cache_key, $cache_group);
        // Get the updated like count
        $likes_count = count($likes);

        wp_send_json_success(array('likes' => $likes_count, 'liked' => $liked));
    }

    public function bcforum_get_questions() {
    check_ajax_referer('bc-forum-nonce', 'security');

    global $wpdb;
    $questions_table = $wpdb->prefix . 'questions';

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

    if ($questionId) {
        $cache_key = 'question_' . $questionId;
        $cache_group = 'bc_questions';

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

        if ($question === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $question = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}questions WHERE id = %d",$questionId));

            if (!empty($question)) {
                wp_cache_set($cache_key, $question, $cache_group, 3600); // Cache for 1 hour
            }
        }

        if (!empty($question)) {
           echo wp_kses($this->single_question_html($question[0]),$this->allowed_tags);
        } else {
            echo '<p>No Questions Found</p>';
        }
    } else {
        echo '<p>Kindly Please Login</p>';
    }

    wp_die();
}
    public function add_admin_menu()
    {
        add_menu_page(
            'BC Forums',
            'BC Forums',
            'manage_options',
            'bcforums',            
            array($this, 'display_bcforums'),
            'dashicons-admin-generic'
        );   
        add_submenu_page(
            'null',
            'BC Forums',
            'BC Forums',
            'manage_options',
            'bcforum',
            array($this, 'display_bcforum_admin_page')
        );
        add_submenu_page(
            'null',
            'Add New Question',
            'Add New Question',
            'manage_options',
            'add-new-question',
            array($this, 'display_bcforum_new_question_page')
        );
        add_submenu_page(
            'bcforums',
            'Add New Forum',
            'Add New Forum',
            'manage_options',
            'add-new-forum',
            array($this, 'display_add_new_forum')
        );
        add_submenu_page(
            'null',
            'Edit Question',
            'Edit Question',
            'manage_options',
            'bcforum-edit-question',
            array($this, 'display_edit_question_page')
        );       
        add_submenu_page(
            'bcforums',
            'Question Settings',
            'Settings',
            'manage_options',
            'bcforums-settings',
            array($this, 'display_question_settings_page')
        );
        add_submenu_page(
            'null',
            'View Question',
            'View Question',
            'manage_options',
            'bcforum-view-question',
            array($this, 'bcforum_view_question')
        );
        add_submenu_page(
            'null',
            'View Forum',
            'View Forum',
            'manage_options',
            'bcforum-view-forum',
            array($this, 'bcforum_view_forum')
        );
        add_submenu_page(
            'null',
            'Edit Forum',
            'Edit Forum',
            'manage_options',
            'bcforum-edit-forum',
            array($this, 'display_bcforum_edit_forum')
        );
    }  

public function bcforum_view_forum() {
    check_ajax_referer('bc-forum-nonce', 'security');
    global $wpdb;
    $table_name = $wpdb->prefix . 'questions';
    $forum_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    $cache_key = 'forum_questions_' . $forum_id;
    $cache_group = 'bc_forum_questions';

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

    if ($questions === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $questions = $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM %i WHERE forum_id = %d",$table_name,$forum_id)
        );

        wp_cache_set($cache_key, $questions, $cache_group, 3600); // Cache for 1 hour
    }
    ?>
<div class="wrap">
    <h1>Forum Questions</h1>
    <?php if (!empty($questions)) :?>
    <table class="widefat fixed" cellspacing="0">
        <thead>
            <tr>
                <th class="manage-column column-id" scope="col">ID</th>
                <th class="manage-column column-question" scope="col">Question</th>
                <th class="manage-column column-actions" scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($questions as $question) :?>
            <tr>
                <td><?php echo esc_html($question->id);?></td>
                <td><?php echo esc_html($question->question_title);?></td>
                <td>
                    <a href="#" class="button">Edit</a>
                    <a href="#" class="button">Delete</a>
                </td>
            </tr>
            <?php endforeach;?>
        </tbody>
    </table>
    <?php else :?>
    <p>No questions found for this forum.</p>
    <?php endif;?>
    <a href="<?php echo esc_url(admin_url('admin.php?page=bcforums'));?>" class="button">Back to Forums</a>
</div>
<?php
}


    public function display_bcforum_edit_forum() {

    global $wpdb;
    $table_name = $wpdb->prefix .'bc_forums';

     // Validate and sanitize forum-id from GET
     $forum_id = isset($_GET['forum-id']) ? intval($_GET['forum-id']) : 0;
     if (!$forum_id) {
         echo '<div class="notice notice-error"><p>Invalid Forum ID.</p></div>';
         return;
     }

    // Try to get cached forum data
    $cache_key = 'forum_' . $forum_id;
    $cache_group = 'bc_forums';
    $forum = wp_cache_get($cache_key, $cache_group);

    if ($forum === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $forum = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d",$table_name,$forum_id));
        if ($forum) {
            wp_cache_set($cache_key, $forum, $cache_group, 3600); // Cache for 1 hour
        }
    }

    if (!$forum) {
        return;
    }

    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_forum'])) {

        if (!isset($_POST['forum_title'])) {
            return;
        }
        check_admin_referer('edit_forum_nonce_action', 'edit_forum_nonce');

        $forum_title = sanitize_text_field(wp_unslash($_POST['forum_title']));
        $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;

        // Update the forum
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $updated = $wpdb->update(
            $table_name,
            array(
                'title' => $forum_title,
                'page_id' => $page_id,
            ),
            array('id' => $forum_id),
            array('%s', '%d'),
            array('%d')
        );
        // Invalidate cache
        wp_cache_delete($cache_key, $cache_group);

        if ($updated !== false) {
            echo '<div class="notice notice-success"><p>Forum updated successfully!</p></div>';
        } else {
            echo '<div class="notice notice-error"><p>Failed to update the Forum.</p></div>';
        }        
    }
    if (!$forum) {
        echo '<div class="notice notice-error"><p>Forum not found.</p></div>';
        return;
    }
?>
<div class="wrap">
    <h1>Edit Forum</h1>
    <?php $this->edit_forum($forum);?>
</div>
<?php
}

public function edit_forum($forum = null){
?>
<form method="post" action="">
    <?php wp_nonce_field('edit_forum_nonce_action', 'edit_forum_nonce');?>
    <table class="form-table">
        <tr>
            <th scope="row"><label for="forum_title">Forum Title</label></th>
            <td><input name="forum_title" type="text" id="forum_title" value="<?php echo esc_attr($forum->title);?>"
                    class="regular-text" required /></td>
        </tr>
        <tr>
            <th scope="row"><label for="page_id">Select Page</label></th>
            <td>
                <select name="page_id" id="page_id" required>
                    <?php
                             $pages = get_pages();
                                foreach ($pages as $page) {
                                    $selected = $page->ID == $forum->page_id ? 'selected="selected"' : '';
                                    echo '<option value="' . esc_attr($page->ID) . '" ' . esc_attr($selected) . '>' . esc_html($page->post_title) . '</option>';
                                    
                                }
                            ?>
                </select>
            </td>
        </tr>
    </table>
    <p class="submit">
        <input type="submit" name="submit_forum" id="submit_forum" class="button button-primary" value="Update Forum">
    </p>
</form>
<?php

}


    public function display_add_new_forum() {
        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_forum'])) {
            if (!isset($_POST['forum_title'])) {
            return;
            }
            if (!isset($_POST['add_new_forum_nonce']) || 
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['add_new_forum_nonce'])), 'add_new_forum_nonce_action') ) {
                wp_die('Security check failed');
            }
            $forum_title = sanitize_text_field(wp_unslash($_POST['forum_title']));
             $page_id = isset($_POST['page_id']) ? intval(wp_unslash($_POST['page_id'])) : 0;

            global $wpdb;
            $table_name = $wpdb->prefix . 'bc_forums';

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $inserted = $wpdb->insert(
                $table_name,
                array(
                    'title' => $forum_title,
                    'page_id' => $page_id,
                    // 'page_id' will use the default value
                ),
                array(
                    '%s',
                    '%d',
                )
            );
            if ($inserted !== false) {
                echo '<div class="notice notice-success"><p>Forum added successfully!</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>Failed to add the Forum.</p></div>';
            }     
           
        }
        ?>
<div class="wrap">
    <h1>Add New Forum</h1>
    <form method="post" action="">
        <?php wp_nonce_field( 'add_new_forum_nonce_action', 'add_new_forum_nonce' );?>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="forum_title">Forum Title</label>
                </th>
                <td>
                    <input name="forum_title" type="text" id="forum_title" value="" class="regular-text" required />
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="page_id">Select Page or Post</label>
                </th>
                <td>
                    <select name="page_id" id="page_id" required>
                        <?php
                                // Fetch all pages and posts
                                $pages = get_pages();
                                $posts = get_posts(array('numberposts' => -1));
                                
                                // Merge pages and posts
                                $items = array_merge($pages, $posts);
                                
                                foreach ($items as $item) {
                                    // Check if it's a post or page
                                    $is_page = $item instanceof WP_Post && $item->post_type == 'page';
                                    
                                    // Determine if this item should be selected
                                    $selected = $item->ID == $forum->page_id ? 'selected="selected"' : '';
                                    
                                    // Output the option element
                                    echo '<option value="' . esc_attr($item->ID) . '" ' . esc_attr($selected) . '>' . esc_html($item->post_title) . ' (' . ($is_page ? 'Page' : 'Post') . ')</option>';
                                }
                                ?>
                    </select>
                </td>
            </tr>

        </table>
        <p class="submit">
            <input type="submit" name="submit_forum" id="submit_forum" class="button button-primary" value="Add Forum">
        </p>
    </form>
</div>
<?php
    }


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

    // Set cache key and group
    $cache_key = 'bc_forums_count';
    $cache_group = 'bc_forum_data';

    // Try to get from cache
    $total_forums = wp_cache_get($cache_key, $cache_group);

    if ($total_forums === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $total_forums = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}bc_forums");

        // Store in cache for 1 hour
        wp_cache_set($cache_key, $total_forums, $cache_group, 3600);
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset($_REQUEST['page']) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : '';

    ?>
<div class="wrap">
    <h1>Forums List</h1>
    <hr class="wp-header-end">
    <ul class="subsubsub">
        <li class="all">
            <a href="admin.php?page=bcforums" class="current" aria-current="page">
                All <span class="count">(<?php echo esc_html($total_forums);?>)</span>
            </a>
        </li>
    </ul>

    <form method="get">
        <input type="hidden" name="page" value="<?php echo esc_attr( $page ); ?>">

        <?php 
            $forumsListTable = new BCForum_Forums_List();
            $forumsListTable->prepare_items();
            $forumsListTable->display();                    
            ?>
    </form>

</div>
<?php
}

    public function create_settings_section(){
        // Register a new setting for "bcforums-settings" page.        

        register_setting('bcforums-settings', 'bcforum_label_name', 'sanitize_text_field');  
        
        // Add settings section.
        add_settings_section(
            'settings_section',
            __('Settings Section', 'bc-forum'),
            '__return_null',
            'bcforums-settings'
        );
        // Add settings field.
        add_settings_field(
            'bcforum_label_name',
            __('Label for Ask a Question Button', 'bc-forum'),
            array($this, 'bcforum_label_name'),
            'bcforums-settings',
            'settings_section'
        );
    }

    public function bcforum_label_name() {
        $bcforum_label_name = get_option('bcforum_label_name');
        echo '<input type="text" name="bcforum_label_name" value="' . esc_attr($bcforum_label_name) . '" />';
    }

public function bcforum_view_question() {
    global $wpdb;    
  
        $question_id = isset($_GET['question_id']) ? intval($_GET['question_id']) : 0;
    
        if (!$question_id || !wp_verify_nonce(isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '', 'view_question_' . $question_id)) {
            wp_die('Security check failed');
        }
        
        // Cache keys
        $question_key = "question_{$question_id}";
        $answers_key = "answers_q_{$question_id}";
        $count_key   = "answer_count_q_{$question_id}";
        $cache_group = 'bc_forum_data';

        // Try to get cached data
        $question = wp_cache_get($question_key, $cache_group);
        if ($question === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $question = $wpdb->get_row(
                $wpdb->prepare("SELECT * FROM {$wpdb->prefix}questions WHERE id = %d", $question_id),
                ARRAY_A
            );
            wp_cache_set($question_key, $question, $cache_group, 3600);
        }

        $answers = wp_cache_get($answers_key, $cache_group);
        if ($answers === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $answers = $wpdb->get_results(
                $wpdb->prepare("SELECT * FROM {$wpdb->prefix}answers WHERE question_id = %d", $question_id),
                ARRAY_A
            );
            wp_cache_set($answers_key, $answers, $cache_group, 3600);
        }

        $totalAnswersCount = wp_cache_get($count_key, $cache_group);
        if ($totalAnswersCount === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $totalAnswersCount = $wpdb->get_var(
                $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}answers WHERE question_id = %d", $question_id)
            );
            wp_cache_set($count_key, $totalAnswersCount, $cache_group, 3600);
        }

        
        $page = isset($_REQUEST['page']) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : '';
        $nonce = wp_create_nonce( 'view_question_' . $question_id );


        $all_url = add_query_arg(
            array(
                'page'         => 'bcforum-view-question',
                'question_id'     => $question_id,
                '_wpnonce'  => $nonce,
            ),
            admin_url( 'admin.php' )
        );

        if ($question) {
            ?>
<div class="wrap">
    <h1>Question : <?php echo esc_html(ucfirst($question['question_title']));?></h1>
    <h1 class="wp-heading-inline">All Comments</h1>
    <a href="javascript:history.back()" class="page-title-action">Go to Questions</a>
    <hr class="wp-header-end">
    <ul class="subsubsub">
        <li class="all">
            <a href="<?php echo esc_url( $all_url ); ?>" class="current" aria-current="page">
                All <span class="count">(<?php echo esc_html($totalAnswersCount);?>)</span>
            </a>
        </li>
    </ul>
    <form method="post">
        <?php wp_nonce_field( 'view_question_nonce_action', 'view_question_nonce' );?>
        <?php 
                        $answers_list = new BCForum_Single_Question_Answers_List($question_id);
                        $answers_list->prepare_items();
                        $answers_list->display();
                    ?>
    </form>
</div>
<?php
        } else {
            echo '<p>Invalid question ID.</p>';
        }   
}   

public function display_question_settings_page() {
    $success = false;

    // Handle form submission manually
    if (
        isset($_POST['save_custom_label']) &&
        isset($_POST['custom_label_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['custom_label_nonce'])), 'custom_label_action')
    ) {
        // You can save your custom options here with update_option() or any logic
        // Example: update_option('my_custom_option', sanitize_text_field($_POST['my_option']));
        $success = true;
    }
    ?>
<div class="wrap">
    <h2><?php esc_html_e('Settings', 'bc-forum');?></h2>

    <?php if (isset($_GET['settings-updated']) && $_GET['settings-updated'] === 'true') : ?>
    <div id="message" class="updated notice is-dismissible">
        <p><strong><?php esc_html_e('Settings saved successfully.', 'bc-forum');?></strong></p>
    </div>
    <?php endif;?>

    <p><?php esc_html_e('Welcome to the Question Settings page. Here you can configure various options for your questions.', 'bc-forum');?>
    </p>

    <h3><?php esc_html_e('Instructions:', 'bc-forum');?></h3>
    <ol>
        <li><?php esc_html_e('You Need to add Gutenberg block for Question Form on frontend ', 'bc-forum');?><strong>"BC
                Forum"</strong>.</li>
        <li><strong><?php esc_html_e('OR', 'bc-forum');?></strong>
            <?php esc_html_e('You Need to add shortcode for Question Archive on frontend ', 'bc-forum');?><strong>"[bcforum_question_answers]"</strong>.
        </li>
    </ol>

    <form method="post" action="options.php">
        <?php wp_nonce_field('custom_label_action', 'custom_label_nonce');?>
        <?php
            settings_fields('bcforums-settings');
            do_settings_sections('bcforums-settings');
            submit_button();
            ?>
    </form>
</div>
<?php
}


public function display_edit_question_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'questions';

    if (
        !isset($_GET['question_id'], $_GET['question_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['question_nonce'])), 'view_question_nonce_action')
    ) {
        wp_die('Invalid request. Security check failed.');
    }

    $question_id = intval($_GET['question_id']);
    $cache_group = 'bc_forum_data';
    $cache_key   = "question_{$question_id}";

    // Handle form submission
    if (
        isset($_POST['update_question']) &&
        isset($_POST['edit_question_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['edit_question_nonce'])), 'edit_question_nonce_action')
    ) {
        $question_title = isset($_POST['question_title']) ? sanitize_text_field(wp_unslash($_POST['question_title'])) : '';
        $question_content = isset($_POST['question_content']) ? sanitize_textarea_field(wp_unslash($_POST['question_content'])) : '';

        // Update the question
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $updated = $wpdb->update(
            $table_name,
            array(
                'question_title' => $question_title,
                'description' => $question_content,
            ),
            array('id' => $question_id),
            array('%s', '%s'),
            array('%d')
        );

        // Invalidate cache
        wp_cache_delete($cache_key, $cache_group);

        if ($updated !== false) {
            echo '<div class="notice notice-success"><p>Question updated successfully!</p></div>';
        } else {
            echo '<div class="notice notice-error"><p>Failed to update the question.</p></div>';
        }
    }

    // Try to get the question from cache
    $question = wp_cache_get($cache_key, $cache_group);
    if ($question === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $question = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM %i WHERE id = %d",$table_name,$question_id)
        );

        // Cache for 1 hour if found
        if ($question) {
            wp_cache_set($cache_key, $question, $cache_group, 3600);
        }
    }

    if (!$question) {
        echo '<div class="notice notice-error"><p>Question not found.</p></div>';
        return;
    }

    ?>
<div class="wrap">
    <h2>Edit Question</h2>
    <?php $this->edit_question_form($question);?>
</div>
<?php
}



    public function bcforum_handle_form_submission() {

        if (isset($_POST['submit_question'])) {
            if (!isset($_POST['add_question_nonce']) || 
                ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['add_question_nonce'])), 'add_question_nonce_action') ) {
                wp_die('Security check failed');
            }
            global $wpdb;
            $table_name = $wpdb->prefix . 'questions';

            // Handle form submission
            $question_title = isset($_POST['question_title']) ? sanitize_text_field(wp_unslash($_POST['question_title'])) : '';
            $description = isset($_POST['question_content'])?sanitize_textarea_field(wp_unslash($_POST['question_content'])):'';
           
            $forum_id = isset($_POST['forum_type']) ? intval($_POST['forum_type']) : 0;    


            // Get the current user ID and user information
            $user_id = get_current_user_id();
            $user_meta = get_user_meta($user_id);
            $first_name = isset($user_meta['first_name'][0]) ? $user_meta['first_name'][0] : '';
            $last_name = isset($user_meta['last_name'][0]) ? $user_meta['last_name'][0] : '';
            $author_name = trim($first_name . ' ' . $last_name);

            $current_user = wp_get_current_user();
            if (empty($author_name)) {
               $author_name = $current_user->display_name;
            }
            // Get the current timestamp
            $created_at = current_time('mysql');

            // Insert data into the questions table
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->insert($table_name, array(
                'question_title' => $question_title,
                'description' => $description,
                'user_id' => get_current_user_id(),
                'author' => $author_name,                
                'forum_id' => $forum_id,
                'created_at' => $created_at
            )); 
            // Redirect to the desired page
            wp_redirect(admin_url('admin.php?page=bcforums'));
            exit; 
        }
    }
    
    public function display_bcforum_new_question_page() {  
        ?>
<div class="wrap">
    <h2>Add New Question</h2>
    <?php
            $this->question_form();
            ?>
</div>
<?php
    }
    
    public function display_bcforum_admin_page() {
        if (!class_exists('WP_List_Table')) {
            // echo 'Error: WP_List_Table class not found. Please make sure to include it.';
            return;
        }

        global $wpdb;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $forum_id = isset($_GET['forum-id']) ? intval($_GET['forum-id']) : 0;

        $forum_nonce = isset($_GET['forum_nonce']) ? sanitize_text_field(wp_unslash($_GET['forum_nonce'])) : '';

        if (!$forum_id || !wp_verify_nonce($forum_nonce, 'view_forum_nonce_action')) {
            wp_die('Invalid request');
        }
        $forum_name = '';

        if ( $forum_id ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $forum_name = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT title FROM {$wpdb->prefix}bc_forums WHERE id = %d",
                    $forum_id
                )
            );
        }

        $current_user_id = get_current_user_id();

        $cache_group = 'bc_forum_data';
        $cache_key_total = "forum_{$forum_id}_total_questions";
        $cache_key_user  = "forum_{$forum_id}_user_{$current_user_id}_questions";

        // Try to get cached values
        $totalQuestionsCount = wp_cache_get($cache_key_total, $cache_group);
        if ($totalQuestionsCount === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $totalQuestionsCount = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}questions WHERE forum_id = %d",
                $forum_id
            ));
            wp_cache_set($cache_key_total, $totalQuestionsCount, $cache_group, 3600);
        }

        $userQuestionsCount = wp_cache_get($cache_key_user, $cache_group);
        if ($userQuestionsCount === false) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $userQuestionsCount = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}questions WHERE forum_id = %d AND user_id = %d",
                $forum_id,
                $current_user_id
            ));
            wp_cache_set($cache_key_user, $userQuestionsCount, $cache_group, 3600);
        }

        $page = isset($_REQUEST['page']) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : '';
        $forum_id = isset($_GET['forum-id']) ? intval( wp_unslash( $_GET['forum-id'] ) ) : '';
        $forum_nonce = isset($_GET['forum_nonce']) ? sanitize_text_field( wp_unslash( $_GET['forum_nonce'] ) ) : '';

        $all_url = add_query_arg(
            array(
                'page'         => 'bcforum',
                'forum-id'     => $forum_id,
                'forum_nonce'  => $forum_nonce,
            ),
            admin_url( 'admin.php' )
        );
       
        ?>
<div class="wrap">
    <h1 class="wp-heading-inline">
        <?php echo esc_html( $forum_name ? $forum_name : 'All Questions' ); ?>
    </h1>
    <a href="<?php echo esc_url(admin_url('admin.php?page=add-new-question'));?>" class="page-title-action">Add New
        Question</a>

    <hr class="wp-header-end">
    <ul class="subsubsub">
        <li class="all">
            <a href="<?php echo esc_url( $all_url ); ?>" class="current" aria-current="page">
                All <span class="count">(<?php echo esc_html($totalQuestionsCount);?>)</span>
            </a>
        </li>
    </ul>

    <form method="get">
        <input type="hidden" name="page" value="<?php echo esc_attr( $page ); ?>" />
        <input type="hidden" name="forum-id" value="<?php echo esc_attr( $forum_id ); ?>" />
        <input type="hidden" name="forum_nonce" value="<?php echo esc_attr( $forum_nonce ); ?>" />

        <?php
                $list_table = new BCForum_Questions_List();
                $list_table->prepare_items();
                $list_table->display();
                ?>
    </form>

</div>
<?php
    }
       
    public function edit_question_form($question = null){
    ?>
<form id="question_submission_form" class="question-form" method="post">
    <div class="form-group">
        <label for="question_title">Title</label>
        <input type="text" name="question_title"
            value="<?php echo esc_attr($question ? $question->question_title : '');?>" required><br>
    </div>
    <div class="form-group">
        <label for="description">Description</label>
        <textarea name="question_content"
            required><?php echo esc_html(htmlspecialchars($question->description));?></textarea><br>
    </div>
    <?php wp_nonce_field( 'edit_question_nonce_action', 'edit_question_nonce' );?>

    <div class="form-group">
        <input type="submit" name="<?php echo $question ? 'update_question' : 'submit_question';?>"
            value="<?php echo $question ? 'Update' : 'Submit';?>">
    </div>
</form>
<?php
    }

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

    $cache_key = 'bc_forums_dropdown';
    $cache_group = 'bc_forums';

    // Try to get cached forums
    $forums = wp_cache_get($cache_key, $cache_group);

    if ($forums === false) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $forums = $wpdb->get_results("SELECT id, title FROM  {$wpdb->prefix}bc_forums");
        // Cache the results for 1 hour
        wp_cache_set($cache_key, $forums, $cache_group, 3600);
    }
    // Check if the form is being displayed in the frontend or not
    $is_frontend = !is_admin();
    ?>
<form id="question_submission_form" class="question-form" method="post">
    <div class="form-group">
        <label for="question_title">Title</label>
        <input type="text" name="question_title" required>
        <div id="question_title_error" class="error-message">
            <?php esc_html_e('Title Field is Mandatory.','bc-forum');?>
        </div>
    </div>

    <div class="form-group">
        <label for="description">Description</label>
        <textarea name="question_content" required></textarea>
        <div id="question_content_error" class="error-message">
            <?php esc_html_e('Description Field is Mandatory.','bc-forum');?>
        </div>
    </div>

    <input type="hidden" name="current_page_id" value="<?php echo esc_attr(get_the_ID());?>">

    <?php if (!$is_frontend): ?>
    <div class="form-group">
        <label for="forum_type">Type of Forum</label>
        <select name="forum_type" required>
            <option value=""><?php esc_html_e('Select a forum','bc-forum');?></option>
            <?php foreach ($forums as $forum) :?>
            <option value="<?php echo esc_attr($forum->id);?>">
                <?php echo esc_html($forum->title);?>
            </option>
            <?php endforeach;?>
        </select>
        <div id="forum_type_error" class="error-message">
            <?php esc_html_e('Forum Type is Mandatory.','bc-forum');?>
        </div>
    </div>
    <?php endif;?>

    <?php wp_nonce_field('add_question_nonce_action', 'add_question_nonce');?>

    <div class="form-group">
        <input type="submit" name="submit_question" value="Submit">
    </div>
</form>
<?php
}

    
    public function question_form_shortcode() {
        ob_start();
        $is_logged_in = is_user_logged_in();
        $login_url = wp_login_url();   
        $default_label_name = __('Ask a Question','bc-forum');
        $bcforum_label_name = get_option('bcforum_label_name');
        $bcforum_label_name = !empty($bcforum_label_name) ? $bcforum_label_name : $default_label_name;

        ?>
<div class="bc-ask-question-container">
    <div class="bc_forum_ask_question">
        <button id="bc_forum_question_form" data-logged-in="<?php echo $is_logged_in ? 'true' : 'false';?>"
            data-login-url="<?php echo esc_url($login_url);?>">
            <?php echo esc_html($bcforum_label_name);?>
        </button>

    </div>
    <div id="spinner_que" class="spinner"></div>
    <div id="question_modal">
        <div id="question_modal_content">
            <h5><?php echo esc_html('Ask a Question','bc-forum');?><span class="close">&times;</span></h5>
            <?php
                    $this->question_form();
                    ?>
        </div>
    </div>
</div>
<?php
        return ob_get_clean();
    }
    public function single_question_php($question){
        // Retrieve author information
        $author_id = $question->user_id;
        $user_info = get_userdata($author_id);
        $question_id = $question->id;

        $cache_key = 'single_question_html_' . $question_id;
        $cache_group = 'bc_forum_question';
        // Try to get cached HTML
        $cached_html = wp_cache_get($cache_key, $cache_group);
        if ($cached_html !== false) {
            return $cached_html;
        }    
        
         $avatar_url = get_avatar_url($author_id, array('size' => 45));   
         $user_meta = get_user_meta($author_id);
         $user_firstname = isset($user_info->first_name) ? $user_info->first_name : '';
         $user_lastname = isset($user_info->last_name) ? $user_info->last_name : '';
         $user_nickname = isset($user_meta['nickname'][0]) ? $user_meta['nickname'][0] : '';
         $created_time = isset($question->created_at) ? gmdate('F j, Y, g:i A', strtotime($question->created_at)) : '';

         $user_ID = get_current_user_id(); 
         
         if (!empty($user_firstname) || !empty($user_lastname)) {
             $initials = substr($user_firstname, 0, 1) . substr($user_lastname, 0, 1);
         } elseif (!empty($user_nickname)) {
             $initials = substr($user_nickname, 0, 2);
         } else {
             $initials = '';
         }
              
         global $wpdb; 
         $exclude_ids=[];
   
         if(count($exclude_ids)>0){
         $exclude_ids_str = implode(',', array_map('intval', $exclude_ids));
        //  Query with exclusion
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
         $answers = $wpdb->get_results($wpdb->prepare("
             SELECT * 
             FROM {$wpdb->prefix}answers 
             WHERE question_id = %d 
             AND parent = 0 
             AND id NOT IN (%d) 
             ORDER BY question_id DESC",$exclude_ids_str, $question_id,));
             
         }else{
             // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
             $answers = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}answers WHERE question_id = %d AND parent = 0 AND approved = 1 ORDER BY question_id DESC", $question_id));
         }
         $count_answers = count($answers); 
         // Query to get the count of all answers for the specific question_id
         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
         $answers_count = $wpdb->get_var($wpdb->prepare("
         SELECT COUNT(*) 
         FROM {$wpdb->prefix}answers 
         WHERE question_id = %d 
         AND (approved = 1 OR user_id = %d)", 
         $question_id,
         $user_ID
         ));
     
         // Example serialized array
         $likesArray = $question->likes;   
         $questions_table = $wpdb->prefix . 'questions';
         // Retrieve the likes column for the given question ID
         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
         $likes = $wpdb->get_var($wpdb->prepare("SELECT likes FROM %i WHERE id = %d",$questions_table, $question_id));
         $likeCount = 0;
         // Check if likes is not empty, then count the number of entries
         if (!empty($likes)) {
             $likes_array = explode(',', $likes);
             $likeCount = count($likes_array);
         }

         $liked_class = in_array($user_ID, explode(',', $likes ?? '')) ? 'liked' : '';  
    	 wp_cache_set($cache_key, $cache_group, 3600);
         
         return [$author_id, $liked_class, $likeCount, $initials, $answers_count,$user_ID,$user_nickname];
        
    }

public function single_question_html($question){    
// ob_start();        
$question_id = $question->id;
$single_quesiton_sub_html = $this->single_question_php($question);  

$avatar_image = get_avatar_url($single_quesiton_sub_html[0]);
$avatar_image_explode = explode("?", $avatar_image);
$avatar_image_explode1 = explode("/", $avatar_image_explode[0]); 

$html ='';  
$html .='<div class="question-answer-loadmore">' . "\n";
$html .='<div class="question-answer">' . "\n";
$html .='<div class="main-question">' . "\n";
$html .='<div class="single-question">' . "\n";
$html .= '<div class="question-avatar">' . "\n";
if (false) { // Replace `false` with your real condition
    $avatar_url = esc_url(get_avatar_url($single_quesiton_sub_html[0], array('size' => 30)));
    $html .= get_avatar($single_quesiton_sub_html[0], 30, '', esc_attr__('Avatar', 'bc-forum'), array(
        'class' => 'custom-avatar-class',
        'width' => 30,
        'height' => 30,
    )) . "\n";
    
} else {
    if ($single_quesiton_sub_html[3]) {
        $html .= '<div class="avatar-initials">' . esc_html($single_quesiton_sub_html[3]) . '</div>' . "\n";
    }
}
$html .= '</div>' . "\n";

$html .='<div class="question-content">' . "\n";
$html .='<div class="question">' . "\n";
$html .='<h5>' . "\n";
$html .= esc_html(ucfirst($question->question_title));    
if ($question->approved == 0) {
    $html .='<abbr title="This question is waiting for approval." class="no-dotted-line">' . "\n";
    $html .='<span class="approval-pending">' . "\n";
    $html .='Approval Pending..';
    $html .='</span>' . "\n";
    $html .='</abbr>' . "\n";
}                      
$html .='</h5>' . "\n"; 
if (is_user_logged_in()) {
    $html .='<div class="comment-toggle">' . "\n";
            $html .='<span class="dashicons dashicons-admin-comments">' . "\n";
            $html .='</span>' . "\n";
            $html .='<span>' . "\n";
            $html .='Reply..';
            $html .='</span>' . "\n";
    $html .='</div>' . "\n";
 }                     
$html .='</div>' . "\n";
$html .='<div class="description"> ' . "\n";
$html .='<span class="sub-comment-content">' . "\n";
$html .='<p>' . "\n";
$html .=nl2br(esc_html(ucfirst($question->description))); 
$html .='</p> ' . "\n";
$html .='</span>' . "\n";
$html .='</div>' . "\n";
$html .='</div>' . "\n";      
$html .='</div>' . "\n";


$html .= '<div class="author-datetime-details">' . "\n";

$html .= '<div id="' . esc_attr($question_id) . '" class="answers-button comments">' . "\n";


$comment_img_url = plugin_dir_url(__FILE__) . 'assets/comment.png';
$html .= sprintf(
    '<span style="display:inline-block; width:20px; height:20px; background-image:url(%s); background-size:cover;" role="img"></span>',
    esc_url($comment_img_url)
);

$html .= '<p id="count_answers_' . esc_attr($question_id) . '" class="count_answers">' . esc_html($single_quesiton_sub_html[4]) . ' ' . esc_html($single_quesiton_sub_html[4] === 1 ? 'comment' : 'Comments') . '</p>' . "\n";
$html .= '<div id="spinner_' . $question_id . '" class="spinner spin"></div>' . "\n";

$html .= '</div>' . "\n";

$html .= '<div ' . "\n";
$html .= 'id="' . esc_attr($question_id) . '" ' . "\n";
$html .= 'user_id="' . esc_attr($single_quesiton_sub_html[5]) . '" ' . "\n";
$html .= 'class="likes ' . esc_attr($single_quesiton_sub_html[1]) . '" ' . "\n";
$html .= 'style="' . esc_attr(is_user_logged_in() ? '' : 'cursor: wait; pointer-events: none;') . '"' . "\n";
$html .= '>' . "\n";

$unlike_img_url = plugin_dir_url(__FILE__) . 'assets/like.png';
$html .= sprintf(
    '<span class="unlike-img" style="display:inline-block; width:20px; height:20px; background-image:url(%s); background-size:cover;" aria-label="%s" role="img"></span>',
    esc_url($unlike_img_url),
    esc_attr__('like', 'bc-forum')
);

$like_img_url = plugin_dir_url(__FILE__) . 'assets/filled-like.png';
$html .= sprintf(
    '<span class="like-img" style="display:inline-block; width:20px; height:20px; background-image:url(%s); background-size:cover;" aria-label="%s" role="img"></span>',
    esc_url($like_img_url),
    esc_attr__('like', 'bc-forum')
);

$html .= '<p class="count_likes">' . "\n";
$html .=  $single_quesiton_sub_html[2] . ' ' . 'Likes'; 
$html .= '</p>' . "\n";
$html .= '</div>' . "\n";
$question_createdDate = gmdate('F j, Y, g:i A', strtotime($question->created_at));
$html .= '<div class="auth-details">' . "\n";
$html .= '<p>Posted by: ' . esc_html($single_quesiton_sub_html[6]) . ', ' . esc_html($question_createdDate) . '</p>' . "\n";

$html .= '</div>' . "\n";
$html .= '</div>' . "\n";

if (is_user_logged_in()) {
    $html .= '<div class="comment-box">' . "\n";
    $html .= '<div id="spinner-comment" class="spinner spin">' . "\n";
    $html .= '</div>' . "\n";
    $html .= '<form class="comment-form" method="post">' . "\n";
    $html .= '<input type="hidden" name="question_id" value="' . esc_attr($question_id) . '">' . "\n";
    $html .= '<textarea name="answer" id="comment" rows="2" cols="30" maxlength="150" placeholder="Write your comment here..." required></textarea>' . "\n";
    $html .= '<div class="error-message ">';
    $html .= 'Comments Field is Mandatory'; 
    $html .= '</div>' . "\n";
    $html .= '<button class="submit">' . 'Comment'. '</button>' . "\n";
    $html .= '</form>' . "\n";
    $html .= '</div>' . "\n";
}

$html .= '<div id="' . esc_attr($question_id) . '" class="reply-answers">' . "\n";
$html .=  $this->bcforum_question_answers($question_id); // Make sure this function echoes or returns HTML
$html .= '</div>' . "\n";

$html .='</div>' . "\n";
$html .='</div>' . "\n";
$html .='</div>' . "\n";

// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
return wp_kses($html, $this->allowed_tags);
} 

 public function bcforum_question_archive_list($atts) {
    ob_start();
    // Output the form
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo $this->question_form_shortcode();

    global $wpdb;
    $current_user_id = get_current_user_id();
    $current_page_id = get_the_ID();

    // Create a unique cache key for this page and user
    $cache_key = 'bcforum_question_archive_list_' . $current_page_id . '_' . $current_user_id;
    $cache_group = 'bcforum_question_archive';

    // Check cache
    $cached_output = wp_cache_get($cache_key, $cache_group);
    if ($cached_output !== false) {
        echo wp_kses($cached_output, $this->allowed_tags);
        return ob_get_clean();
    }
    // Fetch the forum ID for the current page
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $forum_id = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}bc_forums WHERE page_id = %d",
            $current_page_id
        )
    );

    $output = '';

    if ($forum_id) {
        // Fetch questions: approved OR by current user
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $questions = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}questions 
                 WHERE (approved = 1 OR user_id = %d) 
                 AND forum_id = %d 
                 ORDER BY created_at DESC",
                $current_user_id,
                $forum_id
            )
        );

        if (!empty($questions)) {
            $output .= $this->generate_question_list($questions);
        } else {
            $output .= '<p>No Questions Found.</p>';
        }
    } else {
        $output .= '<p>No Forum Found for this Page.</p>';
    }

    // Cache the generated HTML for 1 hour
    wp_cache_set($cache_key, $output, $cache_group, 3600);

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo $output;
    return ob_get_clean();
}
    public function generate_question_list($questions) {
        ob_start();?>
<div class="question-list">
    <?php foreach ($questions as $question) : ?>
    <?php 
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                  echo $this->single_question_html($question); 
                  ?>
    <?php endforeach;?>
</div>
<?php
        return ob_get_clean();
    }

    public function bcforum_question_answers_php($question_id,$limit,$offset,$exclude_ids){
    global $wpdb;
    $current_user_id = get_current_user_id();    
    // Generate a unique cache key
    $cache_key = 'answers_q_' . $question_id . '_o_' . $offset . '_l_' . $limit . '_e_' . md5(json_encode($exclude_ids));
    $cache_group = 'bc_forum_answers';
    // Try to get cached content
    $cached_output = wp_cache_get($cache_key, $cache_group);
    if ($cached_output !== false) {
        echo wp_kses($cached_output,$allowed_tags);
        return;
    }
    if(count($exclude_ids)>0){
        $exclude_ids_str = implode(',', array_map('intval', $exclude_ids));
        // Query with exclusion
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $answers = $wpdb->get_results($wpdb->prepare("
            SELECT * 
            FROM {$wpdb->prefix}answers 
            WHERE question_id = %d 
            AND parent = 0 
            AND approved = 1
            AND id NOT IN (%d) 
            ORDER BY question_id DESC 
            LIMIT %d OFFSET %d",$exclude_ids_str, $question_id, $limit, $offset));
            
        }else{
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $answers = $wpdb->get_results($wpdb->prepare("
            SELECT * 
            FROM {$wpdb->prefix}answers 
            WHERE question_id = %d 
            AND parent = 0 
            AND (approved = 1 OR user_id = %d) 
            ORDER BY question_id DESC 
            LIMIT %d OFFSET %d", $question_id,$current_user_id, $limit, $offset));
        }
        wp_cache_set($cache_key, $cache_group, 3600);
        return $answers;
    
    }

    public function bcforum_question_answers($question_id, $limit = 3, $offset = 0, $exclude_ids = []) {
        global $wpdb;
    
        $cache_key = 'answers_q_' . $question_id . '_o_' . $offset . '_l_' . $limit . '_e_' . md5(json_encode($exclude_ids));
        $cache_group = 'bc_forum_answers';
    
        $cached_output = wp_cache_get($cache_key, $cache_group);
        if ($cached_output !== false) {
            echo wp_kses($cached_output, $this->allowed_tags);
            return;
        }
    
        $answers = $this->bcforum_question_answers_php($question_id, $limit, $offset, $exclude_ids);
        $html = '';
    
        if (!empty($answers)) {
            $html .= $this->bcforum_generateComments($answers, $question_id);
            // Check for more answers
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $total_answers = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}answers WHERE question_id = %d AND parent = 0",
                $question_id
            ));
    
            if ($total_answers > ($offset + $limit) && $offset == 0) {
                
                $html .= '<div class="load-more-section">' . "\n";
                $html .= '  <div class="load-more-answers"></div>' . "\n";
                $html .= '  <div class="more-btn">' . "\n";
                $html .= '    <button class="load-more-btn" data-question-id="' . esc_attr($question_id) . '" data-page="1">' . "\n";
                $html .= '      <span>More</span><span class="dashicons dashicons-arrow-down-alt2"></span>' . "\n";
                $html .= '    </button>' . "\n";
                $html .= '  </div>' . "\n";
                $html .= '</div>' . "\n";
            }
        }    
        wp_cache_set($cache_key, $html, $cache_group);    
        return wp_kses($html, $this->allowed_tags);
    }

    public function bcforum_answer_html_php($answer){

        // Retrieve author information
        $author_id = $answer->user_id;
        $user_info = get_userdata($author_id);
        $user_meta = get_user_meta($author_id);
        $user_firstname = isset($user_info->first_name) ? $user_info->first_name : '';
        $user_lastname = isset($user_info->last_name) ? $user_info->last_name : '';
        $user_nickname = isset($user_meta['nickname'][0]) ? $user_meta['nickname'][0] : '';
        
        // Define the initials
        if (!empty($user_firstname) || !empty($user_lastname)) {
            $initials = substr($user_firstname, 0, 1) . substr($user_lastname, 0, 1);
        } elseif (!empty($user_nickname)) {
            $initials = substr($user_nickname, 0, 2);
        } else {
            $initials = '';
        }
         // Retrieve and format the created time
        $created_time = isset($answer->created_at) ? gmdate('F j, Y, g:i A', strtotime($answer->created_at)) : '';

        $avatar_image = get_avatar_url($author_id);
        $avatar_image_explode = explode("?", $avatar_image);
        $avatar_image_explode1 = explode("/", $avatar_image_explode[0]); 

        return [$initials,$author_id,$created_time,$user_nickname];

    }
    
    public function bcforum_answer_html($answer, $question_id, $level = 1) {        
        $answer_sub_html = $this->bcforum_answer_html_php($answer);
    
        $level_class = 'level1class';
        if ($level == 2) {
            $level_class = 'level2class';
        } elseif ($level >= 3) {
            $level_class = 'level3class';
        }
    
        $html = '';
        $html .= '<ul class="answer-list ' . esc_attr($level_class) . '">' . "\n";
        $html .= '<li class="answer-item">' . "\n";
        $html .= '<div class="answer">' . "\n";
        $html .= '<div class="answers ' . (is_user_logged_in() ? 'logged' : '') . '">' . "\n";
        $html .= '<div id="spinner-reply" class="spinner spin"></div>' . "\n";
        $html .= '<div class="answer-content">' . "\n";
    
        // Avatar or initials
        $html .= '<div class="question-avatar">' . "\n";
        if (false) { // Replace with actual condition if needed
            $html .= wp_get_attachment_image($answer_sub_html[1], array(30, 30), "", array("class" => "img-responsive"));
        } else {
            if (!empty($answer_sub_html[0])) {
                $html .= '<div class="avatar-initials">' . esc_html($answer_sub_html[0]) . '</div>' . "\n";
            }
        }
        $html .= '</div>' . "\n";
    
        // Answer description
        $html .= '<div class="description">' . "\n";
        $html .= '<span class="sub-comment-content"><p>' . esc_html(ucfirst(wp_trim_words($answer->answer, 25, '...'))) . '</p></span>' . "\n";
        if ($answer->approved == 0) {
            $html .= '<abbr title="' . esc_attr__('This answer is waiting for approval.', 'bc-forum') . '" class="no-dotted-line">' . "\n";
            $html .= '<span style="font-size: 11px; color: #feb104; border: 1px solid; padding: 2px 4px; border-radius: 5px; bottom: 2px; position: relative;">' . esc_html__('Approval Pending..', 'bc-forum') . '</span>' . "\n";
            $html .= '</abbr>' . "\n";
        }
        $html .= '</div>' . "\n"; // end description
    
        $html .= '</div>' . "\n"; // end answer-content
    
        // Reply toggle if user logged in
        if (is_user_logged_in()) {
            $html .= '<div class="comment-toggle">' . "\n";
            $html .= '<span class="dashicons dashicons-admin-comments"></span>' . "\n";
            $html .= '<span>' . esc_html__('Reply..', 'bc-forum') . '</span>' . "\n";
            $html .= '</div>' . "\n";
        }
        $html .= '</div>' . "\n"; // end answers

        // Author details
        $html .= '<div class="author-details">' . "\n";
        // $html .= '<p>Posted by: ' . esc_html($answer->author_name) . ', ' . esc_html($answer_sub_html[2]) . '</p>' . "\n";
        $html .= '<p>Posted by: ' . esc_html($answer_sub_html[3]) . ', ' . esc_html($answer_sub_html[2]) . '</p>' . "\n";
        $html .= '</div>' . "\n";
    
        // Reply form
        if (is_user_logged_in()) {
            $html .= '<div class="comment-box">' . "\n";
            $html .= '<form class="reply-form" method="post">' . "\n";
            $html .= '<input type="hidden" name="question_id" value="' . esc_attr($question_id) . '">' . "\n";
            $html .= '<input type="hidden" name="parent_answer_id" value="' . esc_attr($answer->id) . '">' . "\n";
            $html .= '<input type="hidden" name="parent_answer_level" value="' . esc_attr($answer->level) . '">' . "\n";
            $html .= '<textarea name="answer" rows="2" cols="30" placeholder="Write your reply here..." required></textarea>' . "\n";
            $html .= '<div class="error-message">' . esc_html__('Please write your comment..', 'bc-forum') . '</div>' . "\n";
            $html .= '<button class="submit">' . esc_html__('Comment', 'bc-forum') . '</button>' . "\n";
            $html .= '</form>' . "\n";
            $html .= '</div>' . "\n";
        }
    
        $html .= '</div>' . "\n"; // end answer
        $html .= '</li>' . "\n";
        $html .= '</ul>' . "\n";
    
        return wp_kses($html, $this->allowed_tags);
    }

public function bcforum_getlevel_answers($panswer, $question_id) {
    global $wpdb;
    $current_user_id = get_current_user_id();

    $cache_key = 'level_answers_q' . $question_id . '_p' . $panswer->id . '_u' . $current_user_id;
    $cache_group = 'bc_forum_answers';

    $cached_output = wp_cache_get($cache_key, $cache_group);
    if ($cached_output !== false) {
        return wp_kses($cached_output, $this->allowed_tags);
    }

    $html = '';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $child_answers = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}answers 
             WHERE question_id = %d AND parent != 0 AND parent = %d 
             AND (approved = 1 OR user_id = %d) 
             ORDER BY id ASC",
            $question_id,
            $panswer->id,
            $current_user_id
        )
    );

    if (!empty($child_answers)) {
        foreach ($child_answers as $canswer) {
            // Append answer HTML
            $html .= $this->bcforum_answer_html($canswer, $question_id, $canswer->level);

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $sub_level_answers = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}answers 
                     WHERE question_id = %d AND parent = %d 
                     AND (approved = 1 OR user_id = %d) 
                     ORDER BY id ASC",
                    $question_id,
                    $canswer->id,
                    $current_user_id
                )
            );

            foreach ($sub_level_answers as $sla) {
                // Append nested sub-level answer
                $html .= $this->bcforum_answer_html($sla, $question_id, $sla->level);
                $html .= $this->bcforum_getlevel_answers($sla, $question_id); // Recursive
            }
        }
    }

    // Cache and return
    wp_cache_set($cache_key, $html, $cache_group, HOUR_IN_SECONDS);
    return wp_kses($html, $this->allowed_tags);
}

    public function bcforum_generateComments($answers, $question_id = '', $parent = 0) {
        global $wpdb;
    
        $html = '';    
        foreach ($answers as $panswer) {
            $html .= $this->bcforum_answer_html($panswer, $question_id);         
            $html .= $this->bcforum_getlevel_answers($panswer, $question_id);
        }
    
        return $html;
    }    

    // Function to handle loading more answers
    public function bcforum_loadmore_answers() {
        if ( ! check_ajax_referer( 'bc-forum-nonce', 'security', false ) ) {
            wp_send_json_error( [ 'message' => 'Invalid nonce' ] );
            return;
        }
        // Retrieve necessary data from the AJAX request
        $question_id  = isset($_POST['question_id']) ? intval($_POST['question_id']) : 0;
        $page         = isset($_POST['page']) ? sanitize_text_field(wp_unslash($_POST['page'])) : '';
        $exclude_ids  = isset($_POST['exclude_ids']) && is_array($_POST['exclude_ids']) 
                        ? array_map('intval', wp_unslash($_POST['exclude_ids'])) 
                        : [];
    
        $per_page = 3;
        $offset = ($page - 1) * $per_page;
        
    
        // Generate the HTML using question_answers (it must return a string)
        if (!empty($exclude_ids)) {
            $html = $this->bcforum_question_answers($question_id, $per_page, $offset, $exclude_ids);
        } else {
            $html = $this->bcforum_question_answers($question_id, $per_page, $offset);
        }
    
        // Return the HTML as a JSON response
        wp_send_json($html);
        wp_die();
    }

    public function bcforum_submit_comment() {
    if (!check_ajax_referer('bc-forum-nonce', 'security', false)) {
        wp_die();
    }

    global $wpdb;
    
    // Sanitize inputs
    $data = isset($_POST['data']) && is_array($_POST['data']) ? array_map('sanitize_text_field', wp_unslash($_POST['data'])) : array();
    $question_id = intval($data['question_id']);        
    $parent = intval($data['parent']);    
    $answer = sanitize_text_field($data['answer']);

    // Get parent level with caching
    $cache_key = 'answer_level_' . $parent;
    $parent_level = wp_cache_get($cache_key);
    
    if (false === $parent_level) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $parent_level = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT level FROM {$wpdb->prefix}answers WHERE id = %d",
                $parent
            )
        );
        wp_cache_set($cache_key, $parent_level, '', 3600); // Cache for 1 hour
    }
    
    $level = $parent_level + 1;

    // Get user info
    $user_id = get_current_user_id();
    $user_meta = get_user_meta($user_id);
    $first_name = $user_meta['first_name'][0] ?? '';
    $last_name = $user_meta['last_name'][0] ?? '';
    $author_name = trim($first_name . ' ' . $last_name);

    $current_user = wp_get_current_user();
    if (empty($author_name)) {
        $author_name = $current_user->display_name;
    }

    $created_at = current_time('mysql');

    // Insert new answer
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $result = $wpdb->insert(
        $wpdb->prefix . 'answers',
        array(
            'question_id' => $question_id,
            'parent' => $parent,
            'answer' => $answer,
            'level' => $level, 
            'user_id' => $user_id,
            'author_name' => $author_name,
            'created_at' => $created_at
        ),
        array(
            '%d',
            '%d',
            '%s',
            '%d', 
            '%d',
            '%s',
            '%s'
        )
    );
    // Clear cached count for this question
    $count_cache_key = 'answers_count_' . $question_id;
    wp_cache_delete($count_cache_key);

    // Get answers count with caching
    $answers_count = wp_cache_get($count_cache_key);
    
    if (false === $answers_count) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $answers_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}answers WHERE question_id = %d", 
            $question_id
        ));
        wp_cache_set($count_cache_key, $answers_count, '', 3600);
    }

    $inserted_id = $wpdb->insert_id;

    // Get the new answer with caching
    $answer_cache_key = 'answer_' . $inserted_id;
    $answer = wp_cache_get($answer_cache_key);
    
    if (false === $answer) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $answer = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}answers WHERE id = %d", 
            $inserted_id
        ));
        wp_cache_set($answer_cache_key, $answer, '', 3600);
    }

    
    $answer_html = $this->bcforum_answer_html($answer, $answer->question_id, $answer->level);

    $response = array(
        'answers_count' => $answers_count,
        'answer_html' => $answer_html
    );
    wp_send_json($response);
    wp_die();
}


    public function bcforum_load_assets()
    {
        wp_enqueue_script('jquery');       
        wp_enqueue_style(
            'bcforum-styles',
            plugin_dir_url(__FILE__) . 'bc-forum.css',
            array(),
            filemtime(plugin_dir_path(__FILE__) . 'bc-forum.css')
        );

        wp_enqueue_style('dashicons');
        wp_enqueue_script(
        'bc-forum', 
        plugin_dir_url(__FILE__) . 'bc-forum.js',
        array('wp-blocks', 'wp-element', 'wp-components', 'wp-editor', 'wp-api'), 
        '1.0', 
        true);

        wp_localize_script('bc-forum', 'bcforum_ajax_object', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonceSecurity'  => wp_create_nonce( 'bc-forum-nonce' ),       
           
        )); 
    }
    public function bcforum_load_assets_backend()
    {
    wp_enqueue_script(
        'bc-forum-block-editor-script',
        plugins_url( 'gutenberg.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-editor', 'wp-api-fetch' ,'jquery'),
        filemtime( plugin_dir_path( __FILE__ ) . 'gutenberg.js' ),
        true
    );

    wp_localize_script('bc-forum-block-editor-script', 'bcforum_ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonceSecurity'  => wp_create_nonce( 'bc-forum-nonce' ),       

    ));
    }

    public function bcforum_save_question() {
    if (!check_ajax_referer('bc-forum-nonce', 'security', false)) {
        wp_die();
    }

    global $wpdb;
    $questions_table = $wpdb->prefix . 'questions';
    
    $data = isset($_REQUEST['data']) && is_array($_REQUEST['data']) ? array_map('sanitize_text_field', wp_unslash($_REQUEST['data'])) : array();
    $question_title = sanitize_text_field($data['question_title']);
    $description = sanitize_textarea_field($data['question_content']);
    $current_page_id = sanitize_text_field($data['current_page_id']);

    // Get user info
    $user_id = get_current_user_id();
    $user_meta = get_user_meta($user_id);
    $first_name = $user_meta['first_name'][0] ?? '';
    $last_name = $user_meta['last_name'][0] ?? '';
    $author_name = trim($first_name . ' ' . $last_name);
    $user_nickname = $user_meta['nickname'][0] ?? '';
    
    if (empty($author_name)) {
        $author_name = $user_nickname;
    }

    // Get forum ID with caching
    $forum_cache_key = 'forum_id_for_page_' . $current_page_id;
    $forum_id = wp_cache_get($forum_cache_key);
    
    if (false === $forum_id) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $forum_id = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}bc_forums WHERE page_id = %d",
                $current_page_id
            )
        );
        wp_cache_set($forum_cache_key, $forum_id, '', 3600); // Cache for 1 hour
    }

    // Insert the new question
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $inserted = $wpdb->insert(
        $questions_table,
        array(
            'question_title' => $question_title,
            'description' => $description,
            'user_id' => $user_id,
            'author' => $author_name,
            'forum_id' => $forum_id,
            'created_at' => current_time('mysql')
        )
    );

    if ($inserted) {
        $question_id = $wpdb->insert_id;
        
        // Clear any cached questions list for this forum
        wp_cache_delete('questions_for_forum_' . $forum_id);
        
        // Get the new question with caching
        $question_cache_key = 'question_' . $question_id;
        $new_question = wp_cache_get($question_cache_key);
        
        if (false === $new_question) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $new_question = $wpdb->get_row(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}questions WHERE id = %d",
                    $question_id
                )
            );
            wp_cache_set($question_cache_key, $new_question, '', 3600);
        }

        if ($new_question) {
            wp_send_json(array(
                'success' => true,
                'id' => $question_id,
                'question_title' => $new_question->question_title,
                'description' => $new_question->description,
                'author' => $new_question->author,
                'forum_id' => $new_question->forum_id,
                'created_at' => $new_question->created_at,
            ));
        } else {
            wp_send_json(array('success' => false, 'error' => 'Failed to retrieve the new question.'));
        }
    } else {
        wp_send_json(array('success' => false, 'error' => 'Failed to insert the question.'));
    }
}

    function bcforum_questions_table() {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        // Table name for storing questions
        $questions_table = $wpdb->prefix . 'questions';
        // SQL query to create questions table
        $sql_questions = "CREATE TABLE IF NOT EXISTS $questions_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            question_title text NOT NULL,
            description text NOT NULL,
            user_id bigint(20) unsigned NOT NULL,
            author varchar(255) NOT NULL,
            likes longtext NOT NULL,
            approved tinyint(1) NOT NULL DEFAULT 0,
            forum_id mediumint(9) NOT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            FOREIGN KEY (user_id) REFERENCES {$wpdb->users}(ID),
            FOREIGN KEY (forum_id) REFERENCES {$wpdb->prefix}bc_forums(id) ON DELETE CASCADE

        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        
        dbDelta($sql_questions);
    }

    function bcforum_answers_table() {
    global $wpdb;
    $answers_table = $wpdb->prefix . 'answers';

    // Cache key for tracking if table exists
    $table_cache_key = 'answers_table_exists';
    
    // Check cache first to avoid unnecessary checks
    $table_exists = wp_cache_get($table_cache_key);
    
    if (false === $table_exists) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $table_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SHOW TABLES LIKE %s",
                $wpdb->prefix . 'answers'
            )
        ) !== null;
        
        wp_cache_set($table_cache_key, $table_exists, '', 86400); // Cache for 24 hours
    }

    // Only proceed if table doesn't exist or we need to check columns
    if (!$table_exists || get_option('answers_table_version') < 2) {
        $charset_collate = $wpdb->get_charset_collate();
        $questions_table = $wpdb->prefix . 'questions';        
        $answers_table = $wpdb->prefix . 'answers';
        
        $sql_answers = "CREATE TABLE IF NOT EXISTS $answers_table (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            question_id mediumint(9) NOT NULL,
            parent mediumint(9) DEFAULT 0,
            answer longtext NOT NULL,
            user_id bigint(20) unsigned NOT NULL,
            level int(11) NOT NULL DEFAULT 0,
            author_name varchar(255) NOT NULL, 
            approved tinyint(1) NOT NULL DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            FOREIGN KEY (question_id) REFERENCES $questions_table(id) ON DELETE CASCADE,
            FOREIGN KEY (user_id) REFERENCES {$wpdb->users}(ID) ON DELETE CASCADE
        ) $charset_collate;";
            
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql_answers);

        // Cache column check results
        $columns_cache_key = 'answers_table_columns';
        $columns = wp_cache_get($columns_cache_key);
        
        if (false === $columns) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $columns = $wpdb->get_col("DESC  {$wpdb->prefix}answers", 0);
            wp_cache_set($columns_cache_key, $columns, '', 86400);
        }

        // Check for missing columns
        $missing_columns = array();
        if (!in_array('author_name', $columns)) {
            $missing_columns[] = 'author_name varchar(255) NOT NULL';
        }
        if (!in_array('created_at', $columns)) {
            $missing_columns[] = 'created_at datetime DEFAULT CURRENT_TIMESTAMP';
        }

        // Add all missing columns in a single query if possible
        if (!empty($missing_columns)) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange          
            $wpdb->query("ALTER TABLE %i ADD COLUMN ",$answers_table . "" . implode(', ADD COLUMN ', $missing_columns));
            
            // Clear columns cache after modification
            wp_cache_delete($columns_cache_key);
        }
        // Clear table existence cache since we just created/modified it
        wp_cache_delete($table_cache_key);
    }
}

    public function bcforum_create_table(){
        global $wpdb;
        $table_name = $wpdb->prefix . 'bc_forums';
        
        $charset_collate = $wpdb->get_charset_collate();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            title text NOT NULL,
            page_id mediumint(9) NOT NULL DEFAULT 0,
            PRIMARY KEY  (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

    }
}

new BCForum();