<?php
// AJAX handler to fetch full post content
function rswpthemes_awt_fetch_full_post() {
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $category = isset($_POST['category']) ? intval($_POST['category']) : '';
    $author = isset($_POST['author']) ? intval($_POST['author']) : '';
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $sort_order = isset($_POST['sort_order']) ? sanitize_text_field($_POST['sort_order']) : '';

    if ($post_id <= 0) {
        wp_send_json_error(array('message' => 'Invalid post ID.'));
        wp_die();
    }

    $post = get_post($post_id);
    if (!$post || $post->post_status !== 'publish') {
        wp_send_json_error(array('message' => 'Post not found or not published.'));
        wp_die();
    }

    // Build the query arguments to fetch the current post list (same as the main query)
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1, // Get all posts to determine next/previous
        'post_status' => 'publish',
        'fields' => 'ids', // Only fetch IDs for efficiency
    );

    // Add category filter
    if (!empty($category)) {
        $args['cat'] = $category;
    }

    // Add author filter
    if (!empty($author)) {
        $args['author'] = $author;
    }

    // Add search filter
    if (!empty($search)) {
        $args['s'] = '';
        add_filter('posts_where', function ($where) use ($search) {
            global $wpdb;
            $search_term = $wpdb->esc_like($search);
            $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_title LIKE %s", "%{$search_term}%");
            return $where;
        });
    }

    // Add sorting
    if (!empty($sort_order)) {
        if ($sort_order === 'title_asc') {
            $args['orderby'] = 'title';
            $args['order'] = 'ASC';
        } elseif ($sort_order === 'title_desc') {
            $args['orderby'] = 'title';
            $args['order'] = 'DESC';
        } elseif ($sort_order === 'date_asc') {
            $args['orderby'] = 'date';
            $args['order'] = 'ASC';
        } elseif ($sort_order === 'date_desc') {
            $args['orderby'] = 'date';
            $args['order'] = 'DESC';
        }
    }

    // Get the list of post IDs in the current query
    $query = new WP_Query($args);
    $post_ids = $query->posts;

    // Find the current post's position in the list
    $current_index = array_search($post_id, $post_ids);
    $prev_post_id = ($current_index > 0) ? $post_ids[$current_index - 1] : 0;
    $next_post_id = ($current_index < count($post_ids) - 1) ? $post_ids[$current_index + 1] : 0;

    // Clean up search filter
    if (!empty($search)) {
        remove_filter('posts_where', function () {}, 10);
    }

    // Get the featured image
    $featured_image = get_the_post_thumbnail_url($post_id, 'large') ?: '';

    // Get the categories
    $categories = get_the_category($post_id);
    $category_names = array_map(function($cat) {
        return '<span class="filter-category" data-category-id="' . esc_attr($cat->term_id) . '">' . esc_html($cat->name) . '</span>';
    }, $categories);
    $category_list = implode(', ', $category_names);
    $category_ids = wp_list_pluck($categories, 'term_id');

    // Get author info
    $author_id = $post->post_author;
    $author_name = get_the_author_meta('display_name', $author_id);
    $post_date = get_the_date('M j, Y', $post_id);
    $read_time = '3 min read';

    // Prepare the post content
    $content = apply_filters('the_content', $post->post_content);

    // Fetch related posts (e.g., from the same category, excluding the current post)
    $related_args = array(
        'post_type' => 'post',
        'posts_per_page' => 3, // Show 3 related posts
        'post_status' => 'publish',
        'post__not_in' => array($post_id), // Exclude the current post
        'category__in' => $category_ids, // Match categories
        'orderby' => 'rand', // Random order for variety
    );

    $related_query = new WP_Query($related_args);
    $related_posts_html = '';
    if ($related_query->have_posts()) {
        ob_start();
        ?>
        <div class="rswpthemes-awt-post-popup-related-posts">
            <h3>Related Posts</h3>
            <div class="related-posts-list">
                <?php while ($related_query->have_posts()) : $related_query->the_post(); ?>
                    <div class="related-post">
                        <a href="#" class="related-post-link" data-post-id="<?php echo esc_attr(get_the_ID()); ?>">
                            <?php the_title(); ?>
                        </a>
                    </div>
                <?php endwhile; ?>
            </div>
        </div>
        <?php
        $related_posts_html = ob_get_clean();
        wp_reset_postdata();
    }

    // Build the HTML for the popup
    ob_start();
    ?>
    <div class="rswpthemes-awt-post-popup-navigation">
        <button class="rswpthemes-awt-post-popup-prev <?php echo $prev_post_id ? '' : 'disabled'; ?>" data-post-id="<?php echo esc_attr($prev_post_id); ?>" aria-label="Previous Post">
            &larr; Previous
        </button>
        <button class="rswpthemes-awt-post-popup-next <?php echo $next_post_id ? '' : 'disabled'; ?>" data-post-id="<?php echo esc_attr($next_post_id); ?>" aria-label="Next Post">
            Next &rarr;
        </button>
    </div>
    <div class="rswpthemes-awt-post-popup-header">
        <?php if ($featured_image) : ?>
            <div class="rswpthemes-awt-post-popup-image" style="background-image: url('<?php echo esc_url($featured_image); ?>');"></div>
        <?php endif; ?>
        <h1 class="rswpthemes-awt-post-popup-title"><?php echo esc_html($post->post_title); ?></h1>
        <div class="rswpthemes-awt-post-popup-meta">
            <span class="category"><?php echo wp_kses_post($category_list); ?></span>
            <span class="author filter-author" data-author-id="<?php echo esc_attr($author_id); ?>">
                <?php echo esc_html($author_name); ?>
            </span>
            <span class="date"><?php echo esc_html($post_date); ?></span>
            <span class="read-time"><?php echo esc_html($read_time); ?></span>
        </div>
    </div>
    <div class="rswpthemes-awt-post-popup-content-body">
        <div class="rswpthemes-awt-post-popup-content-inner">
        	<?php echo wp_kses_post($content); ?>
        </div>
        <div class="rswpthemes-awt-related-post-wrapper">
        	<?php echo $related_posts_html; // Add related posts at the end ?>
        </div>
    </div>
    <?php
    $html = ob_get_clean();

    wp_send_json_success(array('html' => $html));
    wp_die();
}
add_action('wp_ajax_rswpthemes_awt_fetch_full_post', 'rswpthemes_awt_fetch_full_post');
add_action('wp_ajax_nopriv_rswpthemes_awt_fetch_full_post', 'rswpthemes_awt_fetch_full_post');